repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Core/Portable/SpecialMembers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class SpecialMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static SpecialMembers() { byte[] initializationBytes = new byte[] { // System_String__CtorSZArrayChar (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_String__ConcatStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Length (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Chars (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Format (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__Substring (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Double__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Double, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Single__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Single, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Delegate__Combine (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__Remove (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Decimal__Zero (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__MinusOne (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__One (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__CtorInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__CtorUInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__CtorUInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__CtorSingle (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Decimal__CtorDouble (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__CtorInt32Int32Int32BooleanByte (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Addition (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Subtraction (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Multiply (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Division (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Modulus (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_UnaryNegation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Increment (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Decrement (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__NegateDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__RemainderDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__AddDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__SubtractDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__MultiplyDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__DivideDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__ModuloDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__CompareDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Implicit_FromByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Implicit_FromChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Decimal__op_Implicit_FromInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Decimal__op_Implicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__op_Implicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__op_Implicit_FromSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // System_Decimal__op_Implicit_FromUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // System_Decimal__op_Implicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__op_Implicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__op_Explicit_ToByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_FromDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__op_Explicit_FromSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_DateTime__MinValue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Field Signature // System_DateTime__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_DateTime__CompareDateTimeDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_Collections_IEnumerable__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_IEnumerator, // System_Collections_IEnumerator__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_IEnumerator__Reset (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Collections_Generic_IEnumerable_T__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerator_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_IDisposable__Dispose (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_IDisposable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Array__Length (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__LongLength (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Array__GetLowerBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__GetUpperBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__EqualsObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__ToString (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Object__ReferenceEquals (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_IntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_IntPtr__op_Explicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_IntPtr__op_Explicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_UIntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_UIntPtr__op_Explicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_UIntPtr__op_Explicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Nullable_T_GetValueOrDefault (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_Value (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_HasValue (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Nullable_T__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Implicit_FromT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Explicit_ToT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type }; string[] allNames = new string[(int)SpecialMember.Count] { ".ctor", // System_String__CtorSZArrayChar "Concat", // System_String__ConcatStringString "Concat", // System_String__ConcatStringStringString "Concat", // System_String__ConcatStringStringStringString "Concat", // System_String__ConcatStringArray "Concat", // System_String__ConcatObject "Concat", // System_String__ConcatObjectObject "Concat", // System_String__ConcatObjectObjectObject "Concat", // System_String__ConcatObjectArray "op_Equality", // System_String__op_Equality "op_Inequality", // System_String__op_Inequality "get_Length", // System_String__Length "get_Chars", // System_String__Chars "Format", // System_String__Format "Substring", // System_String__Substring "IsNaN", // System_Double__IsNaN "IsNaN", // System_Single__IsNaN "Combine", // System_Delegate__Combine "Remove", // System_Delegate__Remove "op_Equality", // System_Delegate__op_Equality "op_Inequality", // System_Delegate__op_Inequality "Zero", // System_Decimal__Zero "MinusOne", // System_Decimal__MinusOne "One", // System_Decimal__One ".ctor", // System_Decimal__CtorInt32 ".ctor", // System_Decimal__CtorUInt32 ".ctor", // System_Decimal__CtorInt64 ".ctor", // System_Decimal__CtorUInt64 ".ctor", // System_Decimal__CtorSingle ".ctor", // System_Decimal__CtorDouble ".ctor", // System_Decimal__CtorInt32Int32Int32BooleanByte "op_Addition", // System_Decimal__op_Addition "op_Subtraction", // System_Decimal__op_Subtraction "op_Multiply", // System_Decimal__op_Multiply "op_Division", // System_Decimal__op_Division "op_Modulus", // System_Decimal__op_Modulus "op_UnaryNegation", // System_Decimal__op_UnaryNegation "op_Increment", // System_Decimal__op_Increment "op_Decrement", // System_Decimal__op_Decrement "Negate", // System_Decimal__NegateDecimal "Remainder", // System_Decimal__RemainderDecimalDecimal "Add", // System_Decimal__AddDecimalDecimal "Subtract", // System_Decimal__SubtractDecimalDecimal "Multiply", // System_Decimal__MultiplyDecimalDecimal "Divide", // System_Decimal__DivideDecimalDecimal "Remainder", // System_Decimal__ModuloDecimalDecimal "Compare", // System_Decimal__CompareDecimalDecimal "op_Equality", // System_Decimal__op_Equality "op_Inequality", // System_Decimal__op_Inequality "op_GreaterThan", // System_Decimal__op_GreaterThan "op_GreaterThanOrEqual", // System_Decimal__op_GreaterThanOrEqual "op_LessThan", // System_Decimal__op_LessThan "op_LessThanOrEqual", // System_Decimal__op_LessThanOrEqual "op_Implicit", // System_Decimal__op_Implicit_FromByte "op_Implicit", // System_Decimal__op_Implicit_FromChar "op_Implicit", // System_Decimal__op_Implicit_FromInt16 "op_Implicit", // System_Decimal__op_Implicit_FromInt32 "op_Implicit", // System_Decimal__op_Implicit_FromInt64 "op_Implicit", // System_Decimal__op_Implicit_FromSByte "op_Implicit", // System_Decimal__op_Implicit_FromUInt16 "op_Implicit", // System_Decimal__op_Implicit_FromUInt32 "op_Implicit", // System_Decimal__op_Implicit_FromUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToByte "op_Explicit", // System_Decimal__op_Explicit_ToUInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSByte "op_Explicit", // System_Decimal__op_Explicit_ToInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSingle "op_Explicit", // System_Decimal__op_Explicit_ToDouble "op_Explicit", // System_Decimal__op_Explicit_ToChar "op_Explicit", // System_Decimal__op_Explicit_ToUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToInt32 "op_Explicit", // System_Decimal__op_Explicit_ToUInt32 "op_Explicit", // System_Decimal__op_Explicit_ToInt64 "op_Explicit", // System_Decimal__op_Explicit_FromDouble "op_Explicit", // System_Decimal__op_Explicit_FromSingle "MinValue", // System_DateTime__MinValue ".ctor", // System_DateTime__CtorInt64 "Compare", // System_DateTime__CompareDateTimeDateTime "op_Equality", // System_DateTime__op_Equality "op_Inequality", // System_DateTime__op_Inequality "op_GreaterThan", // System_DateTime__op_GreaterThan "op_GreaterThanOrEqual", // System_DateTime__op_GreaterThanOrEqual "op_LessThan", // System_DateTime__op_LessThan "op_LessThanOrEqual", // System_DateTime__op_LessThanOrEqual "GetEnumerator", // System_Collections_IEnumerable__GetEnumerator "Current", // System_Collections_IEnumerator__Current "get_Current", // System_Collections_IEnumerator__get_Current "MoveNext", // System_Collections_IEnumerator__MoveNext "Reset", // System_Collections_IEnumerator__Reset "GetEnumerator", // System_Collections_Generic_IEnumerable_T__GetEnumerator "Current", // System_Collections_Generic_IEnumerator_T__Current "get_Current", // System_Collections_Generic_IEnumerator_T__get_Current "Dispose", // System_IDisposable__Dispose "Length", // System_Array__Length "LongLength", // System_Array__LongLength "GetLowerBound", // System_Array__GetLowerBound "GetUpperBound", // System_Array__GetUpperBound "GetHashCode", // System_Object__GetHashCode "Equals", // System_Object__Equals "Equals", // System_Object__EqualsObjectObject "ToString", // System_Object__ToString "ReferenceEquals", // System_Object__ReferenceEquals "op_Explicit", // System_IntPtr__op_Explicit_ToPointer "op_Explicit", // System_IntPtr__op_Explicit_ToInt32 "op_Explicit", // System_IntPtr__op_Explicit_ToInt64 "op_Explicit", // System_IntPtr__op_Explicit_FromPointer "op_Explicit", // System_IntPtr__op_Explicit_FromInt32 "op_Explicit", // System_IntPtr__op_Explicit_FromInt64 "op_Explicit", // System_UIntPtr__op_Explicit_ToPointer "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt64 "op_Explicit", // System_UIntPtr__op_Explicit_FromPointer "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt64 "GetValueOrDefault", // System_Nullable_T_GetValueOrDefault "get_Value", // System_Nullable_T_get_Value "get_HasValue", // System_Nullable_T_get_HasValue ".ctor", // System_Nullable_T__ctor "op_Implicit", // System_Nullable_T__op_Implicit_FromT "op_Explicit", // System_Nullable_T__op_Explicit_ToT "DefaultImplementationsOfInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces "UnmanagedSignatureCallingConvention", // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention "CovariantReturnsOfClasses", // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses ".ctor", // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(SpecialMember member) { return s_descriptors[(int)member]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Reflection.Metadata; using Microsoft.CodeAnalysis.RuntimeMembers; namespace Microsoft.CodeAnalysis { internal static class SpecialMembers { private static readonly ImmutableArray<MemberDescriptor> s_descriptors; static SpecialMembers() { byte[] initializationBytes = new byte[] { // System_String__CtorSZArrayChar (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_String__ConcatStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringStringStringString (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 4, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatStringArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__ConcatObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 3, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__ConcatObjectArray (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_String__Length (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Chars (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_String__Format (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, (byte)SignatureTypeCode.SZArray, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_String__Substring (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_String, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Return Type (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Double__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Double, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Single__IsNaN (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Single, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Delegate__Combine (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__Remove (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Delegate__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Delegate, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Delegate, // System_Decimal__Zero (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__MinusOne (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__One (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // Field Signature // System_Decimal__CtorInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__CtorUInt32 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__CtorUInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__CtorSingle (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_Decimal__CtorDouble (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__CtorInt32Int32Int32BooleanByte (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 5, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Addition (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Subtraction (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Multiply (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Division (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Modulus (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_UnaryNegation (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Increment (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Decrement (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__NegateDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__RemainderDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__AddDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__SubtractDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__MultiplyDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__DivideDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__ModuloDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__CompareDecimalDecimal (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Implicit_FromByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, // System_Decimal__op_Implicit_FromChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, // System_Decimal__op_Implicit_FromInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, // System_Decimal__op_Implicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Decimal__op_Implicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Decimal__op_Implicit_FromSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, // System_Decimal__op_Implicit_FromUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, // System_Decimal__op_Implicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_Decimal__op_Implicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Decimal__op_Explicit_ToByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Byte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSByte (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_SByte, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt16 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int16, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToChar (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Char, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, // System_Decimal__op_Explicit_FromDouble (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Double, // System_Decimal__op_Explicit_FromSingle (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Decimal, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Decimal, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Single, // System_DateTime__MinValue (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // Field Signature // System_DateTime__CtorInt64 (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_DateTime__CompareDateTimeDateTime (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Equality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_Inequality (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_GreaterThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThan (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_DateTime__op_LessThanOrEqual (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_DateTime, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_DateTime, // System_Collections_IEnumerable__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_IEnumerator, // System_Collections_IEnumerator__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Collections_IEnumerator__MoveNext (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Collections_IEnumerator__Reset (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_IEnumerator, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Collections_Generic_IEnumerable_T__GetEnumerator (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeInstance, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Collections_Generic_IEnumerator_T, 1, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__Current (byte)(MemberFlags.Property | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Collections_Generic_IEnumerator_T__get_Current (byte)(MemberFlags.PropertyGet | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Collections_Generic_IEnumerator_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_IDisposable__Dispose (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_IDisposable, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_Array__Length (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__LongLength (byte)MemberFlags.Property, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_Array__GetLowerBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Array__GetUpperBound (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Array, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__GetHashCode (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_Object__Equals (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__EqualsObjectObject (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_Object__ToString (byte)(MemberFlags.Method | MemberFlags.Virtual), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // System_Object__ReferenceEquals (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Object, // DeclaringTypeId 0, // Arity 2, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Object, // System_IntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_ToInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, // System_IntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_IntPtr__op_Explicit_FromInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int32, // System_IntPtr__op_Explicit_FromInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_IntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_IntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Int64, // System_UIntPtr__op_Explicit_ToPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_ToUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, // System_UIntPtr__op_Explicit_FromPointer (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.Pointer, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // System_UIntPtr__op_Explicit_FromUInt32 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt32, // System_UIntPtr__op_Explicit_FromUInt64 (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_UIntPtr, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UIntPtr, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_UInt64, // System_Nullable_T_GetValueOrDefault (byte)MemberFlags.Method, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_Value (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T_get_HasValue (byte)MemberFlags.PropertyGet, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Boolean, // System_Nullable_T__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Implicit_FromT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, (byte)SignatureTypeCode.GenericTypeParameter, 0, // System_Nullable_T__op_Explicit_ToT (byte)(MemberFlags.Method | MemberFlags.Static), // Flags (byte)SpecialType.System_Nullable_T, // DeclaringTypeId 0, // Arity 1, // Method Signature (byte)SignatureTypeCode.GenericTypeParameter, 0, (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Nullable_T, // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces (byte)(MemberFlags.Field | MemberFlags.Static), // Flags (byte)SpecialType.System_Runtime_CompilerServices_RuntimeFeature, // DeclaringTypeId 0, // Arity (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_String, // Field Signature // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor (byte)MemberFlags.Constructor, // Flags (byte)SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute, // DeclaringTypeId 0, // Arity 0, // Method Signature (byte)SignatureTypeCode.TypeHandle, (byte)SpecialType.System_Void, // Return Type }; string[] allNames = new string[(int)SpecialMember.Count] { ".ctor", // System_String__CtorSZArrayChar "Concat", // System_String__ConcatStringString "Concat", // System_String__ConcatStringStringString "Concat", // System_String__ConcatStringStringStringString "Concat", // System_String__ConcatStringArray "Concat", // System_String__ConcatObject "Concat", // System_String__ConcatObjectObject "Concat", // System_String__ConcatObjectObjectObject "Concat", // System_String__ConcatObjectArray "op_Equality", // System_String__op_Equality "op_Inequality", // System_String__op_Inequality "get_Length", // System_String__Length "get_Chars", // System_String__Chars "Format", // System_String__Format "Substring", // System_String__Substring "IsNaN", // System_Double__IsNaN "IsNaN", // System_Single__IsNaN "Combine", // System_Delegate__Combine "Remove", // System_Delegate__Remove "op_Equality", // System_Delegate__op_Equality "op_Inequality", // System_Delegate__op_Inequality "Zero", // System_Decimal__Zero "MinusOne", // System_Decimal__MinusOne "One", // System_Decimal__One ".ctor", // System_Decimal__CtorInt32 ".ctor", // System_Decimal__CtorUInt32 ".ctor", // System_Decimal__CtorInt64 ".ctor", // System_Decimal__CtorUInt64 ".ctor", // System_Decimal__CtorSingle ".ctor", // System_Decimal__CtorDouble ".ctor", // System_Decimal__CtorInt32Int32Int32BooleanByte "op_Addition", // System_Decimal__op_Addition "op_Subtraction", // System_Decimal__op_Subtraction "op_Multiply", // System_Decimal__op_Multiply "op_Division", // System_Decimal__op_Division "op_Modulus", // System_Decimal__op_Modulus "op_UnaryNegation", // System_Decimal__op_UnaryNegation "op_Increment", // System_Decimal__op_Increment "op_Decrement", // System_Decimal__op_Decrement "Negate", // System_Decimal__NegateDecimal "Remainder", // System_Decimal__RemainderDecimalDecimal "Add", // System_Decimal__AddDecimalDecimal "Subtract", // System_Decimal__SubtractDecimalDecimal "Multiply", // System_Decimal__MultiplyDecimalDecimal "Divide", // System_Decimal__DivideDecimalDecimal "Remainder", // System_Decimal__ModuloDecimalDecimal "Compare", // System_Decimal__CompareDecimalDecimal "op_Equality", // System_Decimal__op_Equality "op_Inequality", // System_Decimal__op_Inequality "op_GreaterThan", // System_Decimal__op_GreaterThan "op_GreaterThanOrEqual", // System_Decimal__op_GreaterThanOrEqual "op_LessThan", // System_Decimal__op_LessThan "op_LessThanOrEqual", // System_Decimal__op_LessThanOrEqual "op_Implicit", // System_Decimal__op_Implicit_FromByte "op_Implicit", // System_Decimal__op_Implicit_FromChar "op_Implicit", // System_Decimal__op_Implicit_FromInt16 "op_Implicit", // System_Decimal__op_Implicit_FromInt32 "op_Implicit", // System_Decimal__op_Implicit_FromInt64 "op_Implicit", // System_Decimal__op_Implicit_FromSByte "op_Implicit", // System_Decimal__op_Implicit_FromUInt16 "op_Implicit", // System_Decimal__op_Implicit_FromUInt32 "op_Implicit", // System_Decimal__op_Implicit_FromUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToByte "op_Explicit", // System_Decimal__op_Explicit_ToUInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSByte "op_Explicit", // System_Decimal__op_Explicit_ToInt16 "op_Explicit", // System_Decimal__op_Explicit_ToSingle "op_Explicit", // System_Decimal__op_Explicit_ToDouble "op_Explicit", // System_Decimal__op_Explicit_ToChar "op_Explicit", // System_Decimal__op_Explicit_ToUInt64 "op_Explicit", // System_Decimal__op_Explicit_ToInt32 "op_Explicit", // System_Decimal__op_Explicit_ToUInt32 "op_Explicit", // System_Decimal__op_Explicit_ToInt64 "op_Explicit", // System_Decimal__op_Explicit_FromDouble "op_Explicit", // System_Decimal__op_Explicit_FromSingle "MinValue", // System_DateTime__MinValue ".ctor", // System_DateTime__CtorInt64 "Compare", // System_DateTime__CompareDateTimeDateTime "op_Equality", // System_DateTime__op_Equality "op_Inequality", // System_DateTime__op_Inequality "op_GreaterThan", // System_DateTime__op_GreaterThan "op_GreaterThanOrEqual", // System_DateTime__op_GreaterThanOrEqual "op_LessThan", // System_DateTime__op_LessThan "op_LessThanOrEqual", // System_DateTime__op_LessThanOrEqual "GetEnumerator", // System_Collections_IEnumerable__GetEnumerator "Current", // System_Collections_IEnumerator__Current "get_Current", // System_Collections_IEnumerator__get_Current "MoveNext", // System_Collections_IEnumerator__MoveNext "Reset", // System_Collections_IEnumerator__Reset "GetEnumerator", // System_Collections_Generic_IEnumerable_T__GetEnumerator "Current", // System_Collections_Generic_IEnumerator_T__Current "get_Current", // System_Collections_Generic_IEnumerator_T__get_Current "Dispose", // System_IDisposable__Dispose "Length", // System_Array__Length "LongLength", // System_Array__LongLength "GetLowerBound", // System_Array__GetLowerBound "GetUpperBound", // System_Array__GetUpperBound "GetHashCode", // System_Object__GetHashCode "Equals", // System_Object__Equals "Equals", // System_Object__EqualsObjectObject "ToString", // System_Object__ToString "ReferenceEquals", // System_Object__ReferenceEquals "op_Explicit", // System_IntPtr__op_Explicit_ToPointer "op_Explicit", // System_IntPtr__op_Explicit_ToInt32 "op_Explicit", // System_IntPtr__op_Explicit_ToInt64 "op_Explicit", // System_IntPtr__op_Explicit_FromPointer "op_Explicit", // System_IntPtr__op_Explicit_FromInt32 "op_Explicit", // System_IntPtr__op_Explicit_FromInt64 "op_Explicit", // System_UIntPtr__op_Explicit_ToPointer "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_ToUInt64 "op_Explicit", // System_UIntPtr__op_Explicit_FromPointer "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt32 "op_Explicit", // System_UIntPtr__op_Explicit_FromUInt64 "GetValueOrDefault", // System_Nullable_T_GetValueOrDefault "get_Value", // System_Nullable_T_get_Value "get_HasValue", // System_Nullable_T_get_HasValue ".ctor", // System_Nullable_T__ctor "op_Implicit", // System_Nullable_T__op_Implicit_FromT "op_Explicit", // System_Nullable_T__op_Explicit_ToT "DefaultImplementationsOfInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces "UnmanagedSignatureCallingConvention", // System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention "CovariantReturnsOfClasses", // System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses "VirtualStaticsInInterfaces", // System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces ".ctor", // System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor }; s_descriptors = MemberDescriptor.InitializeFromStream(new System.IO.MemoryStream(initializationBytes, writable: false), allNames); } public static MemberDescriptor GetDescriptor(SpecialMember member) { return s_descriptors[(int)member]; } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Test/Core/Microsoft.CodeAnalysis.Test.Utilities.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>net5.0;netcoreapp3.1;netstandard2.0;net472</TargetFrameworks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Emit.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" /> <InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests" /> <InternalsVisibleTo Include="InteractiveHost.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Rebuild.UnitTests" /> <InternalsVisibleTo Include="Roslyn.Test.PdbUtilities" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> </ItemGroup> <ItemGroup> <!-- TODO: Remove the below IVTs to CodeStyle Unit test projects once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\ControlFlowRegionExtensions.cs" Link="Compilation\FlowAnalysis\ControlFlowRegionExtensions.cs" /> <Compile Include="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\FlowAnalysis\CustomDataFlowAnalysis.cs" Link="Compilation\FlowAnalysis\CustomDataFlowAnalysis.cs" /> <Compile Include="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\FlowAnalysis\DataFlowAnalyzer.cs" Link="Compilation\FlowAnalysis\DataFlowAnalyzer.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="TestResource.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PackageReference Include="DiffPlex" Version="$(DiffPlexVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.Test.Resources.Proprietary" Version="$(MicrosoftCodeAnalysisTestResourcesProprietaryVersion)" /> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" Version="$(MicrosoftDiaSymReaderConverterXmlVersion)" /> <PackageReference Include="Microsoft.Metadata.Visualizer" Version="$(MicrosoftMetadataVisualizerVersion)" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="$(MicrosoftNETCorePlatformsVersion)" /> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" /> <PackageReference Include="xunit.extensibility.core" Version="$(xunitextensibilitycoreVersion)" /> <PackageReference Include="Xunit.Combinatorial" Version="$(XunitCombinatorialVersion)" /> <PackageReference Include="ICSharpCode.Decompiler" Version="$(ICSharpCodeDecompilerVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.AnalyzerUtilities" Version="$(MicrosoftCodeAnalysisAnalyzerUtilitiesVersion)" /> <!-- Needed to find the Unsafe.dll binary to lay out at runtime for the compiler when testing analyzers. --> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net461" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet461Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net451" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet451Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net40" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet40Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net20" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet20Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NET.Build.Extensions" Version="$(MicrosoftNETBuildExtensionsVersion)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="jnm2.ReferenceAssemblies.net35" Version="$(jnm2ReferenceAssembliesnet35Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Basic.Reference.Assemblies.NetStandard20" Version="$(BasicReferenceAssembliesNetStandard20Version)" /> <PackageReference Include="Basic.Reference.Assemblies.Net50" Version="$(BasicReferenceAssembliesNet50Version)" /> </ItemGroup> <Import Project="Generated.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <TargetFrameworks>net5.0;netcoreapp3.1;netstandard2.0;net472</TargetFrameworks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Emit.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.WinRT.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.IOperation.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CommandLine.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests" /> <InternalsVisibleTo Include="Roslyn.Compilers.VisualBasic.IOperation.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Symbol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Syntax.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.ResultProvider.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.ExpressionCompiler.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExpressionEvaluator.FunctionResolver.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ExpressionCompiler.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.ResultProvider.UnitTests" /> <InternalsVisibleTo Include="InteractiveHost.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.Scripting.Desktop.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.MSBuild.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Workspaces.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.FSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.Rebuild.UnitTests" /> <InternalsVisibleTo Include="Roslyn.Test.PdbUtilities" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> </ItemGroup> <ItemGroup> <!-- TODO: Remove the below IVTs to CodeStyle Unit test projects once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" /> </ItemGroup> <ItemGroup> <Compile Include="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\Extensions\ControlFlowRegionExtensions.cs" Link="Compilation\FlowAnalysis\ControlFlowRegionExtensions.cs" /> <Compile Include="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\FlowAnalysis\CustomDataFlowAnalysis.cs" Link="Compilation\FlowAnalysis\CustomDataFlowAnalysis.cs" /> <Compile Include="..\..\..\Workspaces\SharedUtilitiesAndExtensions\Compiler\Core\FlowAnalysis\DataFlowAnalyzer.cs" Link="Compilation\FlowAnalysis\DataFlowAnalyzer.cs" /> </ItemGroup> <ItemGroup> <EmbeddedResource Update="TestResource.resx" GenerateSource="true" /> </ItemGroup> <ItemGroup> <PackageReference Include="DiffPlex" Version="$(DiffPlexVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.Test.Resources.Proprietary" Version="$(MicrosoftCodeAnalysisTestResourcesProprietaryVersion)" /> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" /> <PackageReference Include="Microsoft.DiaSymReader.Converter.Xml" Version="$(MicrosoftDiaSymReaderConverterXmlVersion)" /> <PackageReference Include="Microsoft.Metadata.Visualizer" Version="$(MicrosoftMetadataVisualizerVersion)" /> <PackageReference Include="Microsoft.NETCore.Platforms" Version="$(MicrosoftNETCorePlatformsVersion)" /> <PackageReference Include="Moq" Version="$(MoqVersion)" /> <PackageReference Include="xunit.assert" Version="$(xunitassertVersion)" /> <PackageReference Include="xunit.extensibility.core" Version="$(xunitextensibilitycoreVersion)" /> <PackageReference Include="Xunit.Combinatorial" Version="$(XunitCombinatorialVersion)" /> <PackageReference Include="ICSharpCode.Decompiler" Version="$(ICSharpCodeDecompilerVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.CodeAnalysis.AnalyzerUtilities" Version="$(MicrosoftCodeAnalysisAnalyzerUtilitiesVersion)" /> <!-- Needed to find the Unsafe.dll binary to lay out at runtime for the compiler when testing analyzers. --> <PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="$(SystemRuntimeCompilerServicesUnsafeVersion)" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net461" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet461Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net451" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet451Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net40" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet40Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies.net20" Version="$(MicrosoftNETFrameworkReferenceAssembliesnet20Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.NET.Build.Extensions" Version="$(MicrosoftNETBuildExtensionsVersion)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="jnm2.ReferenceAssemblies.net35" Version="$(jnm2ReferenceAssembliesnet35Version)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="System.Threading.Tasks.Extensions" Version="$(SystemThreadingTasksExtensionsVersion)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.CSharp" Version="$(MicrosoftCSharpVersion)" GeneratePathProperty="true" /> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" IncludeAssets="none" PrivateAssets="all" GeneratePathProperty="true" /> <PackageReference Include="Basic.Reference.Assemblies.NetStandard20" Version="$(BasicReferenceAssembliesNetStandard20Version)" /> <PackageReference Include="Basic.Reference.Assemblies.Net50" Version="$(BasicReferenceAssembliesNet50Version)" /> <PackageReference Include="Basic.Reference.Assemblies.Net60" Version="$(BasicReferenceAssembliesNet60Version)" /> </ItemGroup> <Import Project="Generated.targets" /> </Project>
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Test/Core/TargetFrameworkUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using static TestReferences; using static Roslyn.Test.Utilities.TestMetadata; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { public enum TargetFramework { /// <summary> /// Explicit pick a target framework that has no references /// </summary> Empty, // These are the preferred values that we should be targeting NetStandard20, NetCoreApp, NetFramework, StandardLatest, // Eventually these will be deleted and replaced with NetStandard20. Short term this creates the "standard" // API set across desktop and coreclr. It's also helpful because there are no null annotations hence error // messages have consistent signatures across .NET Core / Framework tests. Standard, StandardAndCSharp, StandardAndVBRuntime, /// <summary> /// Compat framework for the default set of references many vb compilations get. /// </summary> DefaultVb, /// <summary> /// This will eventually be folded into NetCoreApp. The default experience for compiling .NET Core code /// includes the Microsoft.CSharp reference hence it should be the default for our tests /// </summary> NetCoreAppAndCSharp, /// <summary> /// Used for building tests against WinRT scenarios /// </summary> WinRT, // The flavors of mscorlib we support + extending them with LINQ and dynamic. Mscorlib40, Mscorlib40Extended, Mscorlib40AndSystemCore, Mscorlib40AndVBRuntime, Mscorlib45, Mscorlib45Extended, Mscorlib45AndCSharp, Mscorlib45AndVBRuntime, Mscorlib46, Mscorlib46Extended, Mscorlib461, Mscorlib461Extended, DesktopLatestExtended = Mscorlib461Extended, /// <summary> /// Minimal set of required types (<see cref="NetFx.Minimal.mincorlib"/>). /// </summary> Minimal, /// <summary> /// Minimal set of required types and Task implementation (<see cref="NetFx.Minimal.minasync"/>). /// </summary> MinimalAsync, } /// <summary> /// This type holds the reference information for the latest .NET Core platform. Tests /// targeting .NET core specifically should use the references here. As the platform moves /// forward these will be moved to target the latest .NET Core supported by the compiler /// </summary> public static class NetCoreApp { public static ImmutableArray<Net50.ReferenceInfo> AllReferenceInfos { get; } = ImmutableArray.CreateRange(Net50.References.All); public static ImmutableArray<MetadataReference> References { get; } = ImmutableArray.CreateRange<MetadataReference>(Net50.All); /// <summary> /// A subset of <see cref="References"/> that can compile 99% of our test code. /// </summary> public static ImmutableArray<MetadataReference> StandardReferences { get; } = ImmutableArray.Create<MetadataReference>( Net50.netstandard, Net50.mscorlib, Net50.SystemRuntime, Net50.SystemCore, Net50.SystemConsole, Net50.SystemLinq, Net50.SystemLinqExpressions, Net50.SystemThreadingTasks, Net50.SystemCollections); public static PortableExecutableReference netstandard { get; } = Net50.netstandard; public static PortableExecutableReference mscorlib { get; } = Net50.mscorlib; public static PortableExecutableReference SystemRuntime { get; } = Net50.SystemRuntime; public static PortableExecutableReference SystemCore { get; } = Net50.SystemCore; public static PortableExecutableReference SystemConsole { get; } = Net50.SystemConsole; public static PortableExecutableReference SystemLinq { get; } = Net50.SystemLinq; public static PortableExecutableReference SystemLinqExpressions { get; } = Net50.SystemLinqExpressions; public static PortableExecutableReference SystemThreadingTasks { get; } = Net50.SystemThreadingTasks; public static PortableExecutableReference SystemCollections { get; } = Net50.SystemCollections; public static PortableExecutableReference SystemRuntimeInteropServices { get; } = Net50.SystemRuntimeInteropServices; public static PortableExecutableReference MicrosoftCSharp { get; } = Net50.MicrosoftCSharp; public static PortableExecutableReference MicrosoftVisualBasic { get; } = Net50.MicrosoftVisualBasic; } /// <summary> /// This type holds the reference information for the latest .NET Framework. These should be /// used by tests that are specific to .NET Framework. This moves forward much more rarely but /// when it does move forward these will change /// </summary> public static class NetFramework { public static ImmutableArray<MetadataReference> StandardReferences => ImmutableArray.Create<MetadataReference>( Net461.mscorlib, Net461.System, Net461.SystemCore, NetFx.ValueTuple.tuplelib, Net461.SystemRuntime); public static PortableExecutableReference mscorlib { get; } = Net461.mscorlib; public static PortableExecutableReference System { get; } = Net461.System; public static PortableExecutableReference SystemRuntime { get; } = Net461.SystemRuntime; public static PortableExecutableReference SystemCore { get; } = Net461.SystemCore; public static PortableExecutableReference SystemThreadingTasks { get; } = Net461.SystemThreadingTasks; public static PortableExecutableReference MicrosoftCSharp { get; } = Net461.MicrosoftCSharp; public static PortableExecutableReference MicrosoftVisualBasic { get; } = Net461.MicrosoftVisualBasic; } public static class TargetFrameworkUtil { public static ImmutableArray<MetadataReference> StandardLatestReferences => RuntimeUtilities.IsCoreClrRuntime ? NetCoreApp.StandardReferences : NetFramework.StandardReferences; public static ImmutableArray<MetadataReference> StandardReferences => RuntimeUtilities.IsCoreClrRuntime ? NetStandard20References : NetFramework.StandardReferences; public static MetadataReference StandardCSharpReference => RuntimeUtilities.IsCoreClrRuntime ? MicrosoftCSharp.Netstandard13Lib : NetFramework.MicrosoftCSharp; public static MetadataReference StandardVisualBasicReference => RuntimeUtilities.IsCoreClrRuntime ? MicrosoftVisualBasic.Netstandard11 : NetFramework.MicrosoftVisualBasic; public static ImmutableArray<MetadataReference> StandardAndCSharpReferences => StandardReferences.Add(StandardCSharpReference); public static ImmutableArray<MetadataReference> StandardAndVBRuntimeReferences => StandardReferences.Add(StandardVisualBasicReference); /* * ⚠ Dev note ⚠: properties in TestBase are backed by Lazy<T>. Avoid changes to the following properties * which would force the initialization of these properties in the static constructor, since the stack traces * for a TypeLoadException are missing important information for resolving problems if/when they occur. * https://github.com/dotnet/roslyn/issues/25961 */ public static ImmutableArray<MetadataReference> Mscorlib40References => ImmutableArray.Create<MetadataReference>(Net40.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib40ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net40.mscorlib, Net40.System, Net40.SystemCore); public static ImmutableArray<MetadataReference> Mscorlib40andSystemCoreReferences => ImmutableArray.Create<MetadataReference>(Net40.mscorlib, Net40.SystemCore); public static ImmutableArray<MetadataReference> Mscorlib40andVBRuntimeReferences => ImmutableArray.Create<MetadataReference>(Net40.mscorlib, Net40.System, Net40.MicrosoftVisualBasic); public static ImmutableArray<MetadataReference> Mscorlib45References => ImmutableArray.Create<MetadataReference>(Net451.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib45ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.System, Net451.SystemCore, TestBase.ValueTupleRef, Net451.SystemRuntime); public static ImmutableArray<MetadataReference> Mscorlib45AndCSharpReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.SystemCore, Net451.MicrosoftCSharp); public static ImmutableArray<MetadataReference> Mscorlib45AndVBRuntimeReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.System, Net451.MicrosoftVisualBasic); public static ImmutableArray<MetadataReference> Mscorlib46References => ImmutableArray.Create<MetadataReference>(Net461.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib46ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net461.mscorlib, Net461.System, TestMetadata.Net461.SystemCore, TestBase.ValueTupleRef, Net461.SystemRuntime); public static ImmutableArray<MetadataReference> Mscorlib461References => ImmutableArray.Create<MetadataReference>(Net461.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib461ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net461.mscorlib, Net461.System, Net461.SystemCore, NetFx.ValueTuple.tuplelib, Net461.SystemRuntime); public static ImmutableArray<MetadataReference> NetStandard20References => ImmutableArray.Create<MetadataReference>(NetStandard20.netstandard, NetStandard20.mscorlib, NetStandard20.SystemRuntime, NetStandard20.SystemCore, NetStandard20.SystemDynamicRuntime, NetStandard20.SystemLinq, NetStandard20.SystemLinqExpressions); public static ImmutableArray<MetadataReference> WinRTReferences => ImmutableArray.Create(TestBase.WinRtRefs); public static ImmutableArray<MetadataReference> DefaultVbReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.System, Net451.SystemCore, Net451.MicrosoftVisualBasic); public static ImmutableArray<MetadataReference> MinimalReferences => ImmutableArray.Create(TestBase.MinCorlibRef); public static ImmutableArray<MetadataReference> MinimalAsyncReferences => ImmutableArray.Create(TestBase.MinAsyncCorlibRef); public static ImmutableArray<MetadataReference> GetReferences(TargetFramework targetFramework) => targetFramework switch { // Primary TargetFramework.Empty => ImmutableArray<MetadataReference>.Empty, TargetFramework.NetStandard20 => NetStandard20References, TargetFramework.NetCoreApp => NetCoreApp.StandardReferences, TargetFramework.NetCoreAppAndCSharp => NetCoreApp.StandardReferences.Add(NetCoreApp.MicrosoftCSharp), TargetFramework.NetFramework => NetFramework.StandardReferences, // Legacy we should be phasing out TargetFramework.Mscorlib40 => Mscorlib40References, TargetFramework.Mscorlib40Extended => Mscorlib40ExtendedReferences, TargetFramework.Mscorlib40AndSystemCore => Mscorlib40andSystemCoreReferences, TargetFramework.Mscorlib40AndVBRuntime => Mscorlib40andVBRuntimeReferences, TargetFramework.Mscorlib45 => Mscorlib45References, TargetFramework.Mscorlib45Extended => Mscorlib45ExtendedReferences, TargetFramework.Mscorlib45AndCSharp => Mscorlib45AndCSharpReferences, TargetFramework.Mscorlib45AndVBRuntime => Mscorlib45AndVBRuntimeReferences, TargetFramework.Mscorlib46 => Mscorlib46References, TargetFramework.Mscorlib46Extended => Mscorlib46ExtendedReferences, TargetFramework.Mscorlib461 => Mscorlib46References, TargetFramework.Mscorlib461Extended => Mscorlib461ExtendedReferences, TargetFramework.WinRT => WinRTReferences, TargetFramework.Standard => StandardReferences, TargetFramework.StandardAndCSharp => StandardAndCSharpReferences, TargetFramework.StandardAndVBRuntime => StandardAndVBRuntimeReferences, TargetFramework.DefaultVb => DefaultVbReferences, TargetFramework.Minimal => MinimalReferences, TargetFramework.MinimalAsync => MinimalAsyncReferences, TargetFramework.StandardLatest => StandardLatestReferences, _ => throw new InvalidOperationException($"Unexpected target framework {targetFramework}"), }; public static ImmutableArray<MetadataReference> GetReferences(TargetFramework tf, IEnumerable<MetadataReference> additionalReferences) { var references = GetReferences(tf); if (additionalReferences == null) { return references; } checkForDuplicateReferences(); return references.AddRange(additionalReferences); // Check to see if there are any duplicate references. This guards against tests inadvertently passing multiple copies of // say System.Core to the tests and implicitly depending on the higher one to win. The few tests which actually mean to // pass multiple versions of a DLL should manually construct the reference list and not use this helper. void checkForDuplicateReferences() { var nameSet = new HashSet<string>(getNames(references), StringComparer.OrdinalIgnoreCase); foreach (var r in additionalReferences) { if (references.Contains(r)) { throw new Exception($"Duplicate reference detected {r.Display}"); } var name = getName(r); if (name != null && !nameSet.Add(name)) { throw new Exception($"Duplicate reference detected {r.Display} - {name}"); } } } IEnumerable<string> getNames(IEnumerable<MetadataReference> e) { foreach (var r in e) { var name = getName(r); if (name != null) { yield return name; } } } string getName(MetadataReference m) { if (m is PortableExecutableReference p && p.GetMetadata() is AssemblyMetadata assemblyMetadata) { try { var identity = assemblyMetadata.GetAssembly().Identity; return identity?.Name; } catch (BadImageFormatException) { // Happens when a native image is incorrectly passed as a PE. return null; } } return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using static TestReferences; using static Roslyn.Test.Utilities.TestMetadata; using Basic.Reference.Assemblies; namespace Roslyn.Test.Utilities { public enum TargetFramework { /// <summary> /// Explicit pick a target framework that has no references /// </summary> Empty, // These are the preferred values that we should be targeting NetStandard20, NetCoreApp, NetFramework, StandardLatest, // Eventually these will be deleted and replaced with NetStandard20. Short term this creates the "standard" // API set across desktop and coreclr. It's also helpful because there are no null annotations hence error // messages have consistent signatures across .NET Core / Framework tests. Standard, StandardAndCSharp, StandardAndVBRuntime, /// <summary> /// Compat framework for the default set of references many vb compilations get. /// </summary> DefaultVb, /// <summary> /// This will eventually be folded into NetCoreApp. The default experience for compiling .NET Core code /// includes the Microsoft.CSharp reference hence it should be the default for our tests /// </summary> NetCoreAppAndCSharp, /// <summary> /// Used for building tests against WinRT scenarios /// </summary> WinRT, // The flavors of mscorlib we support + extending them with LINQ and dynamic. Mscorlib40, Mscorlib40Extended, Mscorlib40AndSystemCore, Mscorlib40AndVBRuntime, Mscorlib45, Mscorlib45Extended, Mscorlib45AndCSharp, Mscorlib45AndVBRuntime, Mscorlib46, Mscorlib46Extended, Mscorlib461, Mscorlib461Extended, DesktopLatestExtended = Mscorlib461Extended, /// <summary> /// Minimal set of required types (<see cref="NetFx.Minimal.mincorlib"/>). /// </summary> Minimal, /// <summary> /// Minimal set of required types and Task implementation (<see cref="NetFx.Minimal.minasync"/>). /// </summary> MinimalAsync, Net50, Net60, } /// <summary> /// This type holds the reference information for the latest .NET Core platform. Tests /// targeting .NET core specifically should use the references here. As the platform moves /// forward these will be moved to target the latest .NET Core supported by the compiler /// </summary> public static class NetCoreApp { public static ImmutableArray<Net50.ReferenceInfo> AllReferenceInfos { get; } = ImmutableArray.CreateRange(Net50.References.All); public static ImmutableArray<MetadataReference> References { get; } = ImmutableArray.CreateRange<MetadataReference>(Net50.All); /// <summary> /// A subset of <see cref="References"/> that can compile 99% of our test code. /// </summary> public static ImmutableArray<MetadataReference> StandardReferences { get; } = ImmutableArray.Create<MetadataReference>( Net50.netstandard, Net50.mscorlib, Net50.SystemRuntime, Net50.SystemCore, Net50.SystemConsole, Net50.SystemLinq, Net50.SystemLinqExpressions, Net50.SystemThreadingTasks, Net50.SystemCollections); public static PortableExecutableReference netstandard { get; } = Net50.netstandard; public static PortableExecutableReference mscorlib { get; } = Net50.mscorlib; public static PortableExecutableReference SystemRuntime { get; } = Net50.SystemRuntime; public static PortableExecutableReference SystemCore { get; } = Net50.SystemCore; public static PortableExecutableReference SystemConsole { get; } = Net50.SystemConsole; public static PortableExecutableReference SystemLinq { get; } = Net50.SystemLinq; public static PortableExecutableReference SystemLinqExpressions { get; } = Net50.SystemLinqExpressions; public static PortableExecutableReference SystemThreadingTasks { get; } = Net50.SystemThreadingTasks; public static PortableExecutableReference SystemCollections { get; } = Net50.SystemCollections; public static PortableExecutableReference SystemRuntimeInteropServices { get; } = Net50.SystemRuntimeInteropServices; public static PortableExecutableReference MicrosoftCSharp { get; } = Net50.MicrosoftCSharp; public static PortableExecutableReference MicrosoftVisualBasic { get; } = Net50.MicrosoftVisualBasic; } /// <summary> /// This type holds the reference information for the latest .NET Framework. These should be /// used by tests that are specific to .NET Framework. This moves forward much more rarely but /// when it does move forward these will change /// </summary> public static class NetFramework { public static ImmutableArray<MetadataReference> StandardReferences => ImmutableArray.Create<MetadataReference>( Net461.mscorlib, Net461.System, Net461.SystemCore, NetFx.ValueTuple.tuplelib, Net461.SystemRuntime); public static PortableExecutableReference mscorlib { get; } = Net461.mscorlib; public static PortableExecutableReference System { get; } = Net461.System; public static PortableExecutableReference SystemRuntime { get; } = Net461.SystemRuntime; public static PortableExecutableReference SystemCore { get; } = Net461.SystemCore; public static PortableExecutableReference SystemThreadingTasks { get; } = Net461.SystemThreadingTasks; public static PortableExecutableReference MicrosoftCSharp { get; } = Net461.MicrosoftCSharp; public static PortableExecutableReference MicrosoftVisualBasic { get; } = Net461.MicrosoftVisualBasic; } public static class TargetFrameworkUtil { public static ImmutableArray<MetadataReference> StandardLatestReferences => RuntimeUtilities.IsCoreClrRuntime ? NetCoreApp.StandardReferences : NetFramework.StandardReferences; public static ImmutableArray<MetadataReference> StandardReferences => RuntimeUtilities.IsCoreClrRuntime ? NetStandard20References : NetFramework.StandardReferences; public static MetadataReference StandardCSharpReference => RuntimeUtilities.IsCoreClrRuntime ? MicrosoftCSharp.Netstandard13Lib : NetFramework.MicrosoftCSharp; public static MetadataReference StandardVisualBasicReference => RuntimeUtilities.IsCoreClrRuntime ? MicrosoftVisualBasic.Netstandard11 : NetFramework.MicrosoftVisualBasic; public static ImmutableArray<MetadataReference> StandardAndCSharpReferences => StandardReferences.Add(StandardCSharpReference); public static ImmutableArray<MetadataReference> StandardAndVBRuntimeReferences => StandardReferences.Add(StandardVisualBasicReference); /* * ⚠ Dev note ⚠: properties in TestBase are backed by Lazy<T>. Avoid changes to the following properties * which would force the initialization of these properties in the static constructor, since the stack traces * for a TypeLoadException are missing important information for resolving problems if/when they occur. * https://github.com/dotnet/roslyn/issues/25961 */ public static ImmutableArray<MetadataReference> Mscorlib40References => ImmutableArray.Create<MetadataReference>(Net40.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib40ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net40.mscorlib, Net40.System, Net40.SystemCore); public static ImmutableArray<MetadataReference> Mscorlib40andSystemCoreReferences => ImmutableArray.Create<MetadataReference>(Net40.mscorlib, Net40.SystemCore); public static ImmutableArray<MetadataReference> Mscorlib40andVBRuntimeReferences => ImmutableArray.Create<MetadataReference>(Net40.mscorlib, Net40.System, Net40.MicrosoftVisualBasic); public static ImmutableArray<MetadataReference> Mscorlib45References => ImmutableArray.Create<MetadataReference>(Net451.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib45ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.System, Net451.SystemCore, TestBase.ValueTupleRef, Net451.SystemRuntime); public static ImmutableArray<MetadataReference> Mscorlib45AndCSharpReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.SystemCore, Net451.MicrosoftCSharp); public static ImmutableArray<MetadataReference> Mscorlib45AndVBRuntimeReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.System, Net451.MicrosoftVisualBasic); public static ImmutableArray<MetadataReference> Mscorlib46References => ImmutableArray.Create<MetadataReference>(Net461.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib46ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net461.mscorlib, Net461.System, TestMetadata.Net461.SystemCore, TestBase.ValueTupleRef, Net461.SystemRuntime); public static ImmutableArray<MetadataReference> Mscorlib461References => ImmutableArray.Create<MetadataReference>(Net461.mscorlib); public static ImmutableArray<MetadataReference> Mscorlib461ExtendedReferences => ImmutableArray.Create<MetadataReference>(Net461.mscorlib, Net461.System, Net461.SystemCore, NetFx.ValueTuple.tuplelib, Net461.SystemRuntime); public static ImmutableArray<MetadataReference> NetStandard20References => ImmutableArray.Create<MetadataReference>(NetStandard20.netstandard, NetStandard20.mscorlib, NetStandard20.SystemRuntime, NetStandard20.SystemCore, NetStandard20.SystemDynamicRuntime, NetStandard20.SystemLinq, NetStandard20.SystemLinqExpressions); public static ImmutableArray<MetadataReference> WinRTReferences => ImmutableArray.Create(TestBase.WinRtRefs); public static ImmutableArray<MetadataReference> DefaultVbReferences => ImmutableArray.Create<MetadataReference>(Net451.mscorlib, Net451.System, Net451.SystemCore, Net451.MicrosoftVisualBasic); public static ImmutableArray<MetadataReference> MinimalReferences => ImmutableArray.Create(TestBase.MinCorlibRef); public static ImmutableArray<MetadataReference> MinimalAsyncReferences => ImmutableArray.Create(TestBase.MinAsyncCorlibRef); public static ImmutableArray<MetadataReference> GetReferences(TargetFramework targetFramework) => targetFramework switch { // Primary TargetFramework.Empty => ImmutableArray<MetadataReference>.Empty, TargetFramework.NetStandard20 => NetStandard20References, TargetFramework.NetCoreApp or TargetFramework.Net50 => NetCoreApp.StandardReferences, TargetFramework.Net60 => ImmutableArray.CreateRange<MetadataReference>(Net60.All), TargetFramework.NetCoreAppAndCSharp => NetCoreApp.StandardReferences.Add(NetCoreApp.MicrosoftCSharp), TargetFramework.NetFramework => NetFramework.StandardReferences, // Legacy we should be phasing out TargetFramework.Mscorlib40 => Mscorlib40References, TargetFramework.Mscorlib40Extended => Mscorlib40ExtendedReferences, TargetFramework.Mscorlib40AndSystemCore => Mscorlib40andSystemCoreReferences, TargetFramework.Mscorlib40AndVBRuntime => Mscorlib40andVBRuntimeReferences, TargetFramework.Mscorlib45 => Mscorlib45References, TargetFramework.Mscorlib45Extended => Mscorlib45ExtendedReferences, TargetFramework.Mscorlib45AndCSharp => Mscorlib45AndCSharpReferences, TargetFramework.Mscorlib45AndVBRuntime => Mscorlib45AndVBRuntimeReferences, TargetFramework.Mscorlib46 => Mscorlib46References, TargetFramework.Mscorlib46Extended => Mscorlib46ExtendedReferences, TargetFramework.Mscorlib461 => Mscorlib46References, TargetFramework.Mscorlib461Extended => Mscorlib461ExtendedReferences, TargetFramework.WinRT => WinRTReferences, TargetFramework.Standard => StandardReferences, TargetFramework.StandardAndCSharp => StandardAndCSharpReferences, TargetFramework.StandardAndVBRuntime => StandardAndVBRuntimeReferences, TargetFramework.DefaultVb => DefaultVbReferences, TargetFramework.Minimal => MinimalReferences, TargetFramework.MinimalAsync => MinimalAsyncReferences, TargetFramework.StandardLatest => StandardLatestReferences, _ => throw new InvalidOperationException($"Unexpected target framework {targetFramework}"), }; public static ImmutableArray<MetadataReference> GetReferences(TargetFramework tf, IEnumerable<MetadataReference> additionalReferences) { var references = GetReferences(tf); if (additionalReferences == null) { return references; } checkForDuplicateReferences(); return references.AddRange(additionalReferences); // Check to see if there are any duplicate references. This guards against tests inadvertently passing multiple copies of // say System.Core to the tests and implicitly depending on the higher one to win. The few tests which actually mean to // pass multiple versions of a DLL should manually construct the reference list and not use this helper. void checkForDuplicateReferences() { var nameSet = new HashSet<string>(getNames(references), StringComparer.OrdinalIgnoreCase); foreach (var r in additionalReferences) { if (references.Contains(r)) { throw new Exception($"Duplicate reference detected {r.Display}"); } var name = getName(r); if (name != null && !nameSet.Add(name)) { throw new Exception($"Duplicate reference detected {r.Display} - {name}"); } } } IEnumerable<string> getNames(IEnumerable<MetadataReference> e) { foreach (var r in e) { var name = getName(r); if (name != null) { yield return name; } } } string getName(MetadataReference m) { if (m is PortableExecutableReference p && p.GetMetadata() is AssemblyMetadata assemblyMetadata) { try { var identity = assemblyMetadata.GetAssembly().Identity; return identity?.Name; } catch (BadImageFormatException) { // Happens when a native image is incorrectly passed as a PE. return null; } } return null; } } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/WellKnownTypeValidationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class WellKnownTypeValidationTests Inherits BasicTestBase <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicSpecialType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Friend Class [String] End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim special = comp.GetSpecialType(SpecialType.System_String) Assert.Equal(TypeKind.Error, special.TypeKind) Assert.Equal(SpecialType.System_String, special.SpecialType) Assert.Equal(Accessibility.Public, special.DeclaredAccessibility) Dim lookup = comp.GetTypeByMetadataName("System.String") Assert.Equal(TypeKind.Class, lookup.TypeKind) Assert.Equal(SpecialType.None, lookup.SpecialType) Assert.Equal(Accessibility.Internal, lookup.DeclaredAccessibility) End Sub ValidateSourceAndMetadata(source, validate) End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicSpecialTypeMember() Dim sourceTemplate = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub {0} Overridable Function ToString() As [String] Return Nothing End Function End Class {0} Class [String] Public Shared Function Concat(s1 As [String], s2 As [String]) As [String] Return Nothing End Function End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validatePresent As Action(Of VisualBasicCompilation) = Sub(comp) Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)) Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)) comp.GetDiagnostics() End Sub Dim validateMissing As Action(Of VisualBasicCompilation) = Sub(comp) Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)) Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)) comp.GetDiagnostics() End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public"), validatePresent) ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend"), validateMissing) End Sub ' Document the fact that we don't reject type parameters with constraints (yet?). <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub GenericConstraintsOnSpecialType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Structure Nullable(Of T As New) End Structure Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim special = comp.GetSpecialType(SpecialType.System_Nullable_T) Assert.Equal(TypeKind.Structure, special.TypeKind) Assert.Equal(SpecialType.System_Nullable_T, special.SpecialType) Dim lookup = comp.GetTypeByMetadataName("System.Nullable`1") Assert.Equal(TypeKind.Structure, lookup.TypeKind) Assert.Equal(SpecialType.System_Nullable_T, lookup.SpecialType) End Sub ValidateSourceAndMetadata(source, validate) End Sub ' No special type members have type parameters that could (incorrectly) be constrained. <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicWellKnownType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Friend Class Type End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type) If wellKnown.DeclaringCompilation Is comp Then Assert.Equal(TypeKind.Class, wellKnown.TypeKind) Assert.Equal(Accessibility.Internal, wellKnown.DeclaredAccessibility) Else Assert.Equal(TypeKind.Error, wellKnown.TypeKind) Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility) End If Dim lookup = comp.GetTypeByMetadataName("System.Type") Assert.Equal(TypeKind.Class, lookup.TypeKind) Assert.Equal(Accessibility.Internal, lookup.DeclaredAccessibility) End Sub ValidateSourceAndMetadata(source, validate) End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicWellKnownType_Nested() Dim sourceTemplate = <![CDATA[ Namespace System.Diagnostics {0} Class DebuggableAttribute {1} Enum DebuggingModes Mode End Enum End Class End Namespace Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class ValueType End Class Public Class [Enum] End Class Public Structure Void End Structure Public Structure [Int32] End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes) Assert.Equal(If(wellKnown.DeclaringCompilation Is comp, TypeKind.Enum, TypeKind.Error), wellKnown.TypeKind) Dim lookup = comp.GetTypeByMetadataName("System.Diagnostics.DebuggableAttribute+DebuggingModes") Assert.Equal(TypeKind.Enum, lookup.TypeKind) End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public", "Friend"), validate) ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend", "Public"), validate) End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicWellKnownTypeMember() Dim sourceTemplate = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class [String] End Class {0} Class Type Public Shared ReadOnly Missing As [Object] End Class Public Class FlagsAttribute {0} Sub New() End Sub End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validatePresent As Action(Of VisualBasicCompilation) = Sub(comp) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor)) comp.GetDiagnostics() End Sub Dim validateMissing As Action(Of VisualBasicCompilation) = Sub(comp) If comp.Assembly.CorLibrary Is comp.Assembly Then Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor)) Else Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)) Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor)) End If comp.GetDiagnostics() End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public"), validatePresent) ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend"), validateMissing) End Sub ' Document the fact that we don't reject type parameters with constraints (yet?). <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub GenericConstraintsOnWellKnownType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace Namespace System.Threading.Tasks Public Class Task(Of T As New) End Class End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T) Assert.Equal(TypeKind.Class, wellKnown.TypeKind) Dim lookup = comp.GetTypeByMetadataName("System.Threading.Tasks.Task`1") Assert.Equal(TypeKind.Class, lookup.TypeKind) End Sub ValidateSourceAndMetadata(source, validate) End Sub ' Document the fact that we don't reject type parameters with constraints (yet?). <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub GenericConstraintsOnWellKnownTypeMember() Dim sourceTemplate = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class Activator Public Shared Function CreateInstance(Of T{0})() As T Throw New Exception() End Function End Class Public Class Exception Public Sub New() End Sub End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Activator__CreateInstance_T)) comp.GetDiagnostics() End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, ""), validate) ValidateSourceAndMetadata(String.Format(sourceTemplate, " As New"), validate) End Sub Private Shared Sub ValidateSourceAndMetadata(source As String, validate As Action(Of VisualBasicCompilation)) Dim comp1 = CreateEmptyCompilation(WrapInCompilationXml(source)) validate(comp1) Dim reference = comp1.EmitToImageReference() Dim comp2 = CreateEmptyCompilationWithReferences(<compilation/>, {reference}) validate(comp2) End Sub Private Shared Function WrapInCompilationXml(source As String) As XElement Return <compilation> <file name="a.vb"> <%= source %> </file> </compilation> End Function <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub PublicVersusInternalWellKnownType() Dim corlibSource = <compilation> <file name="a.vb"> Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class [String] End Class Public Class Attribute End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace Namespace System.Runtime.CompilerServices Public Class InternalsVisibleToAttribute : Inherits System.Attribute Public Sub New(s As [String]) End Sub End Class End Namespace </file> </compilation> If True Then Dim libSourceTemplate = <![CDATA[ Namespace System {0} Class Type End Class End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim corlibRef = CreateEmptyCompilation(corlibSource).EmitToImageReference() Dim publicLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Public")), {corlibRef}).EmitToImageReference() Dim internalLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Friend")), {corlibRef}).EmitToImageReference() Dim comp = CreateEmptyCompilationWithReferences({}, {corlibRef, publicLibRef, internalLibRef}, assemblyName:="Test") Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type) Assert.NotNull(wellKnown) Assert.Equal(TypeKind.Class, wellKnown.TypeKind) Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility) Dim Lookup = comp.GetTypeByMetadataName("System.Type") Assert.Null(Lookup) ' Ambiguous End If If True Then Dim libSourceTemplate = <![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Test")> Namespace System {0} Class Type End Class End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim corlibRef = CreateEmptyCompilation(corlibSource).EmitToImageReference() Dim publicLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Public")), {corlibRef}).EmitToImageReference() Dim internalLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Friend")), {corlibRef}).EmitToImageReference() Dim comp = CreateEmptyCompilationWithReferences({}, {corlibRef, publicLibRef, internalLibRef}, assemblyName:="Test") Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type) Assert.NotNull(wellKnown) Assert.Equal(TypeKind.Error, wellKnown.TypeKind) Dim Lookup = comp.GetTypeByMetadataName("System.Type") Assert.Null(Lookup) ' Ambiguous End If End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllSpecialTypes() Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), {MscorlibRef_v4_0_30316_17626}) For special As SpecialType = CType(SpecialType.None + 1, SpecialType) To SpecialType.Count Dim symbol = comp.GetSpecialType(special) Assert.NotNull(symbol) If special = SpecialType.System_Runtime_CompilerServices_RuntimeFeature OrElse special = SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute Then Assert.Equal(SymbolKind.ErrorType, symbol.Kind) ' Not available Else Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind) End If Next End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllSpecialTypeMembers() Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), {MscorlibRef_v4_0_30316_17626}) For Each special As SpecialMember In [Enum].GetValues(GetType(SpecialMember)) Select Case special Case SpecialMember.System_IntPtr__op_Explicit_ToPointer, SpecialMember.System_IntPtr__op_Explicit_FromPointer, SpecialMember.System_UIntPtr__op_Explicit_ToPointer, SpecialMember.System_UIntPtr__op_Explicit_FromPointer ' VB doesn't have pointer types. Continue For Case SpecialMember.Count ' Not a real value. Continue For End Select Dim symbol = comp.GetSpecialTypeMember(special) If special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces OrElse special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention OrElse special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses OrElse special = SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor Then Assert.Null(symbol) ' Not available Else Assert.NotNull(symbol) End If Next End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllWellKnownTypes() Dim refs As MetadataReference() = { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray() Dim lastType = CType(WellKnownType.NextAvailable - 1, WellKnownType) Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), refs.Concat(MsvbRef_v4_0_30319_17929).ToArray()) For wkt = WellKnownType.First To lastType Select Case wkt Case WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators ' Only present when embedding VB Core. Continue For Case WellKnownType.System_FormattableString, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownType.System_Span_T, WellKnownType.System_ReadOnlySpan_T, WellKnownType.System_Index, WellKnownType.System_Range, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute, WellKnownType.System_IAsyncDisposable, WellKnownType.System_Collections_Generic_IAsyncEnumerable_T, WellKnownType.System_Collections_Generic_IAsyncEnumerator_T, WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource, WellKnownType.System_Threading_Tasks_ValueTask_T, WellKnownType.System_Threading_Tasks_ValueTask, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder, WellKnownType.System_Threading_CancellationToken, WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute, WellKnownType.Microsoft_CodeAnalysis_EmbeddedAttribute, WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownType.System_Runtime_CompilerServices_IsExternalInit, WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler ' Not available on all platforms. Continue For Case WellKnownType.ExtSentinel ' Not a real type Continue For Case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownType.System_Runtime_CompilerServices_ITuple ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownType(wkt) Assert.NotNull(symbol) Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind) Next comp = CreateEmptyCompilationWithReferences(<compilation/>, refs, TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) For wkt = WellKnownType.First To lastType Select Case wkt Case WellKnownType.Microsoft_VisualBasic_CallType, WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, WellKnownType.Microsoft_VisualBasic_CompareMethod, WellKnownType.Microsoft_VisualBasic_ErrObject, WellKnownType.Microsoft_VisualBasic_FileSystem, WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase, WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase, WellKnownType.Microsoft_VisualBasic_Information, WellKnownType.Microsoft_VisualBasic_Interaction, WellKnownType.Microsoft_VisualBasic_Conversion ' Not embedded, so not available. Continue For Case WellKnownType.System_FormattableString, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownType.System_Span_T, WellKnownType.System_ReadOnlySpan_T, WellKnownType.System_Index, WellKnownType.System_Range, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute, WellKnownType.System_IAsyncDisposable, WellKnownType.System_Collections_Generic_IAsyncEnumerable_T, WellKnownType.System_Collections_Generic_IAsyncEnumerator_T, WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource, WellKnownType.System_Threading_Tasks_ValueTask_T, WellKnownType.System_Threading_Tasks_ValueTask, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder, WellKnownType.System_Threading_CancellationToken, WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute, WellKnownType.Microsoft_CodeAnalysis_EmbeddedAttribute, WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownType.System_Runtime_CompilerServices_IsExternalInit, WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler ' Not available on all platforms. Continue For Case WellKnownType.ExtSentinel ' Not a real type Continue For Case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownType.System_Runtime_CompilerServices_ITuple ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownType(wkt) Assert.NotNull(symbol) Assert.True(SymbolKind.ErrorType <> symbol.Kind, $"{symbol} should not be an error type") Next End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllWellKnownTypeMembers() Dim refs As MetadataReference() = { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray() Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), refs.Concat(MsvbRef_v4_0_30319_17929).ToArray()) For Each wkm As WellKnownMember In [Enum].GetValues(GetType(WellKnownMember)) Select Case wkm Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean ' Only present when embedding VB Core. Continue For Case WellKnownMember.Count ' Not a real value. Continue For Case WellKnownMember.System_Array__Empty, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, WellKnownMember.System_Span_T__ctor, WellKnownMember.System_Span_T__get_Item, WellKnownMember.System_Span_T__get_Length, WellKnownMember.System_ReadOnlySpan_T__ctor, WellKnownMember.System_ReadOnlySpan_T__get_Item, WellKnownMember.System_ReadOnlySpan_T__get_Length, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, WellKnownMember.System_IAsyncDisposable__DisposeAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorValue, WellKnownMember.System_Threading_Tasks_ValueTask__ctor, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear ' Not available yet, but will be in upcoming release. Continue For Case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Index__ctor, WellKnownMember.System_Index__GetOffset, WellKnownMember.System_Range__ctor, WellKnownMember.System_Range__EndAt, WellKnownMember.System_Range__get_All, WellKnownMember.System_Range__StartAt, WellKnownMember.System_Range__get_End, WellKnownMember.System_Range__get_Start, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownTypeMember(wkm) Assert.True(symbol IsNot Nothing, $"Unexpected null for {wkm}") Next comp = CreateEmptyCompilationWithReferences(<compilation/>, refs, TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) For Each wkm As WellKnownMember In [Enum].GetValues(GetType(WellKnownMember)) Select Case wkm Case WellKnownMember.Count ' Not a real value. Continue For Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp, WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32, WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32, WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char ' Even though the containing type is embedded, the specific member is not. Continue For Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, WellKnownMember.Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__CallByName, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__TypeName, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName, WellKnownMember.Microsoft_VisualBasic_Information__IsNumeric, WellKnownMember.Microsoft_VisualBasic_Information__SystemTypeName, WellKnownMember.Microsoft_VisualBasic_Information__TypeName, WellKnownMember.Microsoft_VisualBasic_Information__VbTypeName, WellKnownMember.Microsoft_VisualBasic_Interaction__CallByName, WellKnownMember.Microsoft_VisualBasic_Conversion__FixSingle, WellKnownMember.Microsoft_VisualBasic_Conversion__FixDouble, WellKnownMember.Microsoft_VisualBasic_Conversion__IntSingle, WellKnownMember.Microsoft_VisualBasic_Conversion__IntDouble ' The type is not embedded, so the member is not available. Continue For Case WellKnownMember.System_Array__Empty, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, WellKnownMember.System_Span_T__ctor, WellKnownMember.System_Span_T__get_Item, WellKnownMember.System_Span_T__get_Length, WellKnownMember.System_ReadOnlySpan_T__ctor, WellKnownMember.System_ReadOnlySpan_T__get_Item, WellKnownMember.System_ReadOnlySpan_T__get_Length, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, WellKnownMember.System_IAsyncDisposable__DisposeAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorValue, WellKnownMember.System_Threading_Tasks_ValueTask__ctor, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear ' Not available yet, but will be in upcoming release. Continue For Case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Index__ctor, WellKnownMember.System_Index__GetOffset, WellKnownMember.System_Range__ctor, WellKnownMember.System_Range__EndAt, WellKnownMember.System_Range__get_All, WellKnownMember.System_Range__StartAt, WellKnownMember.System_Range__get_End, WellKnownMember.System_Range__get_Start, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownTypeMember(wkm) Assert.True(symbol IsNot Nothing, $"Unexpected null for {wkm}") Next End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class WellKnownTypeValidationTests Inherits BasicTestBase <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicSpecialType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Friend Class [String] End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim special = comp.GetSpecialType(SpecialType.System_String) Assert.Equal(TypeKind.Error, special.TypeKind) Assert.Equal(SpecialType.System_String, special.SpecialType) Assert.Equal(Accessibility.Public, special.DeclaredAccessibility) Dim lookup = comp.GetTypeByMetadataName("System.String") Assert.Equal(TypeKind.Class, lookup.TypeKind) Assert.Equal(SpecialType.None, lookup.SpecialType) Assert.Equal(Accessibility.Internal, lookup.DeclaredAccessibility) End Sub ValidateSourceAndMetadata(source, validate) End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicSpecialTypeMember() Dim sourceTemplate = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub {0} Overridable Function ToString() As [String] Return Nothing End Function End Class {0} Class [String] Public Shared Function Concat(s1 As [String], s2 As [String]) As [String] Return Nothing End Function End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validatePresent As Action(Of VisualBasicCompilation) = Sub(comp) Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)) Assert.NotNull(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)) comp.GetDiagnostics() End Sub Dim validateMissing As Action(Of VisualBasicCompilation) = Sub(comp) Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_Object__ToString)) Assert.Null(comp.GetSpecialTypeMember(SpecialMember.System_String__ConcatStringString)) comp.GetDiagnostics() End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public"), validatePresent) ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend"), validateMissing) End Sub ' Document the fact that we don't reject type parameters with constraints (yet?). <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub GenericConstraintsOnSpecialType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Structure Nullable(Of T As New) End Structure Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim special = comp.GetSpecialType(SpecialType.System_Nullable_T) Assert.Equal(TypeKind.Structure, special.TypeKind) Assert.Equal(SpecialType.System_Nullable_T, special.SpecialType) Dim lookup = comp.GetTypeByMetadataName("System.Nullable`1") Assert.Equal(TypeKind.Structure, lookup.TypeKind) Assert.Equal(SpecialType.System_Nullable_T, lookup.SpecialType) End Sub ValidateSourceAndMetadata(source, validate) End Sub ' No special type members have type parameters that could (incorrectly) be constrained. <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicWellKnownType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Friend Class Type End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type) If wellKnown.DeclaringCompilation Is comp Then Assert.Equal(TypeKind.Class, wellKnown.TypeKind) Assert.Equal(Accessibility.Internal, wellKnown.DeclaredAccessibility) Else Assert.Equal(TypeKind.Error, wellKnown.TypeKind) Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility) End If Dim lookup = comp.GetTypeByMetadataName("System.Type") Assert.Equal(TypeKind.Class, lookup.TypeKind) Assert.Equal(Accessibility.Internal, lookup.DeclaredAccessibility) End Sub ValidateSourceAndMetadata(source, validate) End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicWellKnownType_Nested() Dim sourceTemplate = <![CDATA[ Namespace System.Diagnostics {0} Class DebuggableAttribute {1} Enum DebuggingModes Mode End Enum End Class End Namespace Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class ValueType End Class Public Class [Enum] End Class Public Structure Void End Structure Public Structure [Int32] End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes) Assert.Equal(If(wellKnown.DeclaringCompilation Is comp, TypeKind.Enum, TypeKind.Error), wellKnown.TypeKind) Dim lookup = comp.GetTypeByMetadataName("System.Diagnostics.DebuggableAttribute+DebuggingModes") Assert.Equal(TypeKind.Enum, lookup.TypeKind) End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public", "Friend"), validate) ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend", "Public"), validate) End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub NonPublicWellKnownTypeMember() Dim sourceTemplate = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class [String] End Class {0} Class Type Public Shared ReadOnly Missing As [Object] End Class Public Class FlagsAttribute {0} Sub New() End Sub End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validatePresent As Action(Of VisualBasicCompilation) = Sub(comp) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor)) comp.GetDiagnostics() End Sub Dim validateMissing As Action(Of VisualBasicCompilation) = Sub(comp) If comp.Assembly.CorLibrary Is comp.Assembly Then Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor)) Else Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_Type__Missing)) Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_FlagsAttribute__ctor)) End If comp.GetDiagnostics() End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, "Public"), validatePresent) ValidateSourceAndMetadata(String.Format(sourceTemplate, "Friend"), validateMissing) End Sub ' Document the fact that we don't reject type parameters with constraints (yet?). <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub GenericConstraintsOnWellKnownType() Dim source = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace Namespace System.Threading.Tasks Public Class Task(Of T As New) End Class End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T) Assert.Equal(TypeKind.Class, wellKnown.TypeKind) Dim lookup = comp.GetTypeByMetadataName("System.Threading.Tasks.Task`1") Assert.Equal(TypeKind.Class, lookup.TypeKind) End Sub ValidateSourceAndMetadata(source, validate) End Sub ' Document the fact that we don't reject type parameters with constraints (yet?). <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub GenericConstraintsOnWellKnownTypeMember() Dim sourceTemplate = <![CDATA[ Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class Activator Public Shared Function CreateInstance(Of T{0})() As T Throw New Exception() End Function End Class Public Class Exception Public Sub New() End Sub End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim validate As Action(Of VisualBasicCompilation) = Sub(comp) Assert.NotNull(comp.GetWellKnownTypeMember(WellKnownMember.System_Activator__CreateInstance_T)) comp.GetDiagnostics() End Sub ValidateSourceAndMetadata(String.Format(sourceTemplate, ""), validate) ValidateSourceAndMetadata(String.Format(sourceTemplate, " As New"), validate) End Sub Private Shared Sub ValidateSourceAndMetadata(source As String, validate As Action(Of VisualBasicCompilation)) Dim comp1 = CreateEmptyCompilation(WrapInCompilationXml(source)) validate(comp1) Dim reference = comp1.EmitToImageReference() Dim comp2 = CreateEmptyCompilationWithReferences(<compilation/>, {reference}) validate(comp2) End Sub Private Shared Function WrapInCompilationXml(source As String) As XElement Return <compilation> <file name="a.vb"> <%= source %> </file> </compilation> End Function <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub PublicVersusInternalWellKnownType() Dim corlibSource = <compilation> <file name="a.vb"> Namespace System Public Class [Object] Public Sub New() End Sub End Class Public Class [String] End Class Public Class Attribute End Class Public Class ValueType End Class Public Structure Void End Structure End Namespace Namespace System.Runtime.CompilerServices Public Class InternalsVisibleToAttribute : Inherits System.Attribute Public Sub New(s As [String]) End Sub End Class End Namespace </file> </compilation> If True Then Dim libSourceTemplate = <![CDATA[ Namespace System {0} Class Type End Class End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim corlibRef = CreateEmptyCompilation(corlibSource).EmitToImageReference() Dim publicLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Public")), {corlibRef}).EmitToImageReference() Dim internalLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Friend")), {corlibRef}).EmitToImageReference() Dim comp = CreateEmptyCompilationWithReferences({}, {corlibRef, publicLibRef, internalLibRef}, assemblyName:="Test") Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type) Assert.NotNull(wellKnown) Assert.Equal(TypeKind.Class, wellKnown.TypeKind) Assert.Equal(Accessibility.Public, wellKnown.DeclaredAccessibility) Dim Lookup = comp.GetTypeByMetadataName("System.Type") Assert.Null(Lookup) ' Ambiguous End If If True Then Dim libSourceTemplate = <![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Test")> Namespace System {0} Class Type End Class End Namespace ]]>.Value.Replace(vbLf, vbCrLf).Trim Dim corlibRef = CreateEmptyCompilation(corlibSource).EmitToImageReference() Dim publicLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Public")), {corlibRef}).EmitToImageReference() Dim internalLibRef = CreateEmptyCompilationWithReferences(WrapInCompilationXml(String.Format(libSourceTemplate, "Friend")), {corlibRef}).EmitToImageReference() Dim comp = CreateEmptyCompilationWithReferences({}, {corlibRef, publicLibRef, internalLibRef}, assemblyName:="Test") Dim wellKnown = comp.GetWellKnownType(WellKnownType.System_Type) Assert.NotNull(wellKnown) Assert.Equal(TypeKind.Error, wellKnown.TypeKind) Dim Lookup = comp.GetTypeByMetadataName("System.Type") Assert.Null(Lookup) ' Ambiguous End If End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllSpecialTypes() Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), {MscorlibRef_v4_0_30316_17626}) For special As SpecialType = CType(SpecialType.None + 1, SpecialType) To SpecialType.Count Dim symbol = comp.GetSpecialType(special) Assert.NotNull(symbol) If special = SpecialType.System_Runtime_CompilerServices_RuntimeFeature OrElse special = SpecialType.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute Then Assert.Equal(SymbolKind.ErrorType, symbol.Kind) ' Not available Else Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind) End If Next End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllSpecialTypeMembers() Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), {MscorlibRef_v4_0_30316_17626}) For Each special As SpecialMember In [Enum].GetValues(GetType(SpecialMember)) Select Case special Case SpecialMember.System_IntPtr__op_Explicit_ToPointer, SpecialMember.System_IntPtr__op_Explicit_FromPointer, SpecialMember.System_UIntPtr__op_Explicit_ToPointer, SpecialMember.System_UIntPtr__op_Explicit_FromPointer ' VB doesn't have pointer types. Continue For Case SpecialMember.Count ' Not a real value. Continue For End Select Dim symbol = comp.GetSpecialTypeMember(special) If special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__DefaultImplementationsOfInterfaces OrElse special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__UnmanagedSignatureCallingConvention OrElse special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__CovariantReturnsOfClasses OrElse special = SpecialMember.System_Runtime_CompilerServices_RuntimeFeature__VirtualStaticsInInterfaces OrElse special = SpecialMember.System_Runtime_CompilerServices_PreserveBaseOverridesAttribute__ctor Then Assert.Null(symbol) ' Not available Else Assert.NotNull(symbol) End If Next End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllWellKnownTypes() Dim refs As MetadataReference() = { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray() Dim lastType = CType(WellKnownType.NextAvailable - 1, WellKnownType) Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), refs.Concat(MsvbRef_v4_0_30319_17929).ToArray()) For wkt = WellKnownType.First To lastType Select Case wkt Case WellKnownType.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators ' Only present when embedding VB Core. Continue For Case WellKnownType.System_FormattableString, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownType.System_Span_T, WellKnownType.System_ReadOnlySpan_T, WellKnownType.System_Index, WellKnownType.System_Range, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute, WellKnownType.System_IAsyncDisposable, WellKnownType.System_Collections_Generic_IAsyncEnumerable_T, WellKnownType.System_Collections_Generic_IAsyncEnumerator_T, WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource, WellKnownType.System_Threading_Tasks_ValueTask_T, WellKnownType.System_Threading_Tasks_ValueTask, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder, WellKnownType.System_Threading_CancellationToken, WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute, WellKnownType.Microsoft_CodeAnalysis_EmbeddedAttribute, WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownType.System_Runtime_CompilerServices_IsExternalInit, WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler ' Not available on all platforms. Continue For Case WellKnownType.ExtSentinel ' Not a real type Continue For Case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownType.System_Runtime_CompilerServices_ITuple ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownType(wkt) Assert.NotNull(symbol) Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind) Next comp = CreateEmptyCompilationWithReferences(<compilation/>, refs, TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) For wkt = WellKnownType.First To lastType Select Case wkt Case WellKnownType.Microsoft_VisualBasic_CallType, WellKnownType.Microsoft_VisualBasic_CompilerServices_Operators, WellKnownType.Microsoft_VisualBasic_CompilerServices_NewLateBinding, WellKnownType.Microsoft_VisualBasic_CompilerServices_LikeOperator, WellKnownType.Microsoft_VisualBasic_CompilerServices_StringType, WellKnownType.Microsoft_VisualBasic_CompilerServices_Versioned, WellKnownType.Microsoft_VisualBasic_CompareMethod, WellKnownType.Microsoft_VisualBasic_ErrObject, WellKnownType.Microsoft_VisualBasic_FileSystem, WellKnownType.Microsoft_VisualBasic_ApplicationServices_ApplicationBase, WellKnownType.Microsoft_VisualBasic_ApplicationServices_WindowsFormsApplicationBase, WellKnownType.Microsoft_VisualBasic_Information, WellKnownType.Microsoft_VisualBasic_Interaction, WellKnownType.Microsoft_VisualBasic_Conversion ' Not embedded, so not available. Continue For Case WellKnownType.System_FormattableString, WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownType.System_Span_T, WellKnownType.System_ReadOnlySpan_T, WellKnownType.System_Index, WellKnownType.System_Range, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute, WellKnownType.System_IAsyncDisposable, WellKnownType.System_Collections_Generic_IAsyncEnumerable_T, WellKnownType.System_Collections_Generic_IAsyncEnumerator_T, WellKnownType.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceStatus, WellKnownType.System_Threading_Tasks_Sources_ValueTaskSourceOnCompletedFlags, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T, WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource, WellKnownType.System_Threading_Tasks_ValueTask_T, WellKnownType.System_Threading_Tasks_ValueTask, WellKnownType.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder, WellKnownType.System_Threading_CancellationToken, WellKnownType.System_Runtime_CompilerServices_NonNullTypesAttribute, WellKnownType.Microsoft_CodeAnalysis_EmbeddedAttribute, WellKnownType.System_Runtime_CompilerServices_SwitchExpressionException, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownType.System_Runtime_CompilerServices_IsExternalInit, WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler ' Not available on all platforms. Continue For Case WellKnownType.ExtSentinel ' Not a real type Continue For Case WellKnownType.Microsoft_CodeAnalysis_Runtime_Instrumentation, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownType.System_Runtime_CompilerServices_ITuple ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownType(wkt) Assert.NotNull(symbol) Assert.True(SymbolKind.ErrorType <> symbol.Kind, $"{symbol} should not be an error type") Next End Sub <Fact> <WorkItem(530436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530436")> Public Sub AllWellKnownTypeMembers() Dim refs As MetadataReference() = { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929, CSharpRef, SystemXmlRef, SystemXmlLinqRef, SystemWindowsFormsRef, ValueTupleRef }.Concat(WinRtRefs).ToArray() Dim comp = CreateEmptyCompilationWithReferences((<compilation/>), refs.Concat(MsvbRef_v4_0_30319_17929).ToArray()) For Each wkm As WellKnownMember In [Enum].GetValues(GetType(WellKnownMember)) Select Case wkm Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_EmbeddedOperators__CompareStringStringStringBoolean ' Only present when embedding VB Core. Continue For Case WellKnownMember.Count ' Not a real value. Continue For Case WellKnownMember.System_Array__Empty, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, WellKnownMember.System_Span_T__ctor, WellKnownMember.System_Span_T__get_Item, WellKnownMember.System_Span_T__get_Length, WellKnownMember.System_ReadOnlySpan_T__ctor, WellKnownMember.System_ReadOnlySpan_T__get_Item, WellKnownMember.System_ReadOnlySpan_T__get_Length, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, WellKnownMember.System_IAsyncDisposable__DisposeAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorValue, WellKnownMember.System_Threading_Tasks_ValueTask__ctor, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear ' Not available yet, but will be in upcoming release. Continue For Case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Index__ctor, WellKnownMember.System_Index__GetOffset, WellKnownMember.System_Range__ctor, WellKnownMember.System_Range__EndAt, WellKnownMember.System_Range__get_All, WellKnownMember.System_Range__StartAt, WellKnownMember.System_Range__get_End, WellKnownMember.System_Range__get_Start, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownTypeMember(wkm) Assert.True(symbol IsNot Nothing, $"Unexpected null for {wkm}") Next comp = CreateEmptyCompilationWithReferences(<compilation/>, refs, TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)) For Each wkm As WellKnownMember In [Enum].GetValues(GetType(WellKnownMember)) Select Case wkm Case WellKnownMember.Count ' Not a real value. Continue For Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ChangeType, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForLoopInitObj, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl_ForLoopControl__ForNextCheckObj, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ObjectFlowControl__CheckForSyncLockOnValueType, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__CreateProjectError, WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__EndApp, WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32, WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32, WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char ' Even though the containing type is embedded, the specific member is not. Continue For Case WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__PlusObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__NegateObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__NotObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AndObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__OrObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__XorObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__AddObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__SubtractObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__MultiplyObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__DivideObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ExponentObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ModObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__IntDivideObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__LeftShiftObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__RightShiftObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConcatenateObjectObjectObject, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectNotEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectLessEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareObjectGreaterObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectNotEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectLessEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterEqualObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__ConditionalCompareObjectGreaterObjectObjectBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Operators__CompareStringStringStringBoolean, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateCall, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateGet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateSetComplex, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexGet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSet, WellKnownMember.Microsoft_VisualBasic_CompilerServices_NewLateBinding__LateIndexSetComplex, WellKnownMember.Microsoft_VisualBasic_CompilerServices_StringType__MidStmtStr, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeStringStringStringCompareMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_LikeOperator__LikeObjectObjectObjectCompareMethod, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__CallByName, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__IsNumeric, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__SystemTypeName, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__TypeName, WellKnownMember.Microsoft_VisualBasic_CompilerServices_Versioned__VbTypeName, WellKnownMember.Microsoft_VisualBasic_Information__IsNumeric, WellKnownMember.Microsoft_VisualBasic_Information__SystemTypeName, WellKnownMember.Microsoft_VisualBasic_Information__TypeName, WellKnownMember.Microsoft_VisualBasic_Information__VbTypeName, WellKnownMember.Microsoft_VisualBasic_Interaction__CallByName, WellKnownMember.Microsoft_VisualBasic_Conversion__FixSingle, WellKnownMember.Microsoft_VisualBasic_Conversion__FixDouble, WellKnownMember.Microsoft_VisualBasic_Conversion__IntSingle, WellKnownMember.Microsoft_VisualBasic_Conversion__IntDouble ' The type is not embedded, so the member is not available. Continue For Case WellKnownMember.System_Array__Empty, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor, WellKnownMember.System_Span_T__ctor, WellKnownMember.System_Span_T__get_Item, WellKnownMember.System_Span_T__get_Length, WellKnownMember.System_ReadOnlySpan_T__ctor, WellKnownMember.System_ReadOnlySpan_T__get_Item, WellKnownMember.System_ReadOnlySpan_T__get_Length, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorStateMachineAttribute__ctor, WellKnownMember.System_IAsyncDisposable__DisposeAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerable_T__GetAsyncEnumerator, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__MoveNextAsync, WellKnownMember.System_Collections_Generic_IAsyncEnumerator_T__get_Current, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__get_Version, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__Reset, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetException, WellKnownMember.System_Threading_Tasks_Sources_ManualResetValueTaskSourceCore_T__SetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource_T__OnCompleted, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetResult, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__GetStatus, WellKnownMember.System_Threading_Tasks_Sources_IValueTaskSource__OnCompleted, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorSourceAndToken, WellKnownMember.System_Threading_Tasks_ValueTask_T__ctorValue, WellKnownMember.System_Threading_Tasks_ValueTask__ctor, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__AwaitUnsafeOnCompleted, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Complete, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__Create, WellKnownMember.System_Runtime_CompilerServices_AsyncIteratorMethodBuilder__MoveNext_T, WellKnownMember.System_Runtime_CompilerServices_AsyncStateMachineAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags, WellKnownMember.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler__ToStringAndClear ' Not available yet, but will be in upcoming release. Continue For Case WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningSingleFile, WellKnownMember.Microsoft_CodeAnalysis_Runtime_Instrumentation__CreatePayloadForMethodsSpanningMultipleFiles, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Index__ctor, WellKnownMember.System_Index__GetOffset, WellKnownMember.System_Range__ctor, WellKnownMember.System_Range__EndAt, WellKnownMember.System_Range__get_All, WellKnownMember.System_Range__StartAt, WellKnownMember.System_Range__get_End, WellKnownMember.System_Range__get_Start, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Item, WellKnownMember.System_Runtime_CompilerServices_ITuple__get_Length, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctor, WellKnownMember.System_Runtime_CompilerServices_SwitchExpressionException__ctorObject ' Not always available. Continue For End Select Dim symbol = comp.GetWellKnownTypeMember(wkm) Assert.True(symbol IsNot Nothing, $"Unexpected null for {wkm}") Next End Sub End Class End Namespace
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/ImplementInterface/ImplementInterfaceTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.ImplementInterface.CSharpImplementInterfaceCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface { public class ImplementInterfaceTests { private readonly NamingStylesTestOptionSets _options = new NamingStylesTestOptionSets(LanguageNames.CSharp); private static OptionsCollection AllOptionsOff => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; private static OptionsCollection AllOptionsOn => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }; private static OptionsCollection AccessorOptionsOn => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; internal static async Task TestWithAllCodeStyleOptionsOffAsync( string initialMarkup, string expectedMarkup, (string equivalenceKey, int index)? codeAction = null) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AllOptionsOff }, CodeActionEquivalenceKey = codeAction?.equivalenceKey, CodeActionIndex = codeAction?.index, }.RunAsync(); } internal static async Task TestWithAllCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AllOptionsOn }, }.RunAsync(); } internal static async Task TestWithAccessorCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AccessorOptionsOn }, }.RunAsync(); } private static async Task TestInRegularAndScriptAsync( string initialMarkup, string expectedMarkup, (string equivalenceKey, int index)? codeAction = null) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, CodeActionEquivalenceKey = codeAction?.equivalenceKey, CodeActionIndex = codeAction?.index, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void Method1(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void Method1(); } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodInRecord() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.Preview, TestCode = @"interface IInterface { void Method1(); } record Record : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); } record Record : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task TestMethodWithNativeIntegers() { var nativeIntegerAttributeDefinition = @" namespace System.Runtime.CompilerServices { [System.AttributeUsage(AttributeTargets.All)] public sealed class NativeIntegerAttribute : System.Attribute { public NativeIntegerAttribute() { } public NativeIntegerAttribute(bool[] flags) { } } }"; // Note: we're putting the attribute by hand to simulate metadata await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @"interface IInterface { [return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}] (nint, nuint) Method(nint x, nuint x2); } class Class : {|CS0535:IInterface|} { }" + nativeIntegerAttributeDefinition, FixedCode = @"interface IInterface { [return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}] (nint, nuint) Method(nint x, nuint x2); } class Class : IInterface { public (nint, nuint) Method(nint x, nuint x2) { throw new System.NotImplementedException(); } }" + nativeIntegerAttributeDefinition, Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodWithTuple() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { (int, int) Method((string, string) x); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { (int, int) Method((string, string) x); } class Class : IInterface { public (int, int) Method((string, string) x) { throw new System.NotImplementedException(); } }"); } [WorkItem(16793, "https://github.com/dotnet/roslyn/issues/16793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodWithValueTupleArity1() { await TestWithAllCodeStyleOptionsOffAsync( @" using System; interface I { ValueTuple<object> F(); } class C : {|CS0535:I|} { }", @" using System; interface I { ValueTuple<object> F(); } class C : I { public ValueTuple<object> F() { throw new NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExpressionBodiedMethod1() { await TestWithAllCodeStyleOptionsOnAsync( @"interface IInterface { void Method1(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void Method1(); } class Class : IInterface { public void Method1() => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInMethod() { // Note: we're putting the attribute by hand to simulate metadata await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : IInterface { public (int a, int b)[] Method1((int c, string) x) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInMethod_Explicitly() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : IInterface { (int a, int b)[] IInterface.Method1((int c, string) x) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; } } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; } } class Class : IInterface { public (int a, int b)[] Property1 { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInEvent() { await new VerifyCS.Test { TestCode = @"interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] event System.Func<(int a, int b)> Event1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"using System; interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] event System.Func<(int a, int b)> Event1; } class Class : IInterface { public event Func<(int a, int b)> Event1; }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task NoDynamicAttributeInMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}] object Method1(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}] object Method1(); } class Class : IInterface { public object Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task NoNullableAttributesInMethodFromMetadata() { var test = new VerifyCS.Test { TestState = { Sources = { @" #nullable enable using System; class C : {|CS0535:{|CS0535:IInterface|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @" #nullable enable public interface IInterface { void M(string? s1, string s2); string this[string? s1, string s2] { get; set; } }" }, }, }, AdditionalProjectReferences = { "Assembly1", }, }, FixedState = { Sources = { @" #nullable enable using System; class C : IInterface { public string this[string? s1, string s2] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void M(string? s1, string s2) { throw new NotImplementedException(); } }", }, }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodWhenClassBracesAreMissing() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void Method1(); } class Class : {|CS0535:IInterface|}{|CS1513:|}{|CS1514:|}", @"interface IInterface { void Method1(); } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritance1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { } class Class : {|CS0535:IInterface2|} { }", @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritance2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { } interface IInterface2 : IInterface1 { void Method1(); } class Class : {|CS0535:IInterface2|} { }", @"interface IInterface1 { } interface IInterface2 : IInterface1 { void Method1(); } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritance3() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method2(); } class Class : {|CS0535:{|CS0535:IInterface2|}|} { }", @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method2(); } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } public void Method2() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritanceMatchingMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method1(); } class Class : {|CS0535:{|CS0535:IInterface2|}|} { }", @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method1(); } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExistingConflictingMethodReturnType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } class Class : {|CS0738:IInterface1|} { public int Method1() { return 0; } }", @"interface IInterface1 { void Method1(); } class Class : IInterface1 { public int Method1() { return 0; } void IInterface1.Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExistingConflictingMethodParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(int i); } class Class : {|CS0535:IInterface1|} { public void Method1(string i) { } }", @"interface IInterface1 { void Method1(int i); } class Class : IInterface1 { public void Method1(string i) { } public void Method1(int i) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1<T> { void Method1(T t); } class Class : {|CS0535:IInterface1<int>|} { }", @"interface IInterface1<T> { void Method1(T t); } class Class : IInterface1<int> { public void Method1(int t) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericTypeWithGenericMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1<T> { void Method1<U>(T t, U u); } class Class : {|CS0535:IInterface1<int>|} { }", @"interface IInterface1<T> { void Method1<U>(T t, U u); } class Class : IInterface1<int> { public void Method1<U>(int t, U u) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericTypeWithGenericMethodWithNaturalConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; interface IInterface1<T> { void Method1<U>(T t, U u) where U : IList<T>; } class Class : {|CS0535:IInterface1<int>|} { }", @"using System.Collections.Generic; interface IInterface1<T> { void Method1<U>(T t, U u) where U : IList<T>; } class Class : IInterface1<int> { public void Method1<U>(int t, U u) where U : IList<int> { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericTypeWithGenericMethodWithUnexpressibleConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1<T> { void Method1<U>(T t, U u) where U : T; } class Class : {|CS0535:IInterface1<int>|} { }", @"interface IInterface1<T> { void Method1<U>(T t, U u) where U : T; } class Class : IInterface1<int> { void IInterface1<int>.Method1<U>(int t, U u) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestArrayType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { string[] M(); } class C : {|CS0535:I|} { }", @"interface I { string[] M(); } class C : I { public string[] M() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; }", @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember_FixAll_SameMemberInDifferentType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; } class D : {|CS0535:I|} { I i; }", @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } } class D : I { I i; public void Method1() { i.Method1(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember_FixAll_FieldInOnePropInAnother() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; } class D : {|CS0535:I|} { I i { get; } }", @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } } class D : I { I i { get; } public void Method1() { i.Method1(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember_FixAll_FieldInOneNonViableInAnother() { var test = new VerifyCS.Test { TestCode = @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; } class D : {|CS0535:I|} { int i; }", FixedState = { Sources = { @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } } class D : {|CS0535:I|} { int i; }", }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", CodeActionIndex = 1, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMemberInterfaceWithIndexer() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { int this[int x] { get; set; } } class Goo : {|CS0535:IGoo|} { IGoo f; }", @"interface IGoo { int this[int x] { get; set; } } class Goo : IGoo { IGoo f; public int this[int x] { get { return f[x]; } set { f[x] = value; } } }", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;f", 1)); } [WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCast() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections; sealed class X : {|CS0535:IComparer|} { X x; }", @"using System.Collections; sealed class X : IComparer { X x; public int Compare(object x, object y) { return ((IComparer)this.x).Compare(x, y); } }", codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;x", 1)); } [WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCastAndThis() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections; sealed class X : {|CS0535:IComparer|} { X a; }", @"using System.Collections; sealed class X : IComparer { X a; public int Compare(object x, object y) { return ((IComparer)a).Compare(x, y); } }", codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementAbstract() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } abstract class C : {|CS0535:I|} { }", @"interface I { void Method1(); } abstract class C : I { public abstract void Method1(); }", codeAction: ("False;True;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceWithRefOutParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"class C : {|CS0535:{|CS0535:I|}|} { I goo; } interface I { void Method1(ref int x, out int y, int z); int Method2(); }", @"class C : I { I goo; public void Method1(ref int x, out int y, int z) { goo.Method1(ref x, out y, z); } public int Method2() { return goo.Method2(); } } interface I { void Method1(ref int x, out int y, int z); int Method2(); }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConflictingMethods1() { await TestWithAllCodeStyleOptionsOffAsync( @"class B { public int Method1() { return 0; } } class C : B, {|CS0738:I|} { } interface I { void Method1(); }", @"class B { public int Method1() { return 0; } } class C : B, I { void I.Method1() { throw new System.NotImplementedException(); } } interface I { void Method1(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConflictingProperties() { await TestWithAllCodeStyleOptionsOffAsync( @"class Test : {|CS0737:I1|} { int Prop { get; set; } } interface I1 { int Prop { get; set; } }", @"class Test : I1 { int Prop { get; set; } int I1.Prop { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } interface I1 { int Prop { get; set; } }"); } [WorkItem(539043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitProperties() { var code = @"interface I2 { decimal Calc { get; } } class C : I2 { protected decimal pay; decimal I2.Calc { get { return pay; } } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedMethodName() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void @M(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void @M(); } class Class : IInterface { public void M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedMethodKeyword() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void @int(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void @int(); } class Class : IInterface { public void @int() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceName1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @IInterface { void M(); } class Class : {|CS0737:@IInterface|} { string M() => """"; }", @"interface @IInterface { void M(); } class Class : @IInterface { string M() => """"; void IInterface.M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceName2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @IInterface { void @M(); } class Class : {|CS0737:@IInterface|} { string M() => """"; }", @"interface @IInterface { void @M(); } class Class : @IInterface { string M() => """"; void IInterface.M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceKeyword1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @int { void M(); } class Class : {|CS0737:@int|} { string M() => """"; }", @"interface @int { void M(); } class Class : @int { string M() => """"; void @int.M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceKeyword2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @int { void @bool(); } class Class : {|CS0737:@int|} { string @bool() => """"; }", @"interface @int { void @bool(); } class Class : @int { string @bool() => """"; void @int.@bool() { throw new System.NotImplementedException(); } }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPropertyFormatting() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface DD { int Prop { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; set; } } public class A : DD { public int Prop { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestProperty_PropertyCodeStyleOn1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestProperty_AccessorCodeStyleOn1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop { get => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexer_IndexerCodeStyleOn1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexer_AccessorCodeStyleOn1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethod_AllCodeStyleOn1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int M(); } public class A : {|CS0535:DD|} { }", @"public interface DD { int M(); } public class A : DD { public int M() => throw new System.NotImplementedException(); }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyExpressionBodyYes1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop => throw new System.NotImplementedException(); }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyAccessorBodyYes1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop { get => throw new System.NotImplementedException(); } }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyAccessorBodyYes2() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; set; } } public class A : DD { public int Prop { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyExpressionBodyNo1() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop { get { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerExpressionBodyYes1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerExpressionBodyNo1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; set; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerAccessorExpressionBodyYes1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerAccessorExpressionBodyYes2() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; set; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCommentPlacement() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface DD { void Goo(); } public class A : {|CS0535:DD|} { //comments }", @"public interface DD { void Goo(); } public class A : DD { //comments public void Goo() { throw new System.NotImplementedException(); } }"); } [WorkItem(539991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539991")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestBracePlacement() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingWithIncompleteMember() { var code = @"interface ITest { void Method(); } class Test : ITest { p {|CS1585:public|} void Method() { throw new System.NotImplementedException(); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(541380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541380")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"interface i1 { int p { get; set; } } class c1 : {|CS0535:i1|} { }", @"interface i1 { int p { get; set; } } class c1 : i1 { int i1.p { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", codeAction: ("True;False;False:global::i1;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(541981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541981")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoDelegateThroughField1() { var code = @"interface I { void Method1(); } class C : {|CS0535:I|} { I i { get; set; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = @"interface I { void Method1(); } class C : I { I i { get; set; } public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); await new VerifyCS.Test { TestCode = code, FixedCode = @"interface I { void Method1(); } class C : I { I i { get; set; } public void Method1() { i.Method1(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = code, FixedCode = @"interface I { void Method1(); } class C : I { I i { get; set; } void I.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 2, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIReadOnlyListThroughField() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|} { int[] field; }", @"using System.Collections; using System.Collections.Generic; class A : IReadOnlyList<int> { int[] field; public int this[int index] { get { return ((IReadOnlyList<int>)field)[index]; } } public int Count { get { return ((IReadOnlyCollection<int>)field).Count; } } public IEnumerator<int> GetEnumerator() { return ((IEnumerable<int>)field).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return field.GetEnumerator(); } }", codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIReadOnlyListThroughProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|} { int[] field { get; set; } }", @"using System.Collections; using System.Collections.Generic; class A : IReadOnlyList<int> { public int this[int index] { get { return ((IReadOnlyList<int>)field)[index]; } } public int Count { get { return ((IReadOnlyCollection<int>)field).Count; } } int[] field { get; set; } public IEnumerator<int> GetEnumerator() { return ((IEnumerable<int>)field).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return field.GetEnumerator(); } }", codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a; }", @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A a; public int M() { return ((I)a).M(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField_FieldImplementsMultipleInterfaces() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : {|CS0535:I|}, {|CS0535:I2|} { A a; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : I, {|CS0535:I2|} { A a; public int M() { return ((I)a).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[0], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : {|CS0535:I|}, {|CS0535:I2|} { A a; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : {|CS0535:I|}, I2 { A a; public int M2() { return ((I2)a).M2(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField_MultipleFieldsCanImplementInterface() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a; A aa; }", FixedState = { Sources = { @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A a; A aa; public int M() { return ((I)a).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a; A aa; }", FixedState = { Sources = { @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A a; A aa; public int M() { return ((I)aa).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;aa", CodeActionIndex = 2, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField_MultipleFieldsForMultipleInterfaces() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : {|CS0535:I|}, {|CS0535:I2|} { A a; B b; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : I, {|CS0535:I2|} { A a; B b; public int M() { return ((I)a).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[0], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : {|CS0535:I|}, {|CS0535:I2|} { A a; B b; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : {|CS0535:I|}, I2 { A a; B b; public int M2() { return ((I2)b).M2(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;b", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(18556, "https://github.com/dotnet/roslyn/issues/18556")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughExplicitProperty() { await new VerifyCS.Test { TestCode = @"interface IA { IB B { get; } } interface IB { int M(); } class AB : IA, {|CS0535:IB|} { IB IA.B => null; }", FixedCode = @"interface IA { IB B { get; } } interface IB { int M(); } class AB : IA, IB { IB IA.B => null; public int M() { return ((IA)this).B.M(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::IB;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;IA.B", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoImplementThroughIndexer() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A this[int index] { get { return null; } } }", FixedCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A this[int index] { get { return null; } } public int M() { throw new System.NotImplementedException(); } }", CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoImplementThroughWriteOnlyProperty() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a { set { } } }", FixedCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a { set { } } public int M() { throw new System.NotImplementedException(); } }", CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventThroughMember() { await TestInRegularAndScriptAsync(@" interface IGoo { event System.EventHandler E; } class CanGoo : IGoo { public event System.EventHandler E; } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; }", @" using System; interface IGoo { event System.EventHandler E; } class CanGoo : IGoo { public event System.EventHandler E; } class HasCanGoo : IGoo { CanGoo canGoo; public event EventHandler E { add { ((IGoo)canGoo).E += value; } remove { ((IGoo)canGoo).E -= value; } } }", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventThroughExplicitMember() { await TestInRegularAndScriptAsync( @"interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; } ", @"using System; interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : IGoo { CanGoo canGoo; public event EventHandler E { add { ((IGoo)canGoo).E += value; } remove { ((IGoo)canGoo).E -= value; } } } ", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEvent() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { event System.EventHandler E; } abstract class Goo : {|CS0535:IGoo|} { }", @"using System; interface IGoo { event System.EventHandler E; } abstract class Goo : IGoo { public event EventHandler E; }", codeAction: ("False;False;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventAbstractly() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { event System.EventHandler E; } abstract class Goo : {|CS0535:IGoo|} { }", @"using System; interface IGoo { event System.EventHandler E; } abstract class Goo : IGoo { public abstract event EventHandler E; }", codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventExplicitly() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { event System.EventHandler E; } abstract class Goo : {|CS0535:IGoo|} { }", @"using System; interface IGoo { event System.EventHandler E; } abstract class Goo : IGoo { event EventHandler IGoo.E { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } }", codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFaultToleranceInStaticMembers_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IFoo { static string Name { set; get; } static int {|CS0501:Foo|}(string s); } class Program : IFoo { }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFaultToleranceInStaticMembers_02() { var test = new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IFoo { string Name { set; get; } static int {|CS0501:Foo|}(string s); } class Program : {|CS0535:IFoo|} { }", FixedCode = @"interface IFoo { string Name { set; get; } static int {|CS0501:Foo|}(string s); } class Program : IFoo { public string Name { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFaultToleranceInStaticMembers_03() { var test = new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IGoo { static string Name { set; get; } int Goo(string s); } class Program : {|CS0535:IGoo|} { }", FixedCode = @"interface IGoo { static string Name { set; get; } int Goo(string s); } class Program : IGoo { public int Goo(string s) { throw new System.NotImplementedException(); } }", }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexers() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : {|CS0535:ISomeInterface|} { }", @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : ISomeInterface { public int this[int index] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexersExplicit() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : {|CS0535:ISomeInterface|} { }", @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : ISomeInterface { int ISomeInterface.this[int index] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", codeAction: ("True;False;False:global::ISomeInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexersWithASingleAccessor() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface ISomeInterface { int this[int index] { get; } } class IndexerClass : {|CS0535:ISomeInterface|} { }", @"public interface ISomeInterface { int this[int index] { get; } } class IndexerClass : ISomeInterface { public int this[int index] { get { throw new System.NotImplementedException(); } } }"); } [WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstraints1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<T>() where T : class; } class A : {|CS0535:I|} { }", @"interface I { void Goo<T>() where T : class; } class A : I { public void Goo<T>() where T : class { throw new System.NotImplementedException(); } }"); } [WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstraintsExplicit() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<T>() where T : class; } class A : {|CS0535:I|} { }", @"interface I { void Goo<T>() where T : class; } class A : I { void I.Goo<T>() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUsingAddedForConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<T>() where T : System.Attribute; } class A : {|CS0535:I|} { }", @"using System; interface I { void Goo<T>() where T : System.Attribute; } class A : I { public void Goo<T>() where T : Attribute { throw new NotImplementedException(); } }"); } [WorkItem(542379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542379")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexer() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { int this[int x] { get; set; } } class C : {|CS0535:I|} { }", @"interface I { int this[int x] { get; set; } } class C : I { public int this[int x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRecursiveConstraint1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : I { public void Goo<T>() where T : IComparable<T> { throw new NotImplementedException(); } }"); } [WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRecursiveConstraint2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : I { void I.Goo<T>() { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<string>|} { }", @"interface I<S> { void Goo<T>() where T : class, S; } class A : I<string> { void I<string>.Goo<T>() { throw new System.NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<object>|} { }", @"interface I<S> { void Goo<T>() where T : class, S; } class A : I<object> { public void Goo<T>() where T : class { throw new System.NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint3() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<object>|} { }", @"interface I<S> { void Goo<T>() where T : class, S; } class A : I<object> { void I<object>.Goo<T>() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I<object>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint4() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<Delegate>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<Delegate> { void I<Delegate>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint5() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<MulticastDelegate>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<MulticastDelegate> { void I<MulticastDelegate>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint6() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } delegate void Bar(); class A : {|CS0535:I<Bar>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } delegate void Bar(); class A : I<Bar> { void I<Bar>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint7() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<Enum>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<Enum> { void I<Enum>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint8() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<int[]>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<int[]> { void I<int[]>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint9() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } enum E { } class A : {|CS0535:I<E>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } enum E { } class A : I<E> { void I<E>.Goo<{|CS0455:T|}>() { throw new NotImplementedException(); } }"); } [WorkItem(542621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint10() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : S; } class A : {|CS0535:I<ValueType>|} { }", @"using System; interface I<S> { void Goo<T>() where T : S; } class A : I<ValueType> { void I<ValueType>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542669")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestArrayConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : S; } class C : {|CS0535:I<Array>|} { }", @"using System; interface I<S> { void Goo<T>() where T : S; } class C : I<Array> { void I<Array>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMultipleClassConstraints() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : Exception, S; } class C : {|CS0535:I<Attribute>|} { }", @"using System; interface I<S> { void Goo<T>() where T : Exception, S; } class C : I<Attribute> { void I<Attribute>.Goo<{|CS0455:T|}>() { throw new NotImplementedException(); } }"); } [WorkItem(542751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542751")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestClassConstraintAndRefConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class C : {|CS0535:I<Exception>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class C : I<Exception> { void I<Exception>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : {|CS0535:I<S>|} { }", @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : I<S> { public void Goo<S1>(S x, IList<S1> list) where S1 : S { throw new NotImplementedException(); } }"); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : {|CS0535:I<S>|} { }", @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : I<S> { void I<S>.Goo<S1>(S x, IList<S1> list) { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::I<S>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters3() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : {|CS0535:I<A, B>|} { }", @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : I<A, B> { public void Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2) where A1 : IList<B1> where B1 : IList<A1> { throw new NotImplementedException(); } }"); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters4() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : {|CS0535:I<A, B>|} { }", @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : I<A, B> { void I<A, B>.Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2) { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::I<A, B>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameSimplification() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class A<T> { class B { } interface I { void Goo(B x); } class C<U> : {|CS0535:I|} { } }", @"using System; class A<T> { class B { } interface I { void Goo(B x); } class C<U> : I { public void Goo(B x) { throw new NotImplementedException(); } } }"); } [WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameSimplification2() { await TestWithAllCodeStyleOptionsOffAsync( @"class A<T> { class B { } interface I { void Goo(B[] x); } class C<U> : {|CS0535:I|} { } }", @"class A<T> { class B { } interface I { void Goo(B[] x); } class C<U> : I { public void Goo(B[] x) { throw new System.NotImplementedException(); } } }"); } [WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameSimplification3() { await TestWithAllCodeStyleOptionsOffAsync( @"class A<T> { class B { } interface I { void Goo(B[][,][,,][,,,] x); } class C<U> : {|CS0535:I|} { } }", @"class A<T> { class B { } interface I { void Goo(B[][,][,,][,,,] x); } class C<U> : I { public void Goo(B[][,][,,][,,,] x) { throw new System.NotImplementedException(); } } }"); } [WorkItem(544166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544166")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementAbstractProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { int Gibberish { get; set; } } abstract class Goo : {|CS0535:IGoo|} { }", @"interface IGoo { int Gibberish { get; set; } } abstract class Goo : IGoo { public abstract int Gibberish { get; set; } }", codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(544210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544210")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingOnWrongArity() { var code = @"interface I1<T> { int X { get; set; } } class C : {|CS0305:I1|} { }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplicitDefaultValue() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IOptional { int Goo(int g = 0); } class Opt : {|CS0535:IOptional|} { }", @"interface IOptional { int Goo(int g = 0); } class Opt : IOptional { public int Goo(int g = 0) { throw new System.NotImplementedException(); } }"); } [WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitDefaultValue() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IOptional { int Goo(int g = 0); } class Opt : {|CS0535:IOptional|} { }", @"interface IOptional { int Goo(int g = 0); } class Opt : IOptional { int IOptional.Goo(int g) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::IOptional;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingInHiddenType() { var code = @"using System; class Program : {|CS0535:IComparable|} { #line hidden } #line default"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestGenerateIntoVisiblePart() { await TestWithAllCodeStyleOptionsOffAsync( @"#line default using System; partial class Program : {|CS0535:IComparable|} { void Goo() { #line hidden } } #line default", @"#line default using System; partial class Program : IComparable { public int CompareTo(object obj) { throw new NotImplementedException(); } void Goo() { #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestGenerateIfAvailableRegionExists() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; partial class Program : {|CS0535:IComparable|} { #line hidden } #line default partial class Program { }", @"using System; partial class Program : IComparable { #line hidden } #line default partial class Program { public int CompareTo(object obj) { throw new NotImplementedException(); } }"); } [WorkItem(545334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545334")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoGenerateInVenusCase1() { var code = @"using System; #line 1 ""Bar"" class Goo : {|CS0535:IComparable|}{|CS1513:|}{|CS1514:|} #line default #line hidden // stuff"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalDateTime1() { await new VerifyCS.Test { TestCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : {|CS0535:IGoo|} { }", FixedCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : IGoo { public void Goo([DateTimeConstant(100), Optional] DateTime x) { throw new NotImplementedException(); } }", Options = { AllOptionsOff }, // 🐛 one value is generated with 0L instead of 0 CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); } [WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalDateTime2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : {|CS0535:IGoo|} { }", @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : IGoo { void IGoo.Goo(DateTime x) { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIUnknownIDispatchAttributes1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : {|CS0535:{|CS0535:IGoo|}|} { }", @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : IGoo { public void Goo1([IUnknownConstant, Optional] object x) { throw new System.NotImplementedException(); } public void Goo2([IDispatchConstant, Optional] object x) { throw new System.NotImplementedException(); } }"); } [WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIUnknownIDispatchAttributes2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : {|CS0535:{|CS0535:IGoo|}|} { }", @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : IGoo { void IGoo.Goo1(object x) { throw new System.NotImplementedException(); } void IGoo.Goo2(object x) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(545464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestTypeNameConflict() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { void Goo(); } public class Goo : {|CS0535:IGoo|} { }", @"interface IGoo { void Goo(); } public class Goo : IGoo { void IGoo.Goo() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStringLiteral() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : {|CS0535:IGoo|} { } ", @"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : IGoo { public void Goo(string s = ""\"""") { throw new System.NotImplementedException(); } } "); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalNullableStructParameter1() { await TestWithAllCodeStyleOptionsOffAsync( @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : {|CS0535:d|} { }", @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : d { public void m(b? x = null, b? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalNullableStructParameter2() { await TestWithAllCodeStyleOptionsOffAsync( @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : {|CS0535:d|} { }", @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : d { void d.m(b? x, b? y) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::d;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalNullableIntParameter() { await TestWithAllCodeStyleOptionsOffAsync( @"interface d { void m(int? x = 5, int? y = null); } class c : {|CS0535:d|} { }", @"interface d { void m(int? x = 5, int? y = null); } class c : d { public void m(int? x = 5, int? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545613")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalWithNoDefaultValue() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { void Goo([Optional] I o); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { void Goo([Optional] I o); } class C : I { public void Goo([Optional] I o) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIntegralAndFloatLiterals() { await new VerifyCS.Test { TestCode = @"interface I { void M01(short s = short.MinValue); void M02(short s = -1); void M03(short s = short.MaxValue); void M04(ushort s = ushort.MinValue); void M05(ushort s = 1); void M06(ushort s = ushort.MaxValue); void M07(int s = int.MinValue); void M08(int s = -1); void M09(int s = int.MaxValue); void M10(uint s = uint.MinValue); void M11(uint s = 1); void M12(uint s = uint.MaxValue); void M13(long s = long.MinValue); void M14(long s = -1); void M15(long s = long.MaxValue); void M16(ulong s = ulong.MinValue); void M17(ulong s = 1); void M18(ulong s = ulong.MaxValue); void M19(float s = float.MinValue); void M20(float s = 1); void M21(float s = float.MaxValue); void M22(double s = double.MinValue); void M23(double s = 1); void M24(double s = double.MaxValue); } class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|} { }", FixedCode = @"interface I { void M01(short s = short.MinValue); void M02(short s = -1); void M03(short s = short.MaxValue); void M04(ushort s = ushort.MinValue); void M05(ushort s = 1); void M06(ushort s = ushort.MaxValue); void M07(int s = int.MinValue); void M08(int s = -1); void M09(int s = int.MaxValue); void M10(uint s = uint.MinValue); void M11(uint s = 1); void M12(uint s = uint.MaxValue); void M13(long s = long.MinValue); void M14(long s = -1); void M15(long s = long.MaxValue); void M16(ulong s = ulong.MinValue); void M17(ulong s = 1); void M18(ulong s = ulong.MaxValue); void M19(float s = float.MinValue); void M20(float s = 1); void M21(float s = float.MaxValue); void M22(double s = double.MinValue); void M23(double s = 1); void M24(double s = double.MaxValue); } class C : I { public void M01(short s = short.MinValue) { throw new System.NotImplementedException(); } public void M02(short s = -1) { throw new System.NotImplementedException(); } public void M03(short s = short.MaxValue) { throw new System.NotImplementedException(); } public void M04(ushort s = 0) { throw new System.NotImplementedException(); } public void M05(ushort s = 1) { throw new System.NotImplementedException(); } public void M06(ushort s = ushort.MaxValue) { throw new System.NotImplementedException(); } public void M07(int s = int.MinValue) { throw new System.NotImplementedException(); } public void M08(int s = -1) { throw new System.NotImplementedException(); } public void M09(int s = int.MaxValue) { throw new System.NotImplementedException(); } public void M10(uint s = 0) { throw new System.NotImplementedException(); } public void M11(uint s = 1) { throw new System.NotImplementedException(); } public void M12(uint s = uint.MaxValue) { throw new System.NotImplementedException(); } public void M13(long s = long.MinValue) { throw new System.NotImplementedException(); } public void M14(long s = -1) { throw new System.NotImplementedException(); } public void M15(long s = long.MaxValue) { throw new System.NotImplementedException(); } public void M16(ulong s = 0) { throw new System.NotImplementedException(); } public void M17(ulong s = 1) { throw new System.NotImplementedException(); } public void M18(ulong s = ulong.MaxValue) { throw new System.NotImplementedException(); } public void M19(float s = float.MinValue) { throw new System.NotImplementedException(); } public void M20(float s = 1) { throw new System.NotImplementedException(); } public void M21(float s = float.MaxValue) { throw new System.NotImplementedException(); } public void M22(double s = double.MinValue) { throw new System.NotImplementedException(); } public void M23(double s = 1) { throw new System.NotImplementedException(); } public void M24(double s = double.MaxValue) { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, // 🐛 one value is generated with 0U instead of 0 CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEnumLiterals() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; enum E { A = 1, B = 2 } [FlagsAttribute] enum FlagE { A = 1, B = 2 } interface I { void M1(E e = E.A | E.B); void M2(FlagE e = FlagE.A | FlagE.B); } class C : {|CS0535:{|CS0535:I|}|} { }", @"using System; enum E { A = 1, B = 2 } [FlagsAttribute] enum FlagE { A = 1, B = 2 } interface I { void M1(E e = E.A | E.B); void M2(FlagE e = FlagE.A | FlagE.B); } class C : I { public void M1(E e = (E)3) { throw new NotImplementedException(); } public void M2(FlagE e = FlagE.A | FlagE.B) { throw new NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCharLiterals() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void M01(char c = '\0'); void M02(char c = '\r'); void M03(char c = '\n'); void M04(char c = '\t'); void M05(char c = '\b'); void M06(char c = '\v'); void M07(char c = '\''); void M08(char c = '“'); void M09(char c = 'a'); void M10(char c = '""'); void M11(char c = '\u2029'); } class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|} { }", @"using System; interface I { void M01(char c = '\0'); void M02(char c = '\r'); void M03(char c = '\n'); void M04(char c = '\t'); void M05(char c = '\b'); void M06(char c = '\v'); void M07(char c = '\''); void M08(char c = '“'); void M09(char c = 'a'); void M10(char c = '""'); void M11(char c = '\u2029'); } class C : I { public void M01(char c = '\0') { throw new NotImplementedException(); } public void M02(char c = '\r') { throw new NotImplementedException(); } public void M03(char c = '\n') { throw new NotImplementedException(); } public void M04(char c = '\t') { throw new NotImplementedException(); } public void M05(char c = '\b') { throw new NotImplementedException(); } public void M06(char c = '\v') { throw new NotImplementedException(); } public void M07(char c = '\'') { throw new NotImplementedException(); } public void M08(char c = '“') { throw new NotImplementedException(); } public void M09(char c = 'a') { throw new NotImplementedException(); } public void M10(char c = '""') { throw new NotImplementedException(); } public void M11(char c = '\u2029') { throw new NotImplementedException(); } }"); } [WorkItem(545695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545695")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRemoveParenthesesAroundTypeReference1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo(DayOfWeek x = DayOfWeek.Friday); } class C : {|CS0535:I|} { DayOfWeek DayOfWeek { get; set; } }", @"using System; interface I { void Goo(DayOfWeek x = DayOfWeek.Friday); } class C : I { DayOfWeek DayOfWeek { get; set; } public void Goo(DayOfWeek x = DayOfWeek.Friday) { throw new NotImplementedException(); } }"); } [WorkItem(545696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545696")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDecimalConstants1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(decimal x = decimal.MaxValue); } class C : {|CS0535:I|} { }", @"interface I { void Goo(decimal x = decimal.MaxValue); } class C : I { public void Goo(decimal x = decimal.MaxValue) { throw new System.NotImplementedException(); } }"); } [WorkItem(545711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNullablePrimitiveLiteral() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(decimal? x = decimal.MaxValue); } class C : {|CS0535:I|} { }", @"interface I { void Goo(decimal? x = decimal.MaxValue); } class C : I { public void Goo(decimal? x = decimal.MaxValue) { throw new System.NotImplementedException(); } }"); } [WorkItem(545715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545715")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNullableEnumType() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo(DayOfWeek? x = DayOfWeek.Friday); } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo(DayOfWeek? x = DayOfWeek.Friday); } class C : I { public void Goo(DayOfWeek? x = DayOfWeek.Friday) { throw new NotImplementedException(); } }"); } [WorkItem(545752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545752")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestByteLiterals() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(byte x = 1); } class C : {|CS0535:I|} { }", @"interface I { void Goo(byte x = 1); } class C : I { public void Goo(byte x = 1) { throw new System.NotImplementedException(); } }"); } [WorkItem(545736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545736")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCastedOptionalParameter1() { const string code = @" using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)(-1)); } class C : {|CS0535:I|} { }"; const string expected = @" using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)(-1)); } class C : I { public void Goo(ConsoleColor x = (ConsoleColor)(-1)) { throw new NotImplementedException(); } }"; await TestWithAllCodeStyleOptionsOffAsync(code, expected); } [WorkItem(545737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545737")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCastedEnumValue() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue); } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue); } class C : I { public void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue) { throw new NotImplementedException(); } }"); } [WorkItem(545785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545785")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoCastFromZeroToEnum() { await TestWithAllCodeStyleOptionsOffAsync( @"enum E { A = 1, } interface I { void Goo(E x = 0); } class C : {|CS0535:I|} { }", @"enum E { A = 1, } interface I { void Goo(E x = 0); } class C : I { public void Goo(E x = 0) { throw new System.NotImplementedException(); } }"); } [WorkItem(545793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMultiDimArray() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y); } class C : I { public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[,] y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545794")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestParametersAfterOptionalParameter() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z); } class C : I { public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[] y = null, int[] z = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545605")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAttributeInParameter() { var test = new VerifyCS.Test { TestCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface I { void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2); } class C : {|CS0535:I|} { } ", FixedCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface I { void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2); } class C : I { public void Goo([DateTimeConstant(100), Optional] DateTime d1, [IUnknownConstant, Optional] object d2) { throw new NotImplementedException(); } } ", // 🐛 the DateTimeConstant attribute is generated with 100L instead of 100 CodeActionValidationMode = CodeActionValidationMode.None, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(545897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545897")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameConflictBetweenMethodAndTypeParameter() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void T1<T>(S x, T y); } class C<T> : {|CS0535:I<T>|} { }", @"interface I<S> { void T1<T>(S x, T y); } class C<T> : I<T> { public void T1<T2>(T x, T2 y) { throw new System.NotImplementedException(); } }"); } [WorkItem(545895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545895")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestTypeParameterReplacementWithOuterType() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; interface I<S> { void Goo<T>(S y, List<T>.Enumerator x); } class D<T> : {|CS0535:I<T>|} { }", @"using System.Collections.Generic; interface I<S> { void Goo<T>(S y, List<T>.Enumerator x); } class D<T> : I<T> { public void Goo<T1>(T y, List<T1>.Enumerator x) { throw new System.NotImplementedException(); } }"); } [WorkItem(545864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545864")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFloatConstant() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(float x = 1E10F); } class C : {|CS0535:I|} { }", @"interface I { void Goo(float x = 1E10F); } class C : I { public void Goo(float x = 1E+10F) { throw new System.NotImplementedException(); } }"); } [WorkItem(544640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544640")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestKeywordForTypeParameterName() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<@class>(); } class C : {|CS0535:I|}{|CS1513:|}{|CS1514:|}", @"interface I { void Goo<@class>(); } class C : I { public void Goo<@class>() { throw new System.NotImplementedException(); } } "); } [WorkItem(545922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545922")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExtremeDecimals() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo1(decimal x = 1E28M); void Goo2(decimal x = -1E28M); } class C : {|CS0535:{|CS0535:I|}|} { }", @"interface I { void Goo1(decimal x = 1E28M); void Goo2(decimal x = -1E28M); } class C : I { public void Goo1(decimal x = 10000000000000000000000000000M) { throw new System.NotImplementedException(); } public void Goo2(decimal x = -10000000000000000000000000000M) { throw new System.NotImplementedException(); } }"); } [WorkItem(544659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544659")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonZeroScaleDecimals() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(decimal x = 0.1M); } class C : {|CS0535:I|} { }", @"interface I { void Goo(decimal x = 0.1M); } class C : I { public void Goo(decimal x = 0.1M) { throw new System.NotImplementedException(); } }"); } [WorkItem(544639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544639")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedComment() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; // Implement interface class C : {|CS0535:IServiceProvider|} {|CS1035:|}/* {|CS1513:|}{|CS1514:|}", @"using System; // Implement interface class C : IServiceProvider /* */ { public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(529920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529920")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNewLineBeforeDirective() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; // Implement interface class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} #pragma warning disable ", @"using System; // Implement interface class C : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } #pragma warning disable "); } [WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCommentAfterInterfaceList1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} // Implement interface ", @"using System; class C : IServiceProvider // Implement interface { public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCommentAfterInterfaceList2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} // Implement interface ", @"using System; class C : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } // Implement interface "); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposable_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; class C : IDisposable { public void Dispose() { throw new NotImplementedException(); } } ", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposable_DisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", $@"using System; class C : IDisposable {{ private bool disposedValue; {DisposePattern("protected virtual ", "C", "public void ")} }} ", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitly_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; class C : IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } ", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitly_DisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:System.IDisposable|} { class IDisposable { } }", $@"using System; class C : System.IDisposable {{ private bool disposedValue; class IDisposable {{ }} {DisposePattern("protected virtual ", "C", "void System.IDisposable.")} }}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableAbstractly_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; abstract class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; abstract class C : IDisposable { public abstract void Dispose(); } ", codeAction: ("False;True;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableThroughMember_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|} { private IDisposable goo; }", @"using System; class C : IDisposable { private IDisposable goo; public void Dispose() { goo.Dispose(); } }", codeAction: ("False;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 2)); } [WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitly_NoNamespaceImportForSystem() { await new VerifyCS.Test { TestCode = @"class C : {|CS0535:System.IDisposable|}{|CS1513:|}{|CS1514:|}", FixedCode = $@"class C : System.IDisposable {{ private bool disposedValue; {DisposePattern("protected virtual ", "C", "void System.IDisposable.", gcPrefix: "System.")} }} ", CodeActionEquivalenceKey = "True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", CodeActionIndex = 3, // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); } [WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableViaBaseInterface_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I : IDisposable { void F(); } class C : {|CS0535:{|CS0535:I|}|} { }", @"using System; interface I : IDisposable { void F(); } class C : I { public void Dispose() { throw new NotImplementedException(); } public void F() { throw new NotImplementedException(); } }", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableViaBaseInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I : IDisposable { void F(); } class C : {|CS0535:{|CS0535:I|}|} { }", $@"using System; interface I : IDisposable {{ void F(); }} class C : I {{ private bool disposedValue; public void F() {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "public void ")} }}", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitlyViaBaseInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I : IDisposable { void F(); } class C : {|CS0535:{|CS0535:I|}|} { }", $@"using System; interface I : IDisposable {{ void F(); }} class C : I {{ private bool disposedValue; void I.F() {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "void IDisposable.")} }}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDontImplementDisposePatternForLocallyDefinedIDisposable() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace System { interface IDisposable { void Dispose(); } class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} }", @"namespace System { interface IDisposable { void Dispose(); } class C : IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } }", codeAction: ("True;False;False:global::System.IDisposable;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDontImplementDisposePatternForStructures1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; struct S : IDisposable { public void Dispose() { throw new NotImplementedException(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDontImplementDisposePatternForStructures2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; struct S : IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } ", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(545924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545924")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEnumNestedInGeneric() { var test = new VerifyCS.Test() { TestCode = @"class C<T> { public enum E { X } } interface I { void Goo<T>(C<T>.E x = C<T>.E.X); } class D : {|CS0535:I|} { }", FixedCode = @"class C<T> { public enum E { X } } interface I { void Goo<T>(C<T>.E x = C<T>.E.X); } class D : I { public void Goo<T>(C<T>.E x = C<T>.E.X) { throw new System.NotImplementedException(); } }", // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:@""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString3() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:@""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString4() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545940")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDecimalENotation() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo1(decimal x = 1E-25M); void Goo2(decimal x = -1E-25M); void Goo3(decimal x = 1E-24M); void Goo4(decimal x = -1E-24M); } class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|} { }", @"interface I { void Goo1(decimal x = 1E-25M); void Goo2(decimal x = -1E-25M); void Goo3(decimal x = 1E-24M); void Goo4(decimal x = -1E-24M); } class C : I { public void Goo1(decimal x = 0.0000000000000000000000001M) { throw new System.NotImplementedException(); } public void Goo2(decimal x = -0.0000000000000000000000001M) { throw new System.NotImplementedException(); } public void Goo3(decimal x = 0.000000000000000000000001M) { throw new System.NotImplementedException(); } public void Goo4(decimal x = -0.000000000000000000000001M) { throw new System.NotImplementedException(); } }"); } [WorkItem(545938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545938")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestGenericEnumWithRenamedTypeParameters() { var test = new VerifyCS.Test { TestCode = @"class C<T> { public enum E { X } } interface I<S> { void Goo<T>(S y, C<T>.E x = C<T>.E.X); } class D<T> : {|CS0535:I<T>|} { }", FixedCode = @"class C<T> { public enum E { X } } interface I<S> { void Goo<T>(S y, C<T>.E x = C<T>.E.X); } class D<T> : I<T> { public void Goo<T1>(T y, C<T1>.E x = C<T1>.E.X) { throw new System.NotImplementedException(); } }", // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(545919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545919")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotRenameTypeParameterToParameterName() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>(S T1); } class C<T> : {|CS0535:I<T>|} { }", @"interface I<S> { void Goo<T>(S T1); } class C<T> : I<T> { public void Goo<T2>(T T1) { throw new System.NotImplementedException(); } }"); } [WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAttributes() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : I { [return: MarshalAs(UnmanagedType.U1)] public bool Goo([MarshalAs(UnmanagedType.U1)] bool x) { throw new System.NotImplementedException(); } }"); } [WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAttributesExplicit() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : I { bool I.Goo(bool x) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(546443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546443")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestParameterNameWithTypeName() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface IGoo { void Bar(DateTime DateTime); } class C : {|CS0535:IGoo|} { }", @"using System; interface IGoo { void Bar(DateTime DateTime); } class C : IGoo { public void Bar(DateTime DateTime) { throw new NotImplementedException(); } }"); } [WorkItem(530521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530521")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnboundGeneric() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))] void Goo(); } class C : {|CS0535:I|} { }", @"using System.Collections.Generic; using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))] void Goo(); } class C : I { [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))] public void Goo() { throw new System.NotImplementedException(); } }"); } [WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestQualifiedNameImplicitInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace N { public interface I { void M(); } } class C : {|CS0535:N.I|} { }", @"namespace N { public interface I { void M(); } } class C : N.I { public void M() { throw new System.NotImplementedException(); } }"); } [WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestQualifiedNameExplicitInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace N { public interface I { void M(); } } class C : {|CS0535:N.I|} { }", @"using N; namespace N { public interface I { void M(); } } class C : N.I { void I.M() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::N.I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForPartialType() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface I { void Goo(); } partial class C { } partial class C : {|CS0535:I|} { }", @"public interface I { void Goo(); } partial class C { } partial class C : I { void I.Goo() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForPartialType2() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface I { void Goo(); } partial class C : {|CS0535:I|} { } partial class C { }", @"public interface I { void Goo(); } partial class C : I { void I.Goo() { throw new System.NotImplementedException(); } } partial class C { }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForPartialType3() { await new VerifyCS.Test { TestCode = @"public interface I { void Goo(); } public interface I2 { void Goo2(); } partial class C : {|CS0535:I|} { } partial class C : {|CS0535:I2|} { }", FixedState = { Sources = { @"public interface I { void Goo(); } public interface I2 { void Goo2(); } partial class C : I { void I.Goo() { throw new System.NotImplementedException(); } } partial class C : {|CS0535:I2|} { }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(752447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752447")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitImplOfIndexedProperty() { var test = new VerifyCS.Test { TestState = { Sources = { @" public class Test : {|CS0535:{|CS0535:IGoo|}|} { }", }, AdditionalProjects = { ["Assembly1", LanguageNames.VisualBasic] = { Sources = { @" Public Interface IGoo Property IndexProp(ByVal p1 As Integer) As String End Interface", }, }, }, AdditionalProjectReferences = { "Assembly1", }, }, FixedState = { Sources = { @" public class Test : IGoo { string IGoo.get_IndexProp(int p1) { throw new System.NotImplementedException(); } void IGoo.set_IndexProp(int p1, string Value) { throw new System.NotImplementedException(); } }", }, }, CodeActionEquivalenceKey = "True;False;False:global::IGoo;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(602475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602475")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplicitImplOfIndexedProperty() { await new VerifyCS.Test { TestState = { Sources = { @"using System; class C : {|CS0535:{|CS0535:I|}|} { }", }, AdditionalProjects = { ["Assembly1", LanguageNames.VisualBasic] = { Sources = { @"Public Interface I Property P(x As Integer) End Interface", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"using System; class C : I { public object get_P(int x) { throw new NotImplementedException(); } public void set_P(int x, object Value) { throw new NotImplementedException(); } }", }, }, CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementationOfIndexerWithInaccessibleAttributes() { var test = new VerifyCS.Test { TestState = { Sources = { @" using System; class C : {|CS0535:I|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @" using System; internal class ShouldBeRemovedAttribute : Attribute { } public interface I { string this[[ShouldBeRemovedAttribute] int i] { get; set; } }" }, }, }, AdditionalProjectReferences = { "Assembly1", }, }, FixedState = { Sources = { @" using System; class C : I { public string this[int i] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } }", }, }, CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } #if false [WorkItem(13677)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoGenerateInVenusCase2() { await TestMissingAsync( @"using System; #line 1 ""Bar"" class Goo : [|IComparable|] #line default #line hidden"); } #endif [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForImplicitIDisposable() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { }", $@"using System; class Program : IDisposable {{ private bool disposedValue; {DisposePattern("protected virtual ", "Program", "public void ")} }}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForExplicitIDisposable() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { private bool DisposedValue; }", $@"using System; class Program : IDisposable {{ private bool DisposedValue; private bool disposedValue; {DisposePattern("protected virtual ", "Program", "void IDisposable.")} }}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForIDisposableNonApplicable1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { private bool disposedValue; }", @"using System; class Program : IDisposable { private bool disposedValue; public void Dispose() { throw new NotImplementedException(); } }", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForIDisposableNonApplicable2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { public void Dispose(bool flag) { } }", @"using System; class Program : IDisposable { public void Dispose(bool flag) { } public void Dispose() { throw new NotImplementedException(); } }", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForExplicitIDisposableWithSealedClass() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; sealed class Program : {|CS0535:IDisposable|} { }", $@"using System; sealed class Program : IDisposable {{ private bool disposedValue; {DisposePattern("private ", "Program", "void IDisposable.")} }}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForExplicitIDisposableWithExistingField() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { private bool disposedValue; }", $@"using System; class Program : IDisposable {{ private bool disposedValue; private bool disposedValue1; {DisposePattern("protected virtual ", "Program", "public void ", disposeField: "disposedValue1")} }}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceUnderscoreNameForFields() { await new VerifyCS.Test { TestCode = @"using System; class Program : {|CS0535:IDisposable|} { }", FixedCode = $@"using System; class Program : IDisposable {{ private bool _disposedValue; {DisposePattern("protected virtual ", "Program", "public void ", disposeField: "_disposedValue")} }}", Options = { _options.FieldNamesAreCamelCaseWithUnderscorePrefix, }, CodeActionEquivalenceKey = "False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoComAliasNameAttributeOnMethodParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p); } class C : {|CS0535:I|} { }", @"interface I { void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p); } class C : I { public void M(int p) { throw new System.NotImplementedException(); } }"); } [WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoComAliasNameAttributeOnMethodReturnType() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { [return: ComAliasName(""pAlias1"")] long M([ComAliasName(""pAlias2"")] int p); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { [return: ComAliasName(""pAlias1"")] long M([ComAliasName(""pAlias2"")] int p); } class C : I { public long M(int p) { throw new System.NotImplementedException(); } }"); } [WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoComAliasNameAttributeOnIndexerParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; } } class C : {|CS0535:I|} { }", @"interface I { long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; } } class C : I { public long this[int p] { get { throw new System.NotImplementedException(); } } }"); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingOpenBrace() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace Scenarios { public interface TestInterface { void M1(); } struct TestStruct1 : {|CS0535:TestInterface|}{|CS1513:|}{|CS1514:|} // Comment }", @"namespace Scenarios { public interface TestInterface { void M1(); } struct TestStruct1 : TestInterface { public void M1() { throw new System.NotImplementedException(); } } // Comment }"); } [WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced1() { //CSharpFeaturesResources.DisposePattern await TestWithAllCodeStyleOptionsOffAsync( @"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T { System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; } partial class C { } partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|} { }", $@"using System; using System.Collections.Generic; interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T {{ System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; }} partial class C {{ }} partial class C : I<System.Exception, System.AggregateException>, System.IDisposable {{ private bool disposedValue; public bool Equals(int other) {{ throw new NotImplementedException(); }} public List<AggregateException> M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c) {{ throw new NotImplementedException(); }} public List<UU> M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c) where UU : TT {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "public void ")} }}", codeAction: ("False;False;True:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T { System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; } partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|} { } partial class C { }", $@"using System; using System.Collections.Generic; interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T {{ System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; }} partial class C : I<System.Exception, System.AggregateException>, System.IDisposable {{ private bool disposedValue; bool IEquatable<int>.Equals(int other) {{ throw new NotImplementedException(); }} List<AggregateException> I<Exception, AggregateException>.M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c) {{ throw new NotImplementedException(); }} List<UU> I<Exception, AggregateException>.M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c) {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "void IDisposable.")} }} partial class C {{ }}", codeAction: ("True;False;False:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } private static string DisposePattern( string disposeVisibility, string className, string implementationVisibility, string disposeField = "disposedValue", string gcPrefix = "") { return $@" {disposeVisibility}void Dispose(bool disposing) {{ if (!{disposeField}) {{ if (disposing) {{ // {FeaturesResources.TODO_colon_dispose_managed_state_managed_objects} }} // {FeaturesResources.TODO_colon_free_unmanaged_resources_unmanaged_objects_and_override_finalizer} // {FeaturesResources.TODO_colon_set_large_fields_to_null} {disposeField} = true; }} }} // // {string.Format(FeaturesResources.TODO_colon_override_finalizer_only_if_0_has_code_to_free_unmanaged_resources, "Dispose(bool disposing)")} // ~{className}() // {{ // // {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")} // Dispose(disposing: false); // }} {implementationVisibility}Dispose() {{ // {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")} Dispose(disposing: true); {gcPrefix}GC.SuppressFinalize(this); }}"; } [WorkItem(1132014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1132014")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAttributes() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; public class Goo : {|CS0535:Holder.SomeInterface|} { } public class Holder { public interface SomeInterface { void Something([SomeAttribute] string helloWorld); } private class SomeAttribute : Attribute { } }", @"using System; public class Goo : Holder.SomeInterface { public void Something(string helloWorld) { throw new NotImplementedException(); } } public class Holder { public interface SomeInterface { void Something([SomeAttribute] string helloWorld); } private class SomeAttribute : Attribute { } }"); } [WorkItem(2785, "https://github.com/dotnet/roslyn/issues/2785")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughStaticMemberInGenericClass() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Issue2785<T> : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:IList<object>|}|}|}|}|}|}|}|}|}|}|}|}|} { private static List<object> innerList = new List<object>(); }", @"using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Issue2785<T> : IList<object> { private static List<object> innerList = new List<object>(); public object this[int index] { get { return ((IList<object>)innerList)[index]; } set { ((IList<object>)innerList)[index] = value; } } public int Count { get { return ((ICollection<object>)innerList).Count; } } public bool IsReadOnly { get { return ((ICollection<object>)innerList).IsReadOnly; } } public void Add(object item) { ((ICollection<object>)innerList).Add(item); } public void Clear() { ((ICollection<object>)innerList).Clear(); } public bool Contains(object item) { return ((ICollection<object>)innerList).Contains(item); } public void CopyTo(object[] array, int arrayIndex) { ((ICollection<object>)innerList).CopyTo(array, arrayIndex); } public IEnumerator<object> GetEnumerator() { return ((IEnumerable<object>)innerList).GetEnumerator(); } public int IndexOf(object item) { return ((IList<object>)innerList).IndexOf(item); } public void Insert(int index, object item) { ((IList<object>)innerList).Insert(index, item); } public bool Remove(object item) { return ((ICollection<object>)innerList).Remove(item); } public void RemoveAt(int index) { ((IList<object>)innerList).RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)innerList).GetEnumerator(); } }", codeAction: ("False;False;False:global::System.Collections.Generic.IList<object>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;innerList", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task LongTuple() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y); } class Class : {|CS0535:IInterface|} { (int, string) x; }", @"interface IInterface { (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y); } class Class : IInterface { (int, string) x; public (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task LongTupleWithNames() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y); } class Class : {|CS0535:IInterface|} { (int, string) x; }", @"interface IInterface { (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y); } class Class : IInterface { (int, string) x; public (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task GenericWithTuple() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface<TA, TB> { (TA, TB) Method1((TA, TB) y); } class Class : {|CS0535:IInterface<(int, string), int>|} { (int, string) x; }", @"interface IInterface<TA, TB> { (TA, TB) Method1((TA, TB) y); } class Class : IInterface<(int, string), int> { (int, string) x; public ((int, string), int) Method1(((int, string), int) y) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task GenericWithTupleWithNamess() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface<TA, TB> { (TA a, TB b) Method1((TA a, TB b) y); } class Class : {|CS0535:IInterface<(int, string), int>|} { (int, string) x; }", @"interface IInterface<TA, TB> { (TA a, TB b) Method1((TA a, TB b) y); } class Class : IInterface<(int, string), int> { (int, string) x; public ((int, string) a, int b) Method1(((int, string) a, int b) y) { throw new System.NotImplementedException(); } }"); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithGroupingOff1() { await new VerifyCS.Test { TestCode = @"interface IInterface { int Prop { get; } } class Class : {|CS0535:IInterface|} { void M() { } }", FixedCode = @"interface IInterface { int Prop { get; } } class Class : IInterface { void M() { } public int Prop => throw new System.NotImplementedException(); }", Options = { { ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd }, }, }.RunAsync(); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotReorderComImportMembers_01() { await TestInRegularAndScriptAsync( @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload(); void X(); void MOverload(int i); int Prop { get; } } class Class : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IComInterface|}|}|}|} { }", @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload(); void X(); void MOverload(int i); int Prop { get; } } class Class : IComInterface { public void MOverload() { throw new System.NotImplementedException(); } public void X() { throw new System.NotImplementedException(); } public void MOverload(int i) { throw new System.NotImplementedException(); } public int Prop => throw new System.NotImplementedException(); }"); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotReorderComImportMembers_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload() { } void X() { } void MOverload(int i) { } int Prop { get; } } class Class : {|CS0535:IComInterface|} { }", FixedCode = @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload() { } void X() { } void MOverload(int i) { } int Prop { get; } } class Class : IComInterface { public int Prop => throw new System.NotImplementedException(); }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReturns() { await TestInRegularAndScriptAsync( @" using System; interface I { ref int IGoo(); ref int Goo { get; } ref int this[int i] { get; } } class C : {|CS0535:{|CS0535:{|CS0535:I|}|}|} { }", @" using System; interface I { ref int IGoo(); ref int Goo { get; } ref int this[int i] { get; } } class C : I { public ref int this[int i] => throw new NotImplementedException(); public ref int Goo => throw new NotImplementedException(); public ref int IGoo() { throw new NotImplementedException(); } }"); } [WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")] [WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAutoProperties() { await new VerifyCS.Test() { TestCode = @"interface IInterface { int ReadOnlyProp { get; } int ReadWriteProp { get; set; } int WriteOnlyProp { set; } } class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedCode = @"interface IInterface { int ReadOnlyProp { get; } int ReadWriteProp { get; set; } int WriteOnlyProp { set; } } class Class : IInterface { public int ReadOnlyProp { get; } public int ReadWriteProp { get; set; } public int WriteOnlyProp { set => throw new System.NotImplementedException(); } }", Options = { { ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalParameterWithDefaultLiteral() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_1, TestCode = @" using System.Threading; interface IInterface { void Method1(CancellationToken cancellationToken = default(CancellationToken)); } class Class : {|CS0535:IInterface|} { }", FixedCode = @" using System.Threading; interface IInterface { void Method1(CancellationToken cancellationToken = default(CancellationToken)); } class Class : IInterface { public void Method1(CancellationToken cancellationToken = default) { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInWithMethod_Parameters() { await TestInRegularAndScriptAsync( @"interface ITest { void Method(in int p); } public class Test : {|CS0535:ITest|} { }", @"interface ITest { void Method(in int p); } public class Test : ITest { public void Method(in int p) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReadOnlyWithMethod_ReturnType() { await TestInRegularAndScriptAsync( @"interface ITest { ref readonly int Method(); } public class Test : {|CS0535:ITest|} { }", @"interface ITest { ref readonly int Method(); } public class Test : ITest { public ref readonly int Method() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReadOnlyWithProperty() { await TestInRegularAndScriptAsync( @"interface ITest { ref readonly int Property { get; } } public class Test : {|CS0535:ITest|} { }", @"interface ITest { ref readonly int Property { get; } } public class Test : ITest { public ref readonly int Property => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInWithIndexer_Parameters() { await TestInRegularAndScriptAsync( @"interface ITest { int this[in int p] { set; } } public class Test : {|CS0535:ITest|} { }", @"interface ITest { int this[in int p] { set; } } public class Test : ITest { public int this[in int p] { set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReadOnlyWithIndexer_ReturnType() { await TestInRegularAndScriptAsync( @"interface ITest { ref readonly int this[int p] { get; } } public class Test : {|CS0535:ITest|} { }", @"interface ITest { ref readonly int this[int p] { get; } } public class Test : ITest { public ref readonly int this[int p] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnmanagedConstraint() { await TestInRegularAndScriptAsync( @"public interface ITest { void M<T>() where T : unmanaged; } public class Test : {|CS0535:ITest|} { }", @"public interface ITest { void M<T>() where T : unmanaged; } public class Test : ITest { public void M<T>() where T : unmanaged { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSealedMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSealedMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSealedMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { protected void M1(); protected int P1 {get;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { }", FixedState = { Sources = { @"interface IInterface { protected void M1(); protected int P1 {get;} } class Class : IInterface { int IInterface.P1 { get { throw new System.NotImplementedException(); } } void IInterface.M1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicAccessor_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicAccessor_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { int P1 {get; protected set;} int P2 {protected get; set;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { }", FixedState = { Sources = { @"interface IInterface { int P1 {get; protected set;} int P2 {protected get; set;} } class Class : IInterface { int IInterface.P1 { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } int IInterface.P2 { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicAccessor_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPrivateAccessor_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPrivateAccessor_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPrivateAccessor_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleMember_01() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); internal void M1(); internal int P1 {get;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass. CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleMember_02() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); internal void M1(); internal int P1 {get;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { void IInterface.Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleMember_03() { await new VerifyCS.Test { TestState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); internal void M1(); internal int P1 {get;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAccessor_01() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); int P1 {get; internal set;} int P2 {internal get; set;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass. CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAccessor_02() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); int P1 {get; internal set;} int P2 {internal get; set;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { void IInterface.Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAccessor_03() { await new VerifyCS.Test { TestState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); int P1 {get; internal set;} int P2 {internal get; set;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestVirtualMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestVirtualMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestVirtualMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNotNullConstraint() { await TestInRegularAndScriptAsync( @"public interface ITest { void M<T>() where T : notnull; } public class Test : {|CS0535:ITest|} { }", @"public interface ITest { void M<T>() where T : notnull; } public class Test : ITest { public void M<T>() where T : notnull { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableProperty() { await TestInRegularAndScriptAsync( @"#nullable enable public interface ITest { string? P { get; } } public class Test : {|CS0535:ITest|} { }", @"#nullable enable public interface ITest { string? P { get; } } public class Test : ITest { public string? P => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullablePropertyAlreadyImplemented() { var code = @"#nullable enable public interface ITest { string? P { get; } } public class Test : ITest { public string? P => throw new System.NotImplementedException(); }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableMethod() { await TestInRegularAndScriptAsync( @"#nullable enable public interface ITest { string? P(); } public class Test : {|CS0535:ITest|} { }", @"#nullable enable public interface ITest { string? P(); } public class Test : ITest { public string? P() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableEvent() { // Question whether this is needed, // see https://github.com/dotnet/roslyn/issues/36673 await TestInRegularAndScriptAsync( @"#nullable enable using System; public interface ITest { event EventHandler? SomeEvent; } public class Test : {|CS0535:ITest|} { }", @"#nullable enable using System; public interface ITest { event EventHandler? SomeEvent; } public class Test : ITest { public event EventHandler? SomeEvent; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableDisabled() { await TestInRegularAndScriptAsync( @"#nullable enable public interface ITest { string? P { get; } } #nullable disable public class Test : {|CS0535:ITest|} { }", @"#nullable enable public interface ITest { string? P { get; } } #nullable disable public class Test : ITest { public string P => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task GenericInterfaceNotNull1() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"#nullable enable using System.Diagnostics.CodeAnalysis; interface IFoo<T> { [return: NotNull] T Bar([DisallowNull] T bar); [return: MaybeNull] T Baz([AllowNull] T bar); } class A : {|CS0535:{|CS0535:IFoo<int>|}|} { }", FixedCode = @"#nullable enable using System.Diagnostics.CodeAnalysis; interface IFoo<T> { [return: NotNull] T Bar([DisallowNull] T bar); [return: MaybeNull] T Baz([AllowNull] T bar); } class A : IFoo<int> { [return: NotNull] public int Bar([DisallowNull] int bar) { throw new System.NotImplementedException(); } [return: MaybeNull] public int Baz([AllowNull] int bar) { throw new System.NotImplementedException(); } }", }.RunAsync(); } [WorkItem(13427, "https://github.com/dotnet/roslyn/issues/13427")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotAddNewWithGenericAndNonGenericMethods() { await TestWithAllCodeStyleOptionsOffAsync( @"class B { public void M<T>() { } } interface I { void M(); } class D : B, {|CS0535:I|} { }", @"class B { public void M<T>() { } } interface I { void M(); } class D : B, I { public void M() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementRemainingExplicitlyWhenPartiallyImplemented() { await TestInRegularAndScriptAsync(@" interface I { void M1(); void M2(); } class C : {|CS0535:I|} { public void M1(){} }", @" interface I { void M1(); void M2(); } class C : {|CS0535:I|} { public void M1(){} void I.M2() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementInitOnlyProperty() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp9, TestCode = @" interface I { int Property { get; init; } } class C : {|CS0535:I|} { }", FixedCode = @" interface I { int Property { get; init; } } class C : I { public int Property { get => throw new System.NotImplementedException(); init => throw new System.NotImplementedException(); } }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementRemainingExplicitlyMissingWhenAllImplemented() { var code = @" interface I { void M1(); void M2(); } class C : I { public void M1(){} public void M2(){} }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementRemainingExplicitlyMissingWhenAllImplementedAreExplicit() { var code = @" interface I { void M1(); void M2(); } class C : {|CS0535:I|} { void I.M1(){} }"; var fixedCode = @" interface I { void M1(); void M2(); } class C : I { public void M2() { throw new System.NotImplementedException(); } void I.M1(){} }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementRemainingExplicitlyNonPublicMember() { await TestInRegularAndScriptAsync(@" interface I { void M1(); internal void M2(); } class C : {|CS0535:I|} { public void M1(){} }", @" interface I { void M1(); internal void M2(); } class C : {|CS0535:I|} { public void M1(){} void I.M2() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementOnRecord_WithSemiColon() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface I { void M1(); } record C : {|CS0535:I|}; ", FixedCode = @" interface I { void M1(); } record C : {|CS0535:I|} { public void M1() { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementOnRecord_WithBracesAndTrivia() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface I { void M1(); } record C : {|CS0535:I|} { } // hello ", FixedCode = @" interface I { void M1(); } record C : {|CS0535:I|} { public void M1() { throw new System.NotImplementedException(); } } // hello ", }.RunAsync(); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TestImplementOnRecord_WithSemiColonAndTrivia(string record) { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = $@" interface I {{ void M1(); }} {record} C : {{|CS0535:I|}}; // hello ", FixedCode = $@" interface I {{ void M1(); }} {record} C : {{|CS0535:I|}} // hello {{ public void M1() {{ throw new System.NotImplementedException(); }} }} ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnconstrainedGenericInstantiatedWithValueType() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @"#nullable enable interface IGoo<T> { void Bar(T? x); } class C : {|CS0535:IGoo<int>|} { } ", FixedCode = @"#nullable enable interface IGoo<T> { void Bar(T? x); } class C : IGoo<int> { public void Bar(int x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstrainedGenericInstantiatedWithValueType() { await TestInRegularAndScriptAsync(@" interface IGoo<T> where T : struct { void Bar(T? x); } class C : {|CS0535:IGoo<int>|} { } ", @" interface IGoo<T> where T : struct { void Bar(T? x); } class C : IGoo<int> { public void Bar(int? x) { throw new System.NotImplementedException(); } } "); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnconstrainedGenericInstantiatedWithReferenceType() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @" interface IGoo<T> { #nullable enable void Bar(T? x); #nullable restore } class C : {|CS0535:IGoo<string>|} { } ", FixedCode = @" interface IGoo<T> { #nullable enable void Bar(T? x); #nullable restore } class C : IGoo<string> { public void Bar(string x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @" #nullable enable interface IGoo<T> { void Bar(T? x); } class C : {|CS0535:IGoo<string>|} { } ", FixedCode = @" #nullable enable interface IGoo<T> { void Bar(T? x); } class C : IGoo<string> { public void Bar(string? x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstrainedGenericInstantiatedWithReferenceType() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : {|CS0535:IGoo<string>|} { } ", FixedCode = @" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : IGoo<string> { public void Bar(string? x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable() { await TestInRegularAndScriptAsync(@" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : {|CS0535:IGoo<string>|} { } ", @" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : IGoo<string> { public void Bar(string? x) { throw new System.NotImplementedException(); } } "); } [WorkItem(51779, "https://github.com/dotnet/roslyn/issues/51779")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementTwoPropertiesOfCSharp5() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp5, TestCode = @" interface ITest { int Bar { get; } int Foo { get; } } class Program : {|CS0535:{|CS0535:ITest|}|} { } ", FixedCode = @" interface ITest { int Bar { get; } int Foo { get; } } class Program : ITest { public int Bar { get { throw new System.NotImplementedException(); } } public int Foo { get { throw new System.NotImplementedException(); } } } ", }.RunAsync(); } [WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceMember() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract void M1(); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract void M1(); } class C : ITest { public static void M1() { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceMemberExplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract void M1(); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract void M1(); } class C : ITest { static void ITest.M1() { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceMember_ImplementAbstractly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract void M1(); } abstract class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract void M1(); } abstract class C : ITest { public static void M1() { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title), CodeActionEquivalenceKey = "False;True;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_OnlyExplicitlyImplementable() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract int operator -(ITest x); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract int operator -(ITest x); } class C : ITest { static int ITest.operator -(ITest x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_ImplementImplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); static abstract int operator -(T x, int y); } class C : {|CS0535:{|CS0535:ITest<C>|}|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); static abstract int operator -(T x, int y); } class C : ITest<C> { public static int operator -(C x) { throw new System.NotImplementedException(); } public static int operator -(C x, int y) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_ImplementExplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } class C : ITest<C> { static int ITest<C>.operator -(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_ImplementAbstractly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } abstract class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } abstract class C : ITest<C> { public static int operator -(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title), CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_Explicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract int M(ITest x); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract int M(ITest x); } class C : ITest { static int ITest.M(ITest x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_Implicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract int M(ITest x); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract int M(ITest x); } class C : ITest { public static int M(ITest x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_ImplementImplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : ITest<C> { public static int M(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_ImplementExplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : ITest<C> { static int ITest<C>.M(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_ImplementAbstractly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } abstract class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } abstract class C : ITest<C> { public static int M(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title), CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Testing; using Roslyn.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.Testing.EmptyDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.ImplementInterface.CSharpImplementInterfaceCodeFixProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface { public class ImplementInterfaceTests { private readonly NamingStylesTestOptionSets _options = new NamingStylesTestOptionSets(LanguageNames.CSharp); private static OptionsCollection AllOptionsOff => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; private static OptionsCollection AllOptionsOn => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, }; private static OptionsCollection AccessorOptionsOn => new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, { CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement }, }; internal static async Task TestWithAllCodeStyleOptionsOffAsync( string initialMarkup, string expectedMarkup, (string equivalenceKey, int index)? codeAction = null) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AllOptionsOff }, CodeActionEquivalenceKey = codeAction?.equivalenceKey, CodeActionIndex = codeAction?.index, }.RunAsync(); } internal static async Task TestWithAllCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AllOptionsOn }, }.RunAsync(); } internal static async Task TestWithAccessorCodeStyleOptionsOnAsync(string initialMarkup, string expectedMarkup) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, Options = { AccessorOptionsOn }, }.RunAsync(); } private static async Task TestInRegularAndScriptAsync( string initialMarkup, string expectedMarkup, (string equivalenceKey, int index)? codeAction = null) { await new VerifyCS.Test { TestCode = initialMarkup, FixedCode = expectedMarkup, CodeActionEquivalenceKey = codeAction?.equivalenceKey, CodeActionIndex = codeAction?.index, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void Method1(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void Method1(); } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodInRecord() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.Preview, TestCode = @"interface IInterface { void Method1(); } record Record : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); } record Record : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [WorkItem(42986, "https://github.com/dotnet/roslyn/issues/42986")] public async Task TestMethodWithNativeIntegers() { var nativeIntegerAttributeDefinition = @" namespace System.Runtime.CompilerServices { [System.AttributeUsage(AttributeTargets.All)] public sealed class NativeIntegerAttribute : System.Attribute { public NativeIntegerAttribute() { } public NativeIntegerAttribute(bool[] flags) { } } }"; // Note: we're putting the attribute by hand to simulate metadata await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @"interface IInterface { [return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}] (nint, nuint) Method(nint x, nuint x2); } class Class : {|CS0535:IInterface|} { }" + nativeIntegerAttributeDefinition, FixedCode = @"interface IInterface { [return: {|CS8335:System.Runtime.CompilerServices.NativeInteger(new[] { true, true })|}] (nint, nuint) Method(nint x, nuint x2); } class Class : IInterface { public (nint, nuint) Method(nint x, nuint x2) { throw new System.NotImplementedException(); } }" + nativeIntegerAttributeDefinition, Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodWithTuple() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { (int, int) Method((string, string) x); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { (int, int) Method((string, string) x); } class Class : IInterface { public (int, int) Method((string, string) x) { throw new System.NotImplementedException(); } }"); } [WorkItem(16793, "https://github.com/dotnet/roslyn/issues/16793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodWithValueTupleArity1() { await TestWithAllCodeStyleOptionsOffAsync( @" using System; interface I { ValueTuple<object> F(); } class C : {|CS0535:I|} { }", @" using System; interface I { ValueTuple<object> F(); } class C : I { public ValueTuple<object> F() { throw new NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExpressionBodiedMethod1() { await TestWithAllCodeStyleOptionsOnAsync( @"interface IInterface { void Method1(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void Method1(); } class Class : IInterface { public void Method1() => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInMethod() { // Note: we're putting the attribute by hand to simulate metadata await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : IInterface { public (int a, int b)[] Method1((int c, string) x) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInMethod_Explicitly() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Method1((int c, string) x); } class Class : IInterface { (int a, int b)[] IInterface.Method1((int c, string) x) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; } } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] (int a, int b)[] Property1 { [return: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] get; [param: {|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] set; } } class Class : IInterface { public (int a, int b)[] Property1 { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task TupleWithNamesInEvent() { await new VerifyCS.Test { TestCode = @"interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] event System.Func<(int a, int b)> Event1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"using System; interface IInterface { [{|CS8138:System.Runtime.CompilerServices.TupleElementNames(new[] { ""a"", ""b"" })|}] event System.Func<(int a, int b)> Event1; } class Class : IInterface { public event Func<(int a, int b)> Event1; }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task NoDynamicAttributeInMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { [return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}] object Method1(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { [return: {|CS1970:System.Runtime.CompilerServices.DynamicAttribute()|}] object Method1(); } class Class : IInterface { public object Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task NoNullableAttributesInMethodFromMetadata() { var test = new VerifyCS.Test { TestState = { Sources = { @" #nullable enable using System; class C : {|CS0535:{|CS0535:IInterface|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @" #nullable enable public interface IInterface { void M(string? s1, string s2); string this[string? s1, string s2] { get; set; } }" }, }, }, AdditionalProjectReferences = { "Assembly1", }, }, FixedState = { Sources = { @" #nullable enable using System; class C : IInterface { public string this[string? s1, string s2] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void M(string? s1, string s2) { throw new NotImplementedException(); } }", }, }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethodWhenClassBracesAreMissing() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void Method1(); } class Class : {|CS0535:IInterface|}{|CS1513:|}{|CS1514:|}", @"interface IInterface { void Method1(); } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritance1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { } class Class : {|CS0535:IInterface2|} { }", @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritance2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { } interface IInterface2 : IInterface1 { void Method1(); } class Class : {|CS0535:IInterface2|} { }", @"interface IInterface1 { } interface IInterface2 : IInterface1 { void Method1(); } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritance3() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method2(); } class Class : {|CS0535:{|CS0535:IInterface2|}|} { }", @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method2(); } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } public void Method2() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInheritanceMatchingMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method1(); } class Class : {|CS0535:{|CS0535:IInterface2|}|} { }", @"interface IInterface1 { void Method1(); } interface IInterface2 : IInterface1 { void Method1(); } class Class : IInterface2 { public void Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExistingConflictingMethodReturnType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(); } class Class : {|CS0738:IInterface1|} { public int Method1() { return 0; } }", @"interface IInterface1 { void Method1(); } class Class : IInterface1 { public int Method1() { return 0; } void IInterface1.Method1() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExistingConflictingMethodParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1 { void Method1(int i); } class Class : {|CS0535:IInterface1|} { public void Method1(string i) { } }", @"interface IInterface1 { void Method1(int i); } class Class : IInterface1 { public void Method1(string i) { } public void Method1(int i) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1<T> { void Method1(T t); } class Class : {|CS0535:IInterface1<int>|} { }", @"interface IInterface1<T> { void Method1(T t); } class Class : IInterface1<int> { public void Method1(int t) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericTypeWithGenericMethod() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1<T> { void Method1<U>(T t, U u); } class Class : {|CS0535:IInterface1<int>|} { }", @"interface IInterface1<T> { void Method1<U>(T t, U u); } class Class : IInterface1<int> { public void Method1<U>(int t, U u) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericTypeWithGenericMethodWithNaturalConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; interface IInterface1<T> { void Method1<U>(T t, U u) where U : IList<T>; } class Class : {|CS0535:IInterface1<int>|} { }", @"using System.Collections.Generic; interface IInterface1<T> { void Method1<U>(T t, U u) where U : IList<T>; } class Class : IInterface1<int> { public void Method1<U>(int t, U u) where U : IList<int> { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementGenericTypeWithGenericMethodWithUnexpressibleConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface1<T> { void Method1<U>(T t, U u) where U : T; } class Class : {|CS0535:IInterface1<int>|} { }", @"interface IInterface1<T> { void Method1<U>(T t, U u) where U : T; } class Class : IInterface1<int> { void IInterface1<int>.Method1<U>(int t, U u) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestArrayType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { string[] M(); } class C : {|CS0535:I|} { }", @"interface I { string[] M(); } class C : I { public string[] M() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; }", @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember_FixAll_SameMemberInDifferentType() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; } class D : {|CS0535:I|} { I i; }", @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } } class D : I { I i; public void Method1() { i.Method1(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember_FixAll_FieldInOnePropInAnother() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; } class D : {|CS0535:I|} { I i { get; } }", @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } } class D : I { I i { get; } public void Method1() { i.Method1(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMember_FixAll_FieldInOneNonViableInAnother() { var test = new VerifyCS.Test { TestCode = @"interface I { void Method1(); } class C : {|CS0535:I|} { I i; } class D : {|CS0535:I|} { int i; }", FixedState = { Sources = { @"interface I { void Method1(); } class C : I { I i; public void Method1() { i.Method1(); } } class D : {|CS0535:I|} { int i; }", }, MarkupHandling = MarkupMode.Allow, }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", CodeActionIndex = 1, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMemberInterfaceWithIndexer() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { int this[int x] { get; set; } } class Goo : {|CS0535:IGoo|} { IGoo f; }", @"interface IGoo { int this[int x] { get; set; } } class Goo : IGoo { IGoo f; public int this[int x] { get { return f[x]; } set { f[x] = value; } } }", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;f", 1)); } [WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCast() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections; sealed class X : {|CS0535:IComparer|} { X x; }", @"using System.Collections; sealed class X : IComparer { X x; public int Compare(object x, object y) { return ((IComparer)this.x).Compare(x, y); } }", codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;x", 1)); } [WorkItem(472, "https://github.com/dotnet/roslyn/issues/472")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementThroughFieldMemberRemoveUnnecessaryCastAndThis() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections; sealed class X : {|CS0535:IComparer|} { X a; }", @"using System.Collections; sealed class X : IComparer { X a; public int Compare(object x, object y) { return ((IComparer)a).Compare(x, y); } }", codeAction: ("False;False;False:global::System.Collections.IComparer;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementAbstract() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Method1(); } abstract class C : {|CS0535:I|} { }", @"interface I { void Method1(); } abstract class C : I { public abstract void Method1(); }", codeAction: ("False;True;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceWithRefOutParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"class C : {|CS0535:{|CS0535:I|}|} { I goo; } interface I { void Method1(ref int x, out int y, int z); int Method2(); }", @"class C : I { I goo; public void Method1(ref int x, out int y, int z) { goo.Method1(ref x, out y, z); } public int Method2() { return goo.Method2(); } } interface I { void Method1(ref int x, out int y, int z); int Method2(); }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConflictingMethods1() { await TestWithAllCodeStyleOptionsOffAsync( @"class B { public int Method1() { return 0; } } class C : B, {|CS0738:I|} { } interface I { void Method1(); }", @"class B { public int Method1() { return 0; } } class C : B, I { void I.Method1() { throw new System.NotImplementedException(); } } interface I { void Method1(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConflictingProperties() { await TestWithAllCodeStyleOptionsOffAsync( @"class Test : {|CS0737:I1|} { int Prop { get; set; } } interface I1 { int Prop { get; set; } }", @"class Test : I1 { int Prop { get; set; } int I1.Prop { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } interface I1 { int Prop { get; set; } }"); } [WorkItem(539043, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitProperties() { var code = @"interface I2 { decimal Calc { get; } } class C : I2 { protected decimal pay; decimal I2.Calc { get { return pay; } } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedMethodName() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void @M(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void @M(); } class Class : IInterface { public void M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedMethodKeyword() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { void @int(); } class Class : {|CS0535:IInterface|} { }", @"interface IInterface { void @int(); } class Class : IInterface { public void @int() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceName1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @IInterface { void M(); } class Class : {|CS0737:@IInterface|} { string M() => """"; }", @"interface @IInterface { void M(); } class Class : @IInterface { string M() => """"; void IInterface.M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceName2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @IInterface { void @M(); } class Class : {|CS0737:@IInterface|} { string M() => """"; }", @"interface @IInterface { void @M(); } class Class : @IInterface { string M() => """"; void IInterface.M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceKeyword1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @int { void M(); } class Class : {|CS0737:@int|} { string M() => """"; }", @"interface @int { void M(); } class Class : @int { string M() => """"; void @int.M() { throw new System.NotImplementedException(); } }"); } [WorkItem(539489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539489")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEscapedInterfaceKeyword2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface @int { void @bool(); } class Class : {|CS0737:@int|} { string @bool() => """"; }", @"interface @int { void @bool(); } class Class : @int { string @bool() => """"; void @int.@bool() { throw new System.NotImplementedException(); } }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPropertyFormatting() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface DD { int Prop { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; set; } } public class A : DD { public int Prop { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestProperty_PropertyCodeStyleOn1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestProperty_AccessorCodeStyleOn1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop { get => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexer_IndexerCodeStyleOn1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexer_AccessorCodeStyleOn1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMethod_AllCodeStyleOn1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int M(); } public class A : {|CS0535:DD|} { }", @"public interface DD { int M(); } public class A : DD { public int M() => throw new System.NotImplementedException(); }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyExpressionBodyYes1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop => throw new System.NotImplementedException(); }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyAccessorBodyYes1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop { get => throw new System.NotImplementedException(); } }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyAccessorBodyYes2() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int Prop { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; set; } } public class A : DD { public int Prop { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }"); } [WorkItem(539522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539522")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestReadonlyPropertyExpressionBodyNo1() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface DD { int Prop { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int Prop { get; } } public class A : DD { public int Prop { get { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerExpressionBodyYes1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerExpressionBodyNo1() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; set; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerAccessorExpressionBodyYes1() { await TestWithAccessorCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexerAccessorExpressionBodyYes2() { await TestWithAllCodeStyleOptionsOnAsync( @"public interface DD { int this[int i] { get; set; } } public class A : {|CS0535:DD|} { }", @"public interface DD { int this[int i] { get; set; } } public class A : DD { public int this[int i] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCommentPlacement() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface DD { void Goo(); } public class A : {|CS0535:DD|} { //comments }", @"public interface DD { void Goo(); } public class A : DD { //comments public void Goo() { throw new System.NotImplementedException(); } }"); } [WorkItem(539991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539991")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestBracePlacement() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(540318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540318")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingWithIncompleteMember() { var code = @"interface ITest { void Method(); } class Test : ITest { p {|CS1585:public|} void Method() { throw new System.NotImplementedException(); } }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(541380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541380")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"interface i1 { int p { get; set; } } class c1 : {|CS0535:i1|} { }", @"interface i1 { int p { get; set; } } class c1 : i1 { int i1.p { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", codeAction: ("True;False;False:global::i1;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(541981, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541981")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoDelegateThroughField1() { var code = @"interface I { void Method1(); } class C : {|CS0535:I|} { I i { get; set; } }"; await new VerifyCS.Test { TestCode = code, FixedCode = @"interface I { void Method1(); } class C : I { I i { get; set; } public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); await new VerifyCS.Test { TestCode = code, FixedCode = @"interface I { void Method1(); } class C : I { I i { get; set; } public void Method1() { i.Method1(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;i", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = code, FixedCode = @"interface I { void Method1(); } class C : I { I i { get; set; } void I.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 2, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIReadOnlyListThroughField() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|} { int[] field; }", @"using System.Collections; using System.Collections.Generic; class A : IReadOnlyList<int> { int[] field; public int this[int index] { get { return ((IReadOnlyList<int>)field)[index]; } } public int Count { get { return ((IReadOnlyCollection<int>)field).Count; } } public IEnumerator<int> GetEnumerator() { return ((IEnumerable<int>)field).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return field.GetEnumerator(); } }", codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIReadOnlyListThroughProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; class A : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IReadOnlyList<int>|}|}|}|} { int[] field { get; set; } }", @"using System.Collections; using System.Collections.Generic; class A : IReadOnlyList<int> { public int this[int index] { get { return ((IReadOnlyList<int>)field)[index]; } } public int Count { get { return ((IReadOnlyCollection<int>)field).Count; } } int[] field { get; set; } public IEnumerator<int> GetEnumerator() { return ((IEnumerable<int>)field).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return field.GetEnumerator(); } }", codeAction: ("False;False;False:global::System.Collections.Generic.IReadOnlyList<int>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;field", 1)); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a; }", @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A a; public int M() { return ((I)a).M(); } }", codeAction: ("False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", 1)); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField_FieldImplementsMultipleInterfaces() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : {|CS0535:I|}, {|CS0535:I2|} { A a; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : I, {|CS0535:I2|} { A a; public int M() { return ((I)a).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[0], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : {|CS0535:I|}, {|CS0535:I2|} { A a; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I, I2 { int I.M() { return 0; } int I2.M2() { return 0; } } class B : {|CS0535:I|}, I2 { A a; public int M2() { return ((I2)a).M2(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField_MultipleFieldsCanImplementInterface() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a; A aa; }", FixedState = { Sources = { @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A a; A aa; public int M() { return ((I)a).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a; A aa; }", FixedState = { Sources = { @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A a; A aa; public int M() { return ((I)aa).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(4, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;aa", CodeActionIndex = 2, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughField_MultipleFieldsForMultipleInterfaces() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : {|CS0535:I|}, {|CS0535:I2|} { A a; B b; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : I, {|CS0535:I2|} { A a; B b; public int M() { return ((I)a).M(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[0], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;a", CodeActionIndex = 1, }.RunAsync(); await new VerifyCS.Test { TestCode = @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : {|CS0535:I|}, {|CS0535:I2|} { A a; B b; }", FixedState = { Sources = { @"interface I { int M(); } interface I2 { int M2(); } class A : I { int I.M() { return 0; } } class B : I2 { int I2.M2() { return 0; } } class C : {|CS0535:I|}, I2 { A a; B b; public int M2() { return ((I2)b).M2(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "False;False;False:global::I2;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;b", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(18556, "https://github.com/dotnet/roslyn/issues/18556")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughExplicitProperty() { await new VerifyCS.Test { TestCode = @"interface IA { IB B { get; } } interface IB { int M(); } class AB : IA, {|CS0535:IB|} { IB IA.B => null; }", FixedCode = @"interface IA { IB B { get; } } interface IB { int M(); } class AB : IA, IB { IB IA.B => null; public int M() { return ((IA)this).B.M(); } }", Options = { AllOptionsOff }, CodeActionsVerifier = codeActions => Assert.Equal(3, codeActions.Length), CodeActionEquivalenceKey = "False;False;False:global::IB;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;IA.B", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoImplementThroughIndexer() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A this[int index] { get { return null; } } }", FixedCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : I { A this[int index] { get { return null; } } public int M() { throw new System.NotImplementedException(); } }", CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); } [WorkItem(768799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768799")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoImplementThroughWriteOnlyProperty() { await new VerifyCS.Test { TestCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a { set { } } }", FixedCode = @"interface I { int M(); } class A : I { int I.M() { return 0; } } class B : {|CS0535:I|} { A a { set { } } public int M() { throw new System.NotImplementedException(); } }", CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventThroughMember() { await TestInRegularAndScriptAsync(@" interface IGoo { event System.EventHandler E; } class CanGoo : IGoo { public event System.EventHandler E; } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; }", @" using System; interface IGoo { event System.EventHandler E; } class CanGoo : IGoo { public event System.EventHandler E; } class HasCanGoo : IGoo { CanGoo canGoo; public event EventHandler E { add { ((IGoo)canGoo).E += value; } remove { ((IGoo)canGoo).E -= value; } } }", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventThroughExplicitMember() { await TestInRegularAndScriptAsync( @"interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : {|CS0535:IGoo|} { CanGoo canGoo; } ", @"using System; interface IGoo { event System . EventHandler E ; } class CanGoo : IGoo { event System.EventHandler IGoo.E { add { } remove { } } } class HasCanGoo : IGoo { CanGoo canGoo; public event EventHandler E { add { ((IGoo)canGoo).E += value; } remove { ((IGoo)canGoo).E -= value; } } } ", codeAction: ("False;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;canGoo", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEvent() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { event System.EventHandler E; } abstract class Goo : {|CS0535:IGoo|} { }", @"using System; interface IGoo { event System.EventHandler E; } abstract class Goo : IGoo { public event EventHandler E; }", codeAction: ("False;False;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventAbstractly() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { event System.EventHandler E; } abstract class Goo : {|CS0535:IGoo|} { }", @"using System; interface IGoo { event System.EventHandler E; } abstract class Goo : IGoo { public abstract event EventHandler E; }", codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementEventExplicitly() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { event System.EventHandler E; } abstract class Goo : {|CS0535:IGoo|} { }", @"using System; interface IGoo { event System.EventHandler E; } abstract class Goo : IGoo { event EventHandler IGoo.E { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } }", codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFaultToleranceInStaticMembers_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IFoo { static string Name { set; get; } static int {|CS0501:Foo|}(string s); } class Program : IFoo { }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFaultToleranceInStaticMembers_02() { var test = new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IFoo { string Name { set; get; } static int {|CS0501:Foo|}(string s); } class Program : {|CS0535:IFoo|} { }", FixedCode = @"interface IFoo { string Name { set; get; } static int {|CS0501:Foo|}(string s); } class Program : IFoo { public string Name { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFaultToleranceInStaticMembers_03() { var test = new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IGoo { static string Name { set; get; } int Goo(string s); } class Program : {|CS0535:IGoo|} { }", FixedCode = @"interface IGoo { static string Name { set; get; } int Goo(string s); } class Program : IGoo { public int Goo(string s) { throw new System.NotImplementedException(); } }", }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexers() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : {|CS0535:ISomeInterface|} { }", @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : ISomeInterface { public int this[int index] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexersExplicit() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : {|CS0535:ISomeInterface|} { }", @"public interface ISomeInterface { int this[int index] { get; set; } } class IndexerClass : ISomeInterface { int ISomeInterface.this[int index] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", codeAction: ("True;False;False:global::ISomeInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexersWithASingleAccessor() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface ISomeInterface { int this[int index] { get; } } class IndexerClass : {|CS0535:ISomeInterface|} { }", @"public interface ISomeInterface { int this[int index] { get; } } class IndexerClass : ISomeInterface { public int this[int index] { get { throw new System.NotImplementedException(); } } }"); } [WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstraints1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<T>() where T : class; } class A : {|CS0535:I|} { }", @"interface I { void Goo<T>() where T : class; } class A : I { public void Goo<T>() where T : class { throw new System.NotImplementedException(); } }"); } [WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstraintsExplicit() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<T>() where T : class; } class A : {|CS0535:I|} { }", @"interface I { void Goo<T>() where T : class; } class A : I { void I.Goo<T>() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542357, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542357")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUsingAddedForConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<T>() where T : System.Attribute; } class A : {|CS0535:I|} { }", @"using System; interface I { void Goo<T>() where T : System.Attribute; } class A : I { public void Goo<T>() where T : Attribute { throw new NotImplementedException(); } }"); } [WorkItem(542379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542379")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIndexer() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { int this[int x] { get; set; } } class C : {|CS0535:I|} { }", @"interface I { int this[int x] { get; set; } } class C : I { public int this[int x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }"); } [WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRecursiveConstraint1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : I { public void Goo<T>() where T : IComparable<T> { throw new NotImplementedException(); } }"); } [WorkItem(542588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542588")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRecursiveConstraint2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo<T>() where T : IComparable<T>; } class C : I { void I.Goo<T>() { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<string>|} { }", @"interface I<S> { void Goo<T>() where T : class, S; } class A : I<string> { void I<string>.Goo<T>() { throw new System.NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<object>|} { }", @"interface I<S> { void Goo<T>() where T : class, S; } class A : I<object> { public void Goo<T>() where T : class { throw new System.NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint3() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<object>|} { }", @"interface I<S> { void Goo<T>() where T : class, S; } class A : I<object> { void I<object>.Goo<T>() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I<object>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint4() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<Delegate>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<Delegate> { void I<Delegate>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint5() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<MulticastDelegate>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<MulticastDelegate> { void I<MulticastDelegate>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint6() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } delegate void Bar(); class A : {|CS0535:I<Bar>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } delegate void Bar(); class A : I<Bar> { void I<Bar>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint7() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<Enum>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<Enum> { void I<Enum>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint8() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : {|CS0535:I<int[]>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class A : I<int[]> { void I<int[]>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542587")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint9() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } enum E { } class A : {|CS0535:I<E>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } enum E { } class A : I<E> { void I<E>.Goo<{|CS0455:T|}>() { throw new NotImplementedException(); } }"); } [WorkItem(542621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542621")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnexpressibleConstraint10() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : S; } class A : {|CS0535:I<ValueType>|} { }", @"using System; interface I<S> { void Goo<T>() where T : S; } class A : I<ValueType> { void I<ValueType>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542669")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestArrayConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : S; } class C : {|CS0535:I<Array>|} { }", @"using System; interface I<S> { void Goo<T>() where T : S; } class C : I<Array> { void I<Array>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMultipleClassConstraints() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : Exception, S; } class C : {|CS0535:I<Attribute>|} { }", @"using System; interface I<S> { void Goo<T>() where T : Exception, S; } class C : I<Attribute> { void I<Attribute>.Goo<{|CS0455:T|}>() { throw new NotImplementedException(); } }"); } [WorkItem(542751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542751")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestClassConstraintAndRefConstraint() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I<S> { void Goo<T>() where T : class, S; } class C : {|CS0535:I<Exception>|} { }", @"using System; interface I<S> { void Goo<T>() where T : class, S; } class C : I<Exception> { void I<Exception>.Goo<T>() { throw new NotImplementedException(); } }"); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : {|CS0535:I<S>|} { }", @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : I<S> { public void Goo<S1>(S x, IList<S1> list) where S1 : S { throw new NotImplementedException(); } }"); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : {|CS0535:I<S>|} { }", @"using System; using System.Collections.Generic; interface I<T> { void Goo<S>(T x, IList<S> list) where S : T; } class A<S> : I<S> { void I<S>.Goo<S1>(S x, IList<S1> list) { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::I<S>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters3() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : {|CS0535:I<A, B>|} { }", @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : I<A, B> { public void Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2) where A1 : IList<B1> where B1 : IList<A1> { throw new NotImplementedException(); } }"); } [WorkItem(542505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRenameConflictingTypeParameters4() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : {|CS0535:I<A, B>|} { }", @"using System; using System.Collections.Generic; interface I<X, Y> { void Goo<A, B>(X x, Y y, IList<A> list1, IList<B> list2) where A : IList<B> where B : IList<A>; } class C<A, B> : I<A, B> { void I<A, B>.Goo<A1, B1>(A x, B y, IList<A1> list1, IList<B1> list2) { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::I<A, B>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameSimplification() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class A<T> { class B { } interface I { void Goo(B x); } class C<U> : {|CS0535:I|} { } }", @"using System; class A<T> { class B { } interface I { void Goo(B x); } class C<U> : I { public void Goo(B x) { throw new NotImplementedException(); } } }"); } [WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameSimplification2() { await TestWithAllCodeStyleOptionsOffAsync( @"class A<T> { class B { } interface I { void Goo(B[] x); } class C<U> : {|CS0535:I|} { } }", @"class A<T> { class B { } interface I { void Goo(B[] x); } class C<U> : I { public void Goo(B[] x) { throw new System.NotImplementedException(); } } }"); } [WorkItem(542506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542506")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameSimplification3() { await TestWithAllCodeStyleOptionsOffAsync( @"class A<T> { class B { } interface I { void Goo(B[][,][,,][,,,] x); } class C<U> : {|CS0535:I|} { } }", @"class A<T> { class B { } interface I { void Goo(B[][,][,,][,,,] x); } class C<U> : I { public void Goo(B[][,][,,][,,,] x) { throw new System.NotImplementedException(); } } }"); } [WorkItem(544166, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544166")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementAbstractProperty() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { int Gibberish { get; set; } } abstract class Goo : {|CS0535:IGoo|} { }", @"interface IGoo { int Gibberish { get; set; } } abstract class Goo : IGoo { public abstract int Gibberish { get; set; } }", codeAction: ("False;True;True:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(544210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544210")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingOnWrongArity() { var code = @"interface I1<T> { int X { get; set; } } class C : {|CS0305:I1|} { }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplicitDefaultValue() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IOptional { int Goo(int g = 0); } class Opt : {|CS0535:IOptional|} { }", @"interface IOptional { int Goo(int g = 0); } class Opt : IOptional { public int Goo(int g = 0) { throw new System.NotImplementedException(); } }"); } [WorkItem(544281, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544281")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitDefaultValue() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IOptional { int Goo(int g = 0); } class Opt : {|CS0535:IOptional|} { }", @"interface IOptional { int Goo(int g = 0); } class Opt : IOptional { int IOptional.Goo(int g) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::IOptional;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingInHiddenType() { var code = @"using System; class Program : {|CS0535:IComparable|} { #line hidden } #line default"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestGenerateIntoVisiblePart() { await TestWithAllCodeStyleOptionsOffAsync( @"#line default using System; partial class Program : {|CS0535:IComparable|} { void Goo() { #line hidden } } #line default", @"#line default using System; partial class Program : IComparable { public int CompareTo(object obj) { throw new NotImplementedException(); } void Goo() { #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestGenerateIfAvailableRegionExists() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; partial class Program : {|CS0535:IComparable|} { #line hidden } #line default partial class Program { }", @"using System; partial class Program : IComparable { #line hidden } #line default partial class Program { public int CompareTo(object obj) { throw new NotImplementedException(); } }"); } [WorkItem(545334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545334")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoGenerateInVenusCase1() { var code = @"using System; #line 1 ""Bar"" class Goo : {|CS0535:IComparable|}{|CS1513:|}{|CS1514:|} #line default #line hidden // stuff"; await VerifyCS.VerifyCodeFixAsync(code, code); } [WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalDateTime1() { await new VerifyCS.Test { TestCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : {|CS0535:IGoo|} { }", FixedCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : IGoo { public void Goo([DateTimeConstant(100), Optional] DateTime x) { throw new NotImplementedException(); } }", Options = { AllOptionsOff }, // 🐛 one value is generated with 0L instead of 0 CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); } [WorkItem(545476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545476")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalDateTime2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : {|CS0535:IGoo|} { }", @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo([Optional][DateTimeConstant(100)] DateTime x); } public class C : IGoo { void IGoo.Goo(DateTime x) { throw new NotImplementedException(); } }", codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIUnknownIDispatchAttributes1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : {|CS0535:{|CS0535:IGoo|}|} { }", @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : IGoo { public void Goo1([IUnknownConstant, Optional] object x) { throw new System.NotImplementedException(); } public void Goo2([IDispatchConstant, Optional] object x) { throw new System.NotImplementedException(); } }"); } [WorkItem(545477, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545477")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIUnknownIDispatchAttributes2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : {|CS0535:{|CS0535:IGoo|}|} { }", @"using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface IGoo { void Goo1([Optional][IUnknownConstant] object x); void Goo2([Optional][IDispatchConstant] object x); } public class C : IGoo { void IGoo.Goo1(object x) { throw new System.NotImplementedException(); } void IGoo.Goo2(object x) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::IGoo;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(545464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestTypeNameConflict() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { void Goo(); } public class Goo : {|CS0535:IGoo|} { }", @"interface IGoo { void Goo(); } public class Goo : IGoo { void IGoo.Goo() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStringLiteral() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : {|CS0535:IGoo|} { } ", @"interface IGoo { void Goo ( string s = ""\"""" ) ; } class B : IGoo { public void Goo(string s = ""\"""") { throw new System.NotImplementedException(); } } "); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalNullableStructParameter1() { await TestWithAllCodeStyleOptionsOffAsync( @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : {|CS0535:d|} { }", @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : d { public void m(b? x = null, b? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalNullableStructParameter2() { await TestWithAllCodeStyleOptionsOffAsync( @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : {|CS0535:d|} { }", @"struct b { } interface d { void m(b? x = null, b? y = default(b?)); } class c : d { void d.m(b? x, b? y) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::d;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(916114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916114")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalNullableIntParameter() { await TestWithAllCodeStyleOptionsOffAsync( @"interface d { void m(int? x = 5, int? y = null); } class c : {|CS0535:d|} { }", @"interface d { void m(int? x = 5, int? y = null); } class c : d { public void m(int? x = 5, int? y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545613")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalWithNoDefaultValue() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { void Goo([Optional] I o); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { void Goo([Optional] I o); } class C : I { public void Goo([Optional] I o) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestIntegralAndFloatLiterals() { await new VerifyCS.Test { TestCode = @"interface I { void M01(short s = short.MinValue); void M02(short s = -1); void M03(short s = short.MaxValue); void M04(ushort s = ushort.MinValue); void M05(ushort s = 1); void M06(ushort s = ushort.MaxValue); void M07(int s = int.MinValue); void M08(int s = -1); void M09(int s = int.MaxValue); void M10(uint s = uint.MinValue); void M11(uint s = 1); void M12(uint s = uint.MaxValue); void M13(long s = long.MinValue); void M14(long s = -1); void M15(long s = long.MaxValue); void M16(ulong s = ulong.MinValue); void M17(ulong s = 1); void M18(ulong s = ulong.MaxValue); void M19(float s = float.MinValue); void M20(float s = 1); void M21(float s = float.MaxValue); void M22(double s = double.MinValue); void M23(double s = 1); void M24(double s = double.MaxValue); } class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|}|} { }", FixedCode = @"interface I { void M01(short s = short.MinValue); void M02(short s = -1); void M03(short s = short.MaxValue); void M04(ushort s = ushort.MinValue); void M05(ushort s = 1); void M06(ushort s = ushort.MaxValue); void M07(int s = int.MinValue); void M08(int s = -1); void M09(int s = int.MaxValue); void M10(uint s = uint.MinValue); void M11(uint s = 1); void M12(uint s = uint.MaxValue); void M13(long s = long.MinValue); void M14(long s = -1); void M15(long s = long.MaxValue); void M16(ulong s = ulong.MinValue); void M17(ulong s = 1); void M18(ulong s = ulong.MaxValue); void M19(float s = float.MinValue); void M20(float s = 1); void M21(float s = float.MaxValue); void M22(double s = double.MinValue); void M23(double s = 1); void M24(double s = double.MaxValue); } class C : I { public void M01(short s = short.MinValue) { throw new System.NotImplementedException(); } public void M02(short s = -1) { throw new System.NotImplementedException(); } public void M03(short s = short.MaxValue) { throw new System.NotImplementedException(); } public void M04(ushort s = 0) { throw new System.NotImplementedException(); } public void M05(ushort s = 1) { throw new System.NotImplementedException(); } public void M06(ushort s = ushort.MaxValue) { throw new System.NotImplementedException(); } public void M07(int s = int.MinValue) { throw new System.NotImplementedException(); } public void M08(int s = -1) { throw new System.NotImplementedException(); } public void M09(int s = int.MaxValue) { throw new System.NotImplementedException(); } public void M10(uint s = 0) { throw new System.NotImplementedException(); } public void M11(uint s = 1) { throw new System.NotImplementedException(); } public void M12(uint s = uint.MaxValue) { throw new System.NotImplementedException(); } public void M13(long s = long.MinValue) { throw new System.NotImplementedException(); } public void M14(long s = -1) { throw new System.NotImplementedException(); } public void M15(long s = long.MaxValue) { throw new System.NotImplementedException(); } public void M16(ulong s = 0) { throw new System.NotImplementedException(); } public void M17(ulong s = 1) { throw new System.NotImplementedException(); } public void M18(ulong s = ulong.MaxValue) { throw new System.NotImplementedException(); } public void M19(float s = float.MinValue) { throw new System.NotImplementedException(); } public void M20(float s = 1) { throw new System.NotImplementedException(); } public void M21(float s = float.MaxValue) { throw new System.NotImplementedException(); } public void M22(double s = double.MinValue) { throw new System.NotImplementedException(); } public void M23(double s = 1) { throw new System.NotImplementedException(); } public void M24(double s = double.MaxValue) { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, // 🐛 one value is generated with 0U instead of 0 CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEnumLiterals() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; enum E { A = 1, B = 2 } [FlagsAttribute] enum FlagE { A = 1, B = 2 } interface I { void M1(E e = E.A | E.B); void M2(FlagE e = FlagE.A | FlagE.B); } class C : {|CS0535:{|CS0535:I|}|} { }", @"using System; enum E { A = 1, B = 2 } [FlagsAttribute] enum FlagE { A = 1, B = 2 } interface I { void M1(E e = E.A | E.B); void M2(FlagE e = FlagE.A | FlagE.B); } class C : I { public void M1(E e = (E)3) { throw new NotImplementedException(); } public void M2(FlagE e = FlagE.A | FlagE.B) { throw new NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCharLiterals() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void M01(char c = '\0'); void M02(char c = '\r'); void M03(char c = '\n'); void M04(char c = '\t'); void M05(char c = '\b'); void M06(char c = '\v'); void M07(char c = '\''); void M08(char c = '“'); void M09(char c = 'a'); void M10(char c = '""'); void M11(char c = '\u2029'); } class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|}|}|}|}|}|}|}|} { }", @"using System; interface I { void M01(char c = '\0'); void M02(char c = '\r'); void M03(char c = '\n'); void M04(char c = '\t'); void M05(char c = '\b'); void M06(char c = '\v'); void M07(char c = '\''); void M08(char c = '“'); void M09(char c = 'a'); void M10(char c = '""'); void M11(char c = '\u2029'); } class C : I { public void M01(char c = '\0') { throw new NotImplementedException(); } public void M02(char c = '\r') { throw new NotImplementedException(); } public void M03(char c = '\n') { throw new NotImplementedException(); } public void M04(char c = '\t') { throw new NotImplementedException(); } public void M05(char c = '\b') { throw new NotImplementedException(); } public void M06(char c = '\v') { throw new NotImplementedException(); } public void M07(char c = '\'') { throw new NotImplementedException(); } public void M08(char c = '“') { throw new NotImplementedException(); } public void M09(char c = 'a') { throw new NotImplementedException(); } public void M10(char c = '""') { throw new NotImplementedException(); } public void M11(char c = '\u2029') { throw new NotImplementedException(); } }"); } [WorkItem(545695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545695")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRemoveParenthesesAroundTypeReference1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo(DayOfWeek x = DayOfWeek.Friday); } class C : {|CS0535:I|} { DayOfWeek DayOfWeek { get; set; } }", @"using System; interface I { void Goo(DayOfWeek x = DayOfWeek.Friday); } class C : I { DayOfWeek DayOfWeek { get; set; } public void Goo(DayOfWeek x = DayOfWeek.Friday) { throw new NotImplementedException(); } }"); } [WorkItem(545696, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545696")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDecimalConstants1() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(decimal x = decimal.MaxValue); } class C : {|CS0535:I|} { }", @"interface I { void Goo(decimal x = decimal.MaxValue); } class C : I { public void Goo(decimal x = decimal.MaxValue) { throw new System.NotImplementedException(); } }"); } [WorkItem(545711, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNullablePrimitiveLiteral() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(decimal? x = decimal.MaxValue); } class C : {|CS0535:I|} { }", @"interface I { void Goo(decimal? x = decimal.MaxValue); } class C : I { public void Goo(decimal? x = decimal.MaxValue) { throw new System.NotImplementedException(); } }"); } [WorkItem(545715, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545715")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNullableEnumType() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo(DayOfWeek? x = DayOfWeek.Friday); } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo(DayOfWeek? x = DayOfWeek.Friday); } class C : I { public void Goo(DayOfWeek? x = DayOfWeek.Friday) { throw new NotImplementedException(); } }"); } [WorkItem(545752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545752")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestByteLiterals() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(byte x = 1); } class C : {|CS0535:I|} { }", @"interface I { void Goo(byte x = 1); } class C : I { public void Goo(byte x = 1) { throw new System.NotImplementedException(); } }"); } [WorkItem(545736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545736")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCastedOptionalParameter1() { const string code = @" using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)(-1)); } class C : {|CS0535:I|} { }"; const string expected = @" using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)(-1)); } class C : I { public void Goo(ConsoleColor x = (ConsoleColor)(-1)) { throw new NotImplementedException(); } }"; await TestWithAllCodeStyleOptionsOffAsync(code, expected); } [WorkItem(545737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545737")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCastedEnumValue() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue); } class C : {|CS0535:I|} { }", @"using System; interface I { void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue); } class C : I { public void Goo(ConsoleColor x = (ConsoleColor)int.MaxValue) { throw new NotImplementedException(); } }"); } [WorkItem(545785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545785")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoCastFromZeroToEnum() { await TestWithAllCodeStyleOptionsOffAsync( @"enum E { A = 1, } interface I { void Goo(E x = 0); } class C : {|CS0535:I|} { }", @"enum E { A = 1, } interface I { void Goo(E x = 0); } class C : I { public void Goo(E x = 0) { throw new System.NotImplementedException(); } }"); } [WorkItem(545793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545793")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMultiDimArray() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { void Goo([Optional][DefaultParameterValue(1)] int x, int[,] y); } class C : I { public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[,] y = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545794")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestParametersAfterOptionalParameter() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { void Goo([Optional, DefaultParameterValue(1)] int x, int[] y, int[] z); } class C : I { public void Goo([{|CS1745:DefaultParameterValue|}(1), {|CS1745:Optional|}] int x = {|CS8017:1|}, int[] y = null, int[] z = null) { throw new System.NotImplementedException(); } }"); } [WorkItem(545605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545605")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAttributeInParameter() { var test = new VerifyCS.Test { TestCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface I { void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2); } class C : {|CS0535:I|} { } ", FixedCode = @"using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; interface I { void Goo([Optional][DateTimeConstant(100)] DateTime d1, [Optional][IUnknownConstant] object d2); } class C : I { public void Goo([DateTimeConstant(100), Optional] DateTime d1, [IUnknownConstant, Optional] object d2) { throw new NotImplementedException(); } } ", // 🐛 the DateTimeConstant attribute is generated with 100L instead of 100 CodeActionValidationMode = CodeActionValidationMode.None, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(545897, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545897")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNameConflictBetweenMethodAndTypeParameter() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void T1<T>(S x, T y); } class C<T> : {|CS0535:I<T>|} { }", @"interface I<S> { void T1<T>(S x, T y); } class C<T> : I<T> { public void T1<T2>(T x, T2 y) { throw new System.NotImplementedException(); } }"); } [WorkItem(545895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545895")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestTypeParameterReplacementWithOuterType() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; interface I<S> { void Goo<T>(S y, List<T>.Enumerator x); } class D<T> : {|CS0535:I<T>|} { }", @"using System.Collections.Generic; interface I<S> { void Goo<T>(S y, List<T>.Enumerator x); } class D<T> : I<T> { public void Goo<T1>(T y, List<T1>.Enumerator x) { throw new System.NotImplementedException(); } }"); } [WorkItem(545864, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545864")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestFloatConstant() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(float x = 1E10F); } class C : {|CS0535:I|} { }", @"interface I { void Goo(float x = 1E10F); } class C : I { public void Goo(float x = 1E+10F) { throw new System.NotImplementedException(); } }"); } [WorkItem(544640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544640")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestKeywordForTypeParameterName() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo<@class>(); } class C : {|CS0535:I|}{|CS1513:|}{|CS1514:|}", @"interface I { void Goo<@class>(); } class C : I { public void Goo<@class>() { throw new System.NotImplementedException(); } } "); } [WorkItem(545922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545922")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExtremeDecimals() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo1(decimal x = 1E28M); void Goo2(decimal x = -1E28M); } class C : {|CS0535:{|CS0535:I|}|} { }", @"interface I { void Goo1(decimal x = 1E28M); void Goo2(decimal x = -1E28M); } class C : I { public void Goo1(decimal x = 10000000000000000000000000000M) { throw new System.NotImplementedException(); } public void Goo2(decimal x = -10000000000000000000000000000M) { throw new System.NotImplementedException(); } }"); } [WorkItem(544659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544659")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonZeroScaleDecimals() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo(decimal x = 0.1M); } class C : {|CS0535:I|} { }", @"interface I { void Goo(decimal x = 0.1M); } class C : I { public void Goo(decimal x = 0.1M) { throw new System.NotImplementedException(); } }"); } [WorkItem(544639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544639")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedComment() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; // Implement interface class C : {|CS0535:IServiceProvider|} {|CS1035:|}/* {|CS1513:|}{|CS1514:|}", @"using System; // Implement interface class C : IServiceProvider /* */ { public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(529920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529920")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNewLineBeforeDirective() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; // Implement interface class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} #pragma warning disable ", @"using System; // Implement interface class C : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } #pragma warning disable "); } [WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCommentAfterInterfaceList1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} // Implement interface ", @"using System; class C : IServiceProvider // Implement interface { public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(529947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529947")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestCommentAfterInterfaceList2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|}{|CS1513:|}{|CS1514:|} // Implement interface ", @"using System; class C : IServiceProvider { public object GetService(Type serviceType) { throw new NotImplementedException(); } } // Implement interface "); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposable_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; class C : IDisposable { public void Dispose() { throw new NotImplementedException(); } } ", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposable_DisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", $@"using System; class C : IDisposable {{ private bool disposedValue; {DisposePattern("protected virtual ", "C", "public void ")} }} ", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitly_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; class C : IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } ", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitly_DisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:System.IDisposable|} { class IDisposable { } }", $@"using System; class C : System.IDisposable {{ private bool disposedValue; class IDisposable {{ }} {DisposePattern("protected virtual ", "C", "void System.IDisposable.")} }}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableAbstractly_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; abstract class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; abstract class C : IDisposable { public abstract void Dispose(); } ", codeAction: ("False;True;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [WorkItem(994456, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994456")] [WorkItem(958699, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/958699")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableThroughMember_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IDisposable|} { private IDisposable goo; }", @"using System; class C : IDisposable { private IDisposable goo; public void Dispose() { goo.Dispose(); } }", codeAction: ("False;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;goo", 2)); } [WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitly_NoNamespaceImportForSystem() { await new VerifyCS.Test { TestCode = @"class C : {|CS0535:System.IDisposable|}{|CS1513:|}{|CS1514:|}", FixedCode = $@"class C : System.IDisposable {{ private bool disposedValue; {DisposePattern("protected virtual ", "C", "void System.IDisposable.", gcPrefix: "System.")} }} ", CodeActionEquivalenceKey = "True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", CodeActionIndex = 3, // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }.RunAsync(); } [WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableViaBaseInterface_NoDisposePattern() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I : IDisposable { void F(); } class C : {|CS0535:{|CS0535:I|}|} { }", @"using System; interface I : IDisposable { void F(); } class C : I { public void Dispose() { throw new NotImplementedException(); } public void F() { throw new NotImplementedException(); } }", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableViaBaseInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I : IDisposable { void F(); } class C : {|CS0535:{|CS0535:I|}|} { }", $@"using System; interface I : IDisposable {{ void F(); }} class C : I {{ private bool disposedValue; public void F() {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "public void ")} }}", codeAction: ("False;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(951968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/951968")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementIDisposableExplicitlyViaBaseInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface I : IDisposable { void F(); } class C : {|CS0535:{|CS0535:I|}|} { }", $@"using System; interface I : IDisposable {{ void F(); }} class C : I {{ private bool disposedValue; void I.F() {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "void IDisposable.")} }}", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [WorkItem(941469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/941469")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDontImplementDisposePatternForLocallyDefinedIDisposable() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace System { interface IDisposable { void Dispose(); } class C : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|} }", @"namespace System { interface IDisposable { void Dispose(); } class C : IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } }", codeAction: ("True;False;False:global::System.IDisposable;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDontImplementDisposePatternForStructures1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; struct S : IDisposable { public void Dispose() { throw new NotImplementedException(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDontImplementDisposePatternForStructures2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; struct S : {|CS0535:IDisposable|}{|CS1513:|}{|CS1514:|}", @"using System; struct S : IDisposable { void IDisposable.Dispose() { throw new NotImplementedException(); } } ", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(545924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545924")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEnumNestedInGeneric() { var test = new VerifyCS.Test() { TestCode = @"class C<T> { public enum E { X } } interface I { void Goo<T>(C<T>.E x = C<T>.E.X); } class D : {|CS0535:I|} { }", FixedCode = @"class C<T> { public enum E { X } } interface I { void Goo<T>(C<T>.E x = C<T>.E.X); } class D : I { public void Goo<T>(C<T>.E x = C<T>.E.X) { throw new System.NotImplementedException(); } }", // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:@""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString3() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1039:|}@""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:@""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545939")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnterminatedString4() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class C : {|CS0535:IServiceProvider|} {|CS1010:|}""{|CS1513:|}{|CS1514:|}", @"using System; class C : IServiceProvider {|CS1003:""""|}{ public object GetService(Type serviceType) { throw new NotImplementedException(); } } "); } [WorkItem(545940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545940")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDecimalENotation() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void Goo1(decimal x = 1E-25M); void Goo2(decimal x = -1E-25M); void Goo3(decimal x = 1E-24M); void Goo4(decimal x = -1E-24M); } class C : {|CS0535:{|CS0535:{|CS0535:{|CS0535:I|}|}|}|} { }", @"interface I { void Goo1(decimal x = 1E-25M); void Goo2(decimal x = -1E-25M); void Goo3(decimal x = 1E-24M); void Goo4(decimal x = -1E-24M); } class C : I { public void Goo1(decimal x = 0.0000000000000000000000001M) { throw new System.NotImplementedException(); } public void Goo2(decimal x = -0.0000000000000000000000001M) { throw new System.NotImplementedException(); } public void Goo3(decimal x = 0.000000000000000000000001M) { throw new System.NotImplementedException(); } public void Goo4(decimal x = -0.000000000000000000000001M) { throw new System.NotImplementedException(); } }"); } [WorkItem(545938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545938")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestGenericEnumWithRenamedTypeParameters() { var test = new VerifyCS.Test { TestCode = @"class C<T> { public enum E { X } } interface I<S> { void Goo<T>(S y, C<T>.E x = C<T>.E.X); } class D<T> : {|CS0535:I<T>|} { }", FixedCode = @"class C<T> { public enum E { X } } interface I<S> { void Goo<T>(S y, C<T>.E x = C<T>.E.X); } class D<T> : I<T> { public void Goo<T1>(T y, C<T1>.E x = C<T1>.E.X) { throw new System.NotImplementedException(); } }", // 🐛 generated QualifiedName where SimpleMemberAccessExpression was expected CodeActionValidationMode = CodeActionValidationMode.None, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(545919, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545919")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotRenameTypeParameterToParameterName() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<S> { void Goo<T>(S T1); } class C<T> : {|CS0535:I<T>|} { }", @"interface I<S> { void Goo<T>(S T1); } class C<T> : I<T> { public void Goo<T2>(T T1) { throw new System.NotImplementedException(); } }"); } [WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAttributes() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : I { [return: MarshalAs(UnmanagedType.U1)] public bool Goo([MarshalAs(UnmanagedType.U1)] bool x) { throw new System.NotImplementedException(); } }"); } [WorkItem(530265, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530265")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAttributesExplicit() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.U1)] bool Goo([MarshalAs(UnmanagedType.U1)] bool x); } class C : I { bool I.Goo(bool x) { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(546443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546443")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestParameterNameWithTypeName() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; interface IGoo { void Bar(DateTime DateTime); } class C : {|CS0535:IGoo|} { }", @"using System; interface IGoo { void Bar(DateTime DateTime); } class C : IGoo { public void Bar(DateTime DateTime) { throw new NotImplementedException(); } }"); } [WorkItem(530521, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530521")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnboundGeneric() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Collections.Generic; using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))] void Goo(); } class C : {|CS0535:I|} { }", @"using System.Collections.Generic; using System.Runtime.InteropServices; interface I { [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))] void Goo(); } class C : I { [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(List<>))] public void Goo() { throw new System.NotImplementedException(); } }"); } [WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestQualifiedNameImplicitInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace N { public interface I { void M(); } } class C : {|CS0535:N.I|} { }", @"namespace N { public interface I { void M(); } } class C : N.I { public void M() { throw new System.NotImplementedException(); } }"); } [WorkItem(752436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752436")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestQualifiedNameExplicitInterface() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace N { public interface I { void M(); } } class C : {|CS0535:N.I|} { }", @"using N; namespace N { public interface I { void M(); } } class C : N.I { void I.M() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::N.I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForPartialType() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface I { void Goo(); } partial class C { } partial class C : {|CS0535:I|} { }", @"public interface I { void Goo(); } partial class C { } partial class C : I { void I.Goo() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForPartialType2() { await TestWithAllCodeStyleOptionsOffAsync( @"public interface I { void Goo(); } partial class C : {|CS0535:I|} { } partial class C { }", @"public interface I { void Goo(); } partial class C : I { void I.Goo() { throw new System.NotImplementedException(); } } partial class C { }", codeAction: ("True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(847464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/847464")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForPartialType3() { await new VerifyCS.Test { TestCode = @"public interface I { void Goo(); } public interface I2 { void Goo2(); } partial class C : {|CS0535:I|} { } partial class C : {|CS0535:I2|} { }", FixedState = { Sources = { @"public interface I { void Goo(); } public interface I2 { void Goo2(); } partial class C : I { void I.Goo() { throw new System.NotImplementedException(); } } partial class C : {|CS0535:I2|} { }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "True;False;False:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(752447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/752447")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestExplicitImplOfIndexedProperty() { var test = new VerifyCS.Test { TestState = { Sources = { @" public class Test : {|CS0535:{|CS0535:IGoo|}|} { }", }, AdditionalProjects = { ["Assembly1", LanguageNames.VisualBasic] = { Sources = { @" Public Interface IGoo Property IndexProp(ByVal p1 As Integer) As String End Interface", }, }, }, AdditionalProjectReferences = { "Assembly1", }, }, FixedState = { Sources = { @" public class Test : IGoo { string IGoo.get_IndexProp(int p1) { throw new System.NotImplementedException(); } void IGoo.set_IndexProp(int p1, string Value) { throw new System.NotImplementedException(); } }", }, }, CodeActionEquivalenceKey = "True;False;False:global::IGoo;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } [WorkItem(602475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602475")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplicitImplOfIndexedProperty() { await new VerifyCS.Test { TestState = { Sources = { @"using System; class C : {|CS0535:{|CS0535:I|}|} { }", }, AdditionalProjects = { ["Assembly1", LanguageNames.VisualBasic] = { Sources = { @"Public Interface I Property P(x As Integer) End Interface", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"using System; class C : I { public object get_P(int x) { throw new NotImplementedException(); } public void set_P(int x, object Value) { throw new NotImplementedException(); } }", }, }, CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementationOfIndexerWithInaccessibleAttributes() { var test = new VerifyCS.Test { TestState = { Sources = { @" using System; class C : {|CS0535:I|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @" using System; internal class ShouldBeRemovedAttribute : Attribute { } public interface I { string this[[ShouldBeRemovedAttribute] int i] { get; set; } }" }, }, }, AdditionalProjectReferences = { "Assembly1", }, }, FixedState = { Sources = { @" using System; class C : I { public string this[int i] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } }", }, }, CodeActionEquivalenceKey = "False;False;True:global::I;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }; test.Options.AddRange(AllOptionsOff); await test.RunAsync(); } #if false [WorkItem(13677)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoGenerateInVenusCase2() { await TestMissingAsync( @"using System; #line 1 ""Bar"" class Goo : [|IComparable|] #line default #line hidden"); } #endif [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForImplicitIDisposable() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { }", $@"using System; class Program : IDisposable {{ private bool disposedValue; {DisposePattern("protected virtual ", "Program", "public void ")} }}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForExplicitIDisposable() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { private bool DisposedValue; }", $@"using System; class Program : IDisposable {{ private bool DisposedValue; private bool disposedValue; {DisposePattern("protected virtual ", "Program", "void IDisposable.")} }}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForIDisposableNonApplicable1() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { private bool disposedValue; }", @"using System; class Program : IDisposable { private bool disposedValue; public void Dispose() { throw new NotImplementedException(); } }", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForIDisposableNonApplicable2() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { public void Dispose(bool flag) { } }", @"using System; class Program : IDisposable { public void Dispose(bool flag) { } public void Dispose() { throw new NotImplementedException(); } }", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 0)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForExplicitIDisposableWithSealedClass() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; sealed class Program : {|CS0535:IDisposable|} { }", $@"using System; sealed class Program : IDisposable {{ private bool disposedValue; {DisposePattern("private ", "Program", "void IDisposable.")} }}", codeAction: ("True;False;False:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } [WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceForExplicitIDisposableWithExistingField() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; class Program : {|CS0535:IDisposable|} { private bool disposedValue; }", $@"using System; class Program : IDisposable {{ private bool disposedValue; private bool disposedValue1; {DisposePattern("protected virtual ", "Program", "public void ", disposeField: "disposedValue1")} }}", codeAction: ("False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(9760, "https://github.com/dotnet/roslyn/issues/9760")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceUnderscoreNameForFields() { await new VerifyCS.Test { TestCode = @"using System; class Program : {|CS0535:IDisposable|} { }", FixedCode = $@"using System; class Program : IDisposable {{ private bool _disposedValue; {DisposePattern("protected virtual ", "Program", "public void ", disposeField: "_disposedValue")} }}", Options = { _options.FieldNamesAreCamelCaseWithUnderscorePrefix, }, CodeActionEquivalenceKey = "False;False;True:global::System.IDisposable;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoComAliasNameAttributeOnMethodParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p); } class C : {|CS0535:I|} { }", @"interface I { void M([System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p); } class C : I { public void M(int p) { throw new System.NotImplementedException(); } }"); } [WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoComAliasNameAttributeOnMethodReturnType() { await TestWithAllCodeStyleOptionsOffAsync( @"using System.Runtime.InteropServices; interface I { [return: ComAliasName(""pAlias1"")] long M([ComAliasName(""pAlias2"")] int p); } class C : {|CS0535:I|} { }", @"using System.Runtime.InteropServices; interface I { [return: ComAliasName(""pAlias1"")] long M([ComAliasName(""pAlias2"")] int p); } class C : I { public long M(int p) { throw new System.NotImplementedException(); } }"); } [WorkItem(939123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/939123")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNoComAliasNameAttributeOnIndexerParameters() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I { long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; } } class C : {|CS0535:I|} { }", @"interface I { long this[[System.Runtime.InteropServices.ComAliasName(""pAlias"")] int p] { get; } } class C : I { public long this[int p] { get { throw new System.NotImplementedException(); } } }"); } [WorkItem(947819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMissingOpenBrace() { await TestWithAllCodeStyleOptionsOffAsync( @"namespace Scenarios { public interface TestInterface { void M1(); } struct TestStruct1 : {|CS0535:TestInterface|}{|CS1513:|}{|CS1514:|} // Comment }", @"namespace Scenarios { public interface TestInterface { void M1(); } struct TestStruct1 : TestInterface { public void M1() { throw new System.NotImplementedException(); } } // Comment }"); } [WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced1() { //CSharpFeaturesResources.DisposePattern await TestWithAllCodeStyleOptionsOffAsync( @"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T { System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; } partial class C { } partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|} { }", $@"using System; using System.Collections.Generic; interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T {{ System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; }} partial class C {{ }} partial class C : I<System.Exception, System.AggregateException>, System.IDisposable {{ private bool disposedValue; public bool Equals(int other) {{ throw new NotImplementedException(); }} public List<AggregateException> M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c) {{ throw new NotImplementedException(); }} public List<UU> M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c) where UU : TT {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "public void ")} }}", codeAction: ("False;False;True:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 1)); } [WorkItem(994328, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/994328")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDisposePatternWhenAdditionalUsingsAreIntroduced2() { await TestWithAllCodeStyleOptionsOffAsync( @"interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T { System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; } partial class C : {|CS0535:{|CS0535:{|CS0535:I<System.Exception, System.AggregateException>|}|}|}, {|CS0535:System.IDisposable|} { } partial class C { }", $@"using System; using System.Collections.Generic; interface I<T, U> : System.IDisposable, System.IEquatable<int> where U : T {{ System.Collections.Generic.List<U> M(System.Collections.Generic.Dictionary<T, System.Collections.Generic.List<U>> a, T b, U c); System.Collections.Generic.List<UU> M<TT, UU>(System.Collections.Generic.Dictionary<TT, System.Collections.Generic.List<UU>> a, TT b, UU c) where UU : TT; }} partial class C : I<System.Exception, System.AggregateException>, System.IDisposable {{ private bool disposedValue; bool IEquatable<int>.Equals(int other) {{ throw new NotImplementedException(); }} List<AggregateException> I<Exception, AggregateException>.M(Dictionary<Exception, List<AggregateException>> a, Exception b, AggregateException c) {{ throw new NotImplementedException(); }} List<UU> I<Exception, AggregateException>.M<TT, UU>(Dictionary<TT, List<UU>> a, TT b, UU c) {{ throw new NotImplementedException(); }} {DisposePattern("protected virtual ", "C", "void IDisposable.")} }} partial class C {{ }}", codeAction: ("True;False;False:global::I<global::System.Exception, global::System.AggregateException>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceWithDisposePatternCodeAction;", 3)); } private static string DisposePattern( string disposeVisibility, string className, string implementationVisibility, string disposeField = "disposedValue", string gcPrefix = "") { return $@" {disposeVisibility}void Dispose(bool disposing) {{ if (!{disposeField}) {{ if (disposing) {{ // {FeaturesResources.TODO_colon_dispose_managed_state_managed_objects} }} // {FeaturesResources.TODO_colon_free_unmanaged_resources_unmanaged_objects_and_override_finalizer} // {FeaturesResources.TODO_colon_set_large_fields_to_null} {disposeField} = true; }} }} // // {string.Format(FeaturesResources.TODO_colon_override_finalizer_only_if_0_has_code_to_free_unmanaged_resources, "Dispose(bool disposing)")} // ~{className}() // {{ // // {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")} // Dispose(disposing: false); // }} {implementationVisibility}Dispose() {{ // {string.Format(FeaturesResources.Do_not_change_this_code_Put_cleanup_code_in_0_method, "Dispose(bool disposing)")} Dispose(disposing: true); {gcPrefix}GC.SuppressFinalize(this); }}"; } [WorkItem(1132014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1132014")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAttributes() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; public class Goo : {|CS0535:Holder.SomeInterface|} { } public class Holder { public interface SomeInterface { void Something([SomeAttribute] string helloWorld); } private class SomeAttribute : Attribute { } }", @"using System; public class Goo : Holder.SomeInterface { public void Something(string helloWorld) { throw new NotImplementedException(); } } public class Holder { public interface SomeInterface { void Something([SomeAttribute] string helloWorld); } private class SomeAttribute : Attribute { } }"); } [WorkItem(2785, "https://github.com/dotnet/roslyn/issues/2785")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementInterfaceThroughStaticMemberInGenericClass() { await TestWithAllCodeStyleOptionsOffAsync( @"using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Issue2785<T> : {|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:{|CS0535:IList<object>|}|}|}|}|}|}|}|}|}|}|}|}|} { private static List<object> innerList = new List<object>(); }", @"using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Issue2785<T> : IList<object> { private static List<object> innerList = new List<object>(); public object this[int index] { get { return ((IList<object>)innerList)[index]; } set { ((IList<object>)innerList)[index] = value; } } public int Count { get { return ((ICollection<object>)innerList).Count; } } public bool IsReadOnly { get { return ((ICollection<object>)innerList).IsReadOnly; } } public void Add(object item) { ((ICollection<object>)innerList).Add(item); } public void Clear() { ((ICollection<object>)innerList).Clear(); } public bool Contains(object item) { return ((ICollection<object>)innerList).Contains(item); } public void CopyTo(object[] array, int arrayIndex) { ((ICollection<object>)innerList).CopyTo(array, arrayIndex); } public IEnumerator<object> GetEnumerator() { return ((IEnumerable<object>)innerList).GetEnumerator(); } public int IndexOf(object item) { return ((IList<object>)innerList).IndexOf(item); } public void Insert(int index, object item) { ((IList<object>)innerList).Insert(index, item); } public bool Remove(object item) { return ((ICollection<object>)innerList).Remove(item); } public void RemoveAt(int index) { ((IList<object>)innerList).RemoveAt(index); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)innerList).GetEnumerator(); } }", codeAction: ("False;False;False:global::System.Collections.Generic.IList<object>;mscorlib;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;innerList", 1)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface), CompilerTrait(CompilerFeature.Tuples)] public async Task LongTuple() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y); } class Class : {|CS0535:IInterface|} { (int, string) x; }", @"interface IInterface { (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y); } class Class : IInterface { (int, string) x; public (int, string, int, string, int, string, int, string) Method1((int, string, int, string, int, string, int, string) y) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task LongTupleWithNames() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface { (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y); } class Class : {|CS0535:IInterface|} { (int, string) x; }", @"interface IInterface { (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y); } class Class : IInterface { (int, string) x; public (int a, string b, int c, string d, int e, string f, int g, string h) Method1((int a, string b, int c, string d, int e, string f, int g, string h) y) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task GenericWithTuple() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface<TA, TB> { (TA, TB) Method1((TA, TB) y); } class Class : {|CS0535:IInterface<(int, string), int>|} { (int, string) x; }", @"interface IInterface<TA, TB> { (TA, TB) Method1((TA, TB) y); } class Class : IInterface<(int, string), int> { (int, string) x; public ((int, string), int) Method1(((int, string), int) y) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task GenericWithTupleWithNamess() { await TestWithAllCodeStyleOptionsOffAsync( @"interface IInterface<TA, TB> { (TA a, TB b) Method1((TA a, TB b) y); } class Class : {|CS0535:IInterface<(int, string), int>|} { (int, string) x; }", @"interface IInterface<TA, TB> { (TA a, TB b) Method1((TA a, TB b) y); } class Class : IInterface<(int, string), int> { (int, string) x; public ((int, string) a, int b) Method1(((int, string) a, int b) y) { throw new System.NotImplementedException(); } }"); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithGroupingOff1() { await new VerifyCS.Test { TestCode = @"interface IInterface { int Prop { get; } } class Class : {|CS0535:IInterface|} { void M() { } }", FixedCode = @"interface IInterface { int Prop { get; } } class Class : IInterface { void M() { } public int Prop => throw new System.NotImplementedException(); }", Options = { { ImplementTypeOptions.InsertionBehavior, ImplementTypeInsertionBehavior.AtTheEnd }, }, }.RunAsync(); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotReorderComImportMembers_01() { await TestInRegularAndScriptAsync( @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload(); void X(); void MOverload(int i); int Prop { get; } } class Class : {|CS0535:{|CS0535:{|CS0535:{|CS0535:IComInterface|}|}|}|} { }", @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload(); void X(); void MOverload(int i); int Prop { get; } } class Class : IComInterface { public void MOverload() { throw new System.NotImplementedException(); } public void X() { throw new System.NotImplementedException(); } public void MOverload(int i) { throw new System.NotImplementedException(); } public int Prop => throw new System.NotImplementedException(); }"); } [WorkItem(15387, "https://github.com/dotnet/roslyn/issues/15387")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotReorderComImportMembers_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload() { } void X() { } void MOverload(int i) { } int Prop { get; } } class Class : {|CS0535:IComInterface|} { }", FixedCode = @" using System.Runtime.InteropServices; [ComImport] [Guid(""00000000-0000-0000-0000-000000000000"")] interface IComInterface { void MOverload() { } void X() { } void MOverload(int i) { } int Prop { get; } } class Class : IComInterface { public int Prop => throw new System.NotImplementedException(); }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReturns() { await TestInRegularAndScriptAsync( @" using System; interface I { ref int IGoo(); ref int Goo { get; } ref int this[int i] { get; } } class C : {|CS0535:{|CS0535:{|CS0535:I|}|}|} { }", @" using System; interface I { ref int IGoo(); ref int Goo { get; } ref int this[int i] { get; } } class C : I { public ref int this[int i] => throw new NotImplementedException(); public ref int Goo => throw new NotImplementedException(); public ref int IGoo() { throw new NotImplementedException(); } }"); } [WorkItem(13932, "https://github.com/dotnet/roslyn/issues/13932")] [WorkItem(5898, "https://github.com/dotnet/roslyn/issues/5898")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAutoProperties() { await new VerifyCS.Test() { TestCode = @"interface IInterface { int ReadOnlyProp { get; } int ReadWriteProp { get; set; } int WriteOnlyProp { set; } } class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedCode = @"interface IInterface { int ReadOnlyProp { get; } int ReadWriteProp { get; set; } int WriteOnlyProp { set; } } class Class : IInterface { public int ReadOnlyProp { get; } public int ReadWriteProp { get; set; } public int WriteOnlyProp { set => throw new System.NotImplementedException(); } }", Options = { { ImplementTypeOptions.PropertyGenerationBehavior, ImplementTypePropertyGenerationBehavior.PreferAutoProperties }, }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestOptionalParameterWithDefaultLiteral() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp7_1, TestCode = @" using System.Threading; interface IInterface { void Method1(CancellationToken cancellationToken = default(CancellationToken)); } class Class : {|CS0535:IInterface|} { }", FixedCode = @" using System.Threading; interface IInterface { void Method1(CancellationToken cancellationToken = default(CancellationToken)); } class Class : IInterface { public void Method1(CancellationToken cancellationToken = default) { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInWithMethod_Parameters() { await TestInRegularAndScriptAsync( @"interface ITest { void Method(in int p); } public class Test : {|CS0535:ITest|} { }", @"interface ITest { void Method(in int p); } public class Test : ITest { public void Method(in int p) { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReadOnlyWithMethod_ReturnType() { await TestInRegularAndScriptAsync( @"interface ITest { ref readonly int Method(); } public class Test : {|CS0535:ITest|} { }", @"interface ITest { ref readonly int Method(); } public class Test : ITest { public ref readonly int Method() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReadOnlyWithProperty() { await TestInRegularAndScriptAsync( @"interface ITest { ref readonly int Property { get; } } public class Test : {|CS0535:ITest|} { }", @"interface ITest { ref readonly int Property { get; } } public class Test : ITest { public ref readonly int Property => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInWithIndexer_Parameters() { await TestInRegularAndScriptAsync( @"interface ITest { int this[in int p] { set; } } public class Test : {|CS0535:ITest|} { }", @"interface ITest { int this[in int p] { set; } } public class Test : ITest { public int this[in int p] { set => throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestRefReadOnlyWithIndexer_ReturnType() { await TestInRegularAndScriptAsync( @"interface ITest { ref readonly int this[int p] { get; } } public class Test : {|CS0535:ITest|} { }", @"interface ITest { ref readonly int this[int p] { get; } } public class Test : ITest { public ref readonly int this[int p] => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnmanagedConstraint() { await TestInRegularAndScriptAsync( @"public interface ITest { void M<T>() where T : unmanaged; } public class Test : {|CS0535:ITest|} { }", @"public interface ITest { void M<T>() where T : unmanaged; } public class Test : ITest { public void M<T>() where T : unmanaged { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSealedMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSealedMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSealedMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); sealed void M1() {} sealed int P1 => 1; } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { protected void M1(); protected int P1 {get;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { }", FixedState = { Sources = { @"interface IInterface { protected void M1(); protected int P1 {get;} } class Class : IInterface { int IInterface.P1 { get { throw new System.NotImplementedException(); } } void IInterface.M1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, DiagnosticSelector = diagnostics => diagnostics[1], CodeFixTestBehaviors = CodeFixTestBehaviors.FixOne, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); protected void M1(); protected int P1 {get;} } abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicAccessor_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;False;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicAccessor_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { int P1 {get; protected set;} int P2 {protected get; set;} } class Class : {|CS0535:{|CS0535:IInterface|}|} { }", FixedState = { Sources = { @"interface IInterface { int P1 {get; protected set;} int P2 {protected get; set;} } class Class : IInterface { int IInterface.P1 { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } int IInterface.P2 { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNonPublicAccessor_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", FixedState = { Sources = { @"interface IInterface { void Method1(); int P1 {get; protected set;} int P2 {protected get; set;} } abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPrivateAccessor_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPrivateAccessor_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestPrivateAccessor_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); int P1 {get => 0; private set {}} int P2 {private get => 0; set {}} } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleMember_01() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); internal void M1(); internal int P1 {get;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass. CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleMember_02() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); internal void M1(); internal int P1 {get;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { void IInterface.Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleMember_03() { await new VerifyCS.Test { TestState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); internal void M1(); internal int P1 {get;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAccessor_01() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); int P1 {get; internal set;} int P2 {internal get; set;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { public void Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to implement the interface explicitly with a second code fix pass. CodeActionEquivalenceKey = "False;False;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAccessor_02() { await new VerifyCS.Test { TestState = { Sources = { @"class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); int P1 {get; internal set;} int P2 {internal get; set;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"class Class : {|CS0535:{|CS0535:IInterface|}|} { void IInterface.Method1() { throw new System.NotImplementedException(); } }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestInaccessibleAccessor_03() { await new VerifyCS.Test { TestState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:{|CS0535:IInterface|}|}|} { }", }, AdditionalProjects = { ["Assembly1"] = { Sources = { @"public interface IInterface { void Method1(); int P1 {get; internal set;} int P2 {internal get; set;} }", }, }, }, AdditionalProjectReferences = { "Assembly1" }, }, FixedState = { Sources = { @"abstract class Class : {|CS0535:{|CS0535:IInterface|}|} { public abstract void Method1(); }", }, MarkupHandling = MarkupMode.Allow, }, Options = { AllOptionsOff }, // Specify the code action by equivalence key only to avoid trying to execute a second code fix pass with a different action CodeActionEquivalenceKey = "False;True;True:global::IInterface;Assembly1;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestVirtualMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestVirtualMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestVirtualMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); virtual void M1() {} virtual int P1 => 1; } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticMember_01() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : IInterface { public void Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticMember_02() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } class Class : IInterface { void IInterface.Method1() { throw new System.NotImplementedException(); } }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "True;False;False:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticMember_03() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } abstract class Class : {|CS0535:IInterface|} { }", FixedCode = @"interface IInterface { void Method1(); static void M1() {} static int P1 => 1; static int F1; public abstract class C {} } abstract class Class : IInterface { public abstract void Method1(); }", Options = { AllOptionsOff }, CodeActionEquivalenceKey = "False;True;True:global::IInterface;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNotNullConstraint() { await TestInRegularAndScriptAsync( @"public interface ITest { void M<T>() where T : notnull; } public class Test : {|CS0535:ITest|} { }", @"public interface ITest { void M<T>() where T : notnull; } public class Test : ITest { public void M<T>() where T : notnull { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableProperty() { await TestInRegularAndScriptAsync( @"#nullable enable public interface ITest { string? P { get; } } public class Test : {|CS0535:ITest|} { }", @"#nullable enable public interface ITest { string? P { get; } } public class Test : ITest { public string? P => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullablePropertyAlreadyImplemented() { var code = @"#nullable enable public interface ITest { string? P { get; } } public class Test : ITest { public string? P => throw new System.NotImplementedException(); }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableMethod() { await TestInRegularAndScriptAsync( @"#nullable enable public interface ITest { string? P(); } public class Test : {|CS0535:ITest|} { }", @"#nullable enable public interface ITest { string? P(); } public class Test : ITest { public string? P() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableEvent() { // Question whether this is needed, // see https://github.com/dotnet/roslyn/issues/36673 await TestInRegularAndScriptAsync( @"#nullable enable using System; public interface ITest { event EventHandler? SomeEvent; } public class Test : {|CS0535:ITest|} { }", @"#nullable enable using System; public interface ITest { event EventHandler? SomeEvent; } public class Test : ITest { public event EventHandler? SomeEvent; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestWithNullableDisabled() { await TestInRegularAndScriptAsync( @"#nullable enable public interface ITest { string? P { get; } } #nullable disable public class Test : {|CS0535:ITest|} { }", @"#nullable enable public interface ITest { string? P { get; } } #nullable disable public class Test : ITest { public string P => throw new System.NotImplementedException(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task GenericInterfaceNotNull1() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, TestCode = @"#nullable enable using System.Diagnostics.CodeAnalysis; interface IFoo<T> { [return: NotNull] T Bar([DisallowNull] T bar); [return: MaybeNull] T Baz([AllowNull] T bar); } class A : {|CS0535:{|CS0535:IFoo<int>|}|} { }", FixedCode = @"#nullable enable using System.Diagnostics.CodeAnalysis; interface IFoo<T> { [return: NotNull] T Bar([DisallowNull] T bar); [return: MaybeNull] T Baz([AllowNull] T bar); } class A : IFoo<int> { [return: NotNull] public int Bar([DisallowNull] int bar) { throw new System.NotImplementedException(); } [return: MaybeNull] public int Baz([AllowNull] int bar) { throw new System.NotImplementedException(); } }", }.RunAsync(); } [WorkItem(13427, "https://github.com/dotnet/roslyn/issues/13427")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestDoNotAddNewWithGenericAndNonGenericMethods() { await TestWithAllCodeStyleOptionsOffAsync( @"class B { public void M<T>() { } } interface I { void M(); } class D : B, {|CS0535:I|} { }", @"class B { public void M<T>() { } } interface I { void M(); } class D : B, I { public void M() { throw new System.NotImplementedException(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementRemainingExplicitlyWhenPartiallyImplemented() { await TestInRegularAndScriptAsync(@" interface I { void M1(); void M2(); } class C : {|CS0535:I|} { public void M1(){} }", @" interface I { void M1(); void M2(); } class C : {|CS0535:I|} { public void M1(){} void I.M2() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 2)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementInitOnlyProperty() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.CSharp9, TestCode = @" interface I { int Property { get; init; } } class C : {|CS0535:I|} { }", FixedCode = @" interface I { int Property { get; init; } } class C : I { public int Property { get => throw new System.NotImplementedException(); init => throw new System.NotImplementedException(); } }", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementRemainingExplicitlyMissingWhenAllImplemented() { var code = @" interface I { void M1(); void M2(); } class C : I { public void M1(){} public void M2(){} }"; await VerifyCS.VerifyCodeFixAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task ImplementRemainingExplicitlyMissingWhenAllImplementedAreExplicit() { var code = @" interface I { void M1(); void M2(); } class C : {|CS0535:I|} { void I.M1(){} }"; var fixedCode = @" interface I { void M1(); void M2(); } class C : I { public void M2() { throw new System.NotImplementedException(); } void I.M1(){} }"; await new VerifyCS.Test { TestCode = code, FixedCode = fixedCode, CodeActionsVerifier = codeActions => Assert.Equal(2, codeActions.Length), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementRemainingExplicitlyNonPublicMember() { await TestInRegularAndScriptAsync(@" interface I { void M1(); internal void M2(); } class C : {|CS0535:I|} { public void M1(){} }", @" interface I { void M1(); internal void M2(); } class C : {|CS0535:I|} { public void M1(){} void I.M2() { throw new System.NotImplementedException(); } }", codeAction: ("True;False;True:global::I;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", 1)); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementOnRecord_WithSemiColon() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface I { void M1(); } record C : {|CS0535:I|}; ", FixedCode = @" interface I { void M1(); } record C : {|CS0535:I|} { public void M1() { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementOnRecord_WithBracesAndTrivia() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface I { void M1(); } record C : {|CS0535:I|} { } // hello ", FixedCode = @" interface I { void M1(); } record C : {|CS0535:I|} { public void M1() { throw new System.NotImplementedException(); } } // hello ", }.RunAsync(); } [WorkItem(48295, "https://github.com/dotnet/roslyn/issues/48295")] [Theory, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] [InlineData("record")] [InlineData("record class")] [InlineData("record struct")] public async Task TestImplementOnRecord_WithSemiColonAndTrivia(string record) { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = $@" interface I {{ void M1(); }} {record} C : {{|CS0535:I|}}; // hello ", FixedCode = $@" interface I {{ void M1(); }} {record} C : {{|CS0535:I|}} // hello {{ public void M1() {{ throw new System.NotImplementedException(); }} }} ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnconstrainedGenericInstantiatedWithValueType() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @"#nullable enable interface IGoo<T> { void Bar(T? x); } class C : {|CS0535:IGoo<int>|} { } ", FixedCode = @"#nullable enable interface IGoo<T> { void Bar(T? x); } class C : IGoo<int> { public void Bar(int x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstrainedGenericInstantiatedWithValueType() { await TestInRegularAndScriptAsync(@" interface IGoo<T> where T : struct { void Bar(T? x); } class C : {|CS0535:IGoo<int>|} { } ", @" interface IGoo<T> where T : struct { void Bar(T? x); } class C : IGoo<int> { public void Bar(int? x) { throw new System.NotImplementedException(); } } "); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnconstrainedGenericInstantiatedWithReferenceType() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @" interface IGoo<T> { #nullable enable void Bar(T? x); #nullable restore } class C : {|CS0535:IGoo<string>|} { } ", FixedCode = @" interface IGoo<T> { #nullable enable void Bar(T? x); #nullable restore } class C : IGoo<string> { public void Bar(string x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUnconstrainedGenericInstantiatedWithReferenceType_NullableEnable() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @" #nullable enable interface IGoo<T> { void Bar(T? x); } class C : {|CS0535:IGoo<string>|} { } ", FixedCode = @" #nullable enable interface IGoo<T> { void Bar(T? x); } class C : IGoo<string> { public void Bar(string? x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstrainedGenericInstantiatedWithReferenceType() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp9, TestCode = @" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : {|CS0535:IGoo<string>|} { } ", FixedCode = @" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : IGoo<string> { public void Bar(string? x) { throw new System.NotImplementedException(); } } ", }.RunAsync(); } [WorkItem(49019, "https://github.com/dotnet/roslyn/issues/49019")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestConstrainedGenericInstantiatedWithReferenceType_NullableEnable() { await TestInRegularAndScriptAsync(@" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : {|CS0535:IGoo<string>|} { } ", @" #nullable enable interface IGoo<T> where T : class { void Bar(T? x); } class C : IGoo<string> { public void Bar(string? x) { throw new System.NotImplementedException(); } } "); } [WorkItem(51779, "https://github.com/dotnet/roslyn/issues/51779")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestImplementTwoPropertiesOfCSharp5() { await new VerifyCS.Test { LanguageVersion = LanguageVersion.CSharp5, TestCode = @" interface ITest { int Bar { get; } int Foo { get; } } class Program : {|CS0535:{|CS0535:ITest|}|} { } ", FixedCode = @" interface ITest { int Bar { get; } int Foo { get; } } class Program : ITest { public int Bar { get { throw new System.NotImplementedException(); } } public int Foo { get { throw new System.NotImplementedException(); } } } ", }.RunAsync(); } [WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceMember() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract void M1(); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract void M1(); } class C : ITest { public static void M1() { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceMemberExplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract void M1(); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract void M1(); } class C : ITest { static void ITest.M1() { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53925, "https://github.com/dotnet/roslyn/issues/53925")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceMember_ImplementAbstractly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract void M1(); } abstract class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract void M1(); } abstract class C : ITest { public static void M1() { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title), CodeActionEquivalenceKey = "False;True;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_OnlyExplicitlyImplementable() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract int operator -(ITest x); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract int operator -(ITest x); } class C : ITest { static int ITest.operator -(ITest x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_ImplementImplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); static abstract int operator -(T x, int y); } class C : {|CS0535:{|CS0535:ITest<C>|}|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); static abstract int operator -(T x, int y); } class C : ITest<C> { public static int operator -(C x) { throw new System.NotImplementedException(); } public static int operator -(C x, int y) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_ImplementExplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } class C : ITest<C> { static int ITest<C>.operator -(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterfaceOperator_ImplementAbstractly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } abstract class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int operator -(T x); } abstract class C : ITest<C> { public static int operator -(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title), CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_Explicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract int M(ITest x); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract int M(ITest x); } class C : ITest { static int ITest.M(ITest x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_Implicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest { static abstract int M(ITest x); } class C : {|CS0535:ITest|} { } ", FixedCode = @" interface ITest { static abstract int M(ITest x); } class C : ITest { public static int M(ITest x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_ImplementImplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : ITest<C> { public static int M(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface, codeAction.Title), CodeActionEquivalenceKey = "False;False;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 0, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_ImplementExplicitly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } class C : ITest<C> { static int ITest<C>.M(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_all_members_explicitly, codeAction.Title), CodeActionEquivalenceKey = "True;False;False:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } [WorkItem(53927, "https://github.com/dotnet/roslyn/issues/53927")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/56171"), Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestStaticAbstractInterface_ImplementAbstractly() { await new VerifyCS.Test { ReferenceAssemblies = ReferenceAssemblies.Net.Net50, LanguageVersion = LanguageVersion.Preview, TestCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } abstract class C : {|CS0535:ITest<C>|} { } ", FixedCode = @" interface ITest<T> where T : ITest<T> { static abstract int M(T x); } abstract class C : ITest<C> { public static int M(C x) { throw new System.NotImplementedException(); } } ", CodeActionVerifier = (codeAction, verifier) => verifier.Equal(FeaturesResources.Implement_interface_abstractly, codeAction.Title), CodeActionEquivalenceKey = "False;True;True:global::ITest<global::C>;TestProject;Microsoft.CodeAnalysis.ImplementInterface.AbstractImplementInterfaceService+ImplementInterfaceCodeAction;", CodeActionIndex = 1, }.RunAsync(); } } }
1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Core.Wpf/Adornments/AbstractAdornmentManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments { /// <summary> /// UI manager for graphic overlay tags. These tags will simply paint something related to the text. /// </summary> internal abstract class AbstractAdornmentManager<T> where T : GraphicsTag { private readonly object _invalidatedSpansLock = new(); private readonly IThreadingContext _threadingContext; /// <summary>Notification system about operations we do</summary> private readonly IAsynchronousOperationListener _asyncListener; /// <summary>Spans that are invalidated, and need to be removed from the layer..</summary> private List<IMappingSpan> _invalidatedSpans; /// <summary>View that created us.</summary> protected readonly IWpfTextView TextView; /// <summary>Layer where we draw adornments.</summary> protected readonly IAdornmentLayer AdornmentLayer; /// <summary>Aggregator that tells us where to draw.</summary> protected readonly ITagAggregator<T> TagAggregator; /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This is where we apply visuals to the text. /// /// It happens when another region of the view becomes visible or there is a change in tags. /// For us the end result is the same - get tags from tagger and update visuals correspondingly. /// </summary> protected abstract void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection); internal AbstractAdornmentManager( IThreadingContext threadingContext, IWpfTextView textView, IViewTagAggregatorFactoryService tagAggregatorFactoryService, IAsynchronousOperationListener asyncListener, string adornmentLayerName) { Contract.ThrowIfNull(threadingContext); Contract.ThrowIfNull(textView); Contract.ThrowIfNull(tagAggregatorFactoryService); Contract.ThrowIfNull(adornmentLayerName); Contract.ThrowIfNull(asyncListener); _threadingContext = threadingContext; TextView = textView; AdornmentLayer = textView.GetAdornmentLayer(adornmentLayerName); textView.LayoutChanged += OnLayoutChanged; _asyncListener = asyncListener; // If we are not on the UI thread, we are at race with Close, but we should be on UI thread Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess()); textView.Closed += OnTextViewClosed; TagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView); TagAggregator.TagsChanged += OnTagsChanged; } private void OnTextViewClosed(object sender, System.EventArgs e) { // release the aggregator TagAggregator.TagsChanged -= OnTagsChanged; TagAggregator.Dispose(); // unhook from view TextView.Closed -= OnTextViewClosed; TextView.LayoutChanged -= OnLayoutChanged; // At this point, this object should be available for garbage collection. } /// <summary> /// This handler gets called whenever there is a visual change in the view. /// Example: edit or a scroll. /// </summary> private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None)) using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged")) { // Make sure we're on the UI thread. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var reformattedSpans = e.NewOrReformattedSpans; var viewSnapshot = TextView.TextSnapshot; // No need to remove tags as these spans are reformatted anyways. UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false); // Compute any spans that had been invalidated but were not affected by layout. List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (invalidated != null) { var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot); var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference( invalidatedAndNormalized, e.NewOrReformattedSpans); UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true); } } } private static NormalizedSnapshotSpanCollection TranslateAndNormalize( IEnumerable<IMappingSpan> spans, ITextSnapshot targetSnapshot) { Contract.ThrowIfNull(spans); var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot)); return new NormalizedSnapshotSpanCollection(translated); } /// <summary> /// This handler is called when tag aggregator notifies us about tag changes. /// </summary> private void OnTagsChanged(object sender, TagsChangedEventArgs e) { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1")) { var changedSpan = e.Span; if (changedSpan == null) { return; // nothing changed } var needToScheduleUpdate = false; lock (_invalidatedSpansLock) { if (_invalidatedSpans == null) { // set invalidated spans _invalidatedSpans = new List<IMappingSpan> { changedSpan }; needToScheduleUpdate = true; } else { // add to existing invalidated spans _invalidatedSpans.Add(changedSpan); } } if (needToScheduleUpdate) { // schedule an update _threadingContext.JoinableTaskFactory.WithPriority(TextView.VisualElement.Dispatcher, DispatcherPriority.Render).RunAsync(async () => { using (_asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2")) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); UpdateInvalidSpans(); } }); } } } /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This function is used to update invalidates spans. /// </summary> protected void UpdateInvalidSpans() { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1")) using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None)) { // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (TextView.IsClosed) { return; // already closed } if (invalidated != null) { var viewSnapshot = TextView.TextSnapshot; var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot); UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true); } } } protected void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags) { Contract.ThrowIfNull(changedSpanCollection); // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var viewLines = TextView.TextViewLines; if (viewLines == null || viewLines.Count == 0) { return; // nothing to draw on } // removing is a separate pass from adding so that new stuff is not removed. if (removeOldTags) { foreach (var changedSpan in changedSpanCollection) { // is there any effect on the view? if (viewLines.IntersectsBufferSpan(changedSpan)) { AdornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan); } } } AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(changedSpanCollection); } protected bool ShouldDrawTag(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var mappedPoint = GetMappedPoint(snapshotSpan, mappingTagSpan); if (mappedPoint is null) { return false; } if (!TryMapToSingleSnapshotSpan(mappingTagSpan.Span, TextView.TextSnapshot, out var span)) { return false; } if (!TextView.TextViewLines.IntersectsBufferSpan(span)) { return false; } return true; } protected SnapshotPoint? GetMappedPoint(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var point = mappingTagSpan.Span.Start.GetPoint(snapshotSpan.Snapshot, PositionAffinity.Predecessor); if (point == null) { return null; } var mappedPoint = TextView.BufferGraph.MapUpToSnapshot( point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.VisualSnapshot); if (mappedPoint == null) { return null; } return mappedPoint; } // Map the mapping span to the visual snapshot. note that as a result of projection // topology, originally single span may be mapped into several spans. Visual adornments do // not make much sense on disjoint spans. We will not decorate spans that could not make it // in one piece. protected static bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span) { // IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple // lists and collection if the view buffer is same as anchor we could just map the // anchor to the viewSnapshot however, since the _anchor is not available, we have to // map start and end TODO: verify that affinity is correct. If it does not matter we // should use the cheapest. if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer) { var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value; var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value; span = new SnapshotSpan(mappedStart, mappedEnd); return true; } // TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su" // is it possible to cheaply detect cropping? var spans = mappingSpan.GetSpans(viewSnapshot); if (spans.Count != 1) { span = default; return false; // span is unmapped or disjoint. } span = spans[0]; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using System.Windows.Threading; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Adornments { /// <summary> /// UI manager for graphic overlay tags. These tags will simply paint something related to the text. /// </summary> internal abstract class AbstractAdornmentManager<T> where T : GraphicsTag { private readonly object _invalidatedSpansLock = new(); private readonly IThreadingContext _threadingContext; /// <summary>Notification system about operations we do</summary> private readonly IAsynchronousOperationListener _asyncListener; /// <summary>Spans that are invalidated, and need to be removed from the layer..</summary> private List<IMappingSpan> _invalidatedSpans; /// <summary>View that created us.</summary> protected readonly IWpfTextView TextView; /// <summary>Layer where we draw adornments.</summary> protected readonly IAdornmentLayer AdornmentLayer; /// <summary>Aggregator that tells us where to draw.</summary> protected readonly ITagAggregator<T> TagAggregator; /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This is where we apply visuals to the text. /// /// It happens when another region of the view becomes visible or there is a change in tags. /// For us the end result is the same - get tags from tagger and update visuals correspondingly. /// </summary> protected abstract void AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection); internal AbstractAdornmentManager( IThreadingContext threadingContext, IWpfTextView textView, IViewTagAggregatorFactoryService tagAggregatorFactoryService, IAsynchronousOperationListener asyncListener, string adornmentLayerName) { Contract.ThrowIfNull(threadingContext); Contract.ThrowIfNull(textView); Contract.ThrowIfNull(tagAggregatorFactoryService); Contract.ThrowIfNull(adornmentLayerName); Contract.ThrowIfNull(asyncListener); _threadingContext = threadingContext; TextView = textView; AdornmentLayer = textView.GetAdornmentLayer(adornmentLayerName); textView.LayoutChanged += OnLayoutChanged; _asyncListener = asyncListener; // If we are not on the UI thread, we are at race with Close, but we should be on UI thread Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess()); textView.Closed += OnTextViewClosed; TagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView); TagAggregator.TagsChanged += OnTagsChanged; } private void OnTextViewClosed(object sender, System.EventArgs e) { // release the aggregator TagAggregator.TagsChanged -= OnTagsChanged; TagAggregator.Dispose(); // unhook from view TextView.Closed -= OnTextViewClosed; TextView.LayoutChanged -= OnLayoutChanged; // At this point, this object should be available for garbage collection. } /// <summary> /// This handler gets called whenever there is a visual change in the view. /// Example: edit or a scroll. /// </summary> private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e) { using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None)) using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged")) { // Make sure we're on the UI thread. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var reformattedSpans = e.NewOrReformattedSpans; var viewSnapshot = TextView.TextSnapshot; // No need to remove tags as these spans are reformatted anyways. UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false); // Compute any spans that had been invalidated but were not affected by layout. List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (invalidated != null) { var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot); var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference( invalidatedAndNormalized, e.NewOrReformattedSpans); UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true); } } } private static NormalizedSnapshotSpanCollection TranslateAndNormalize( IEnumerable<IMappingSpan> spans, ITextSnapshot targetSnapshot) { Contract.ThrowIfNull(spans); var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot)); return new NormalizedSnapshotSpanCollection(translated); } /// <summary> /// This handler is called when tag aggregator notifies us about tag changes. /// </summary> private void OnTagsChanged(object sender, TagsChangedEventArgs e) { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1")) { var changedSpan = e.Span; if (changedSpan == null) { return; // nothing changed } var needToScheduleUpdate = false; lock (_invalidatedSpansLock) { if (_invalidatedSpans == null) { // set invalidated spans _invalidatedSpans = new List<IMappingSpan> { changedSpan }; needToScheduleUpdate = true; } else { // add to existing invalidated spans _invalidatedSpans.Add(changedSpan); } } if (needToScheduleUpdate) { // schedule an update _threadingContext.JoinableTaskFactory.WithPriority(TextView.VisualElement.Dispatcher, DispatcherPriority.Render).RunAsync(async () => { using (_asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2")) { await _threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true); UpdateInvalidSpans(); } }); } } } /// <summary> /// MUST BE CALLED ON UI THREAD!!!! This method touches WPF. /// /// This function is used to update invalidates spans. /// </summary> protected void UpdateInvalidSpans() { using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1")) using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None)) { // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); List<IMappingSpan> invalidated; lock (_invalidatedSpansLock) { invalidated = _invalidatedSpans; _invalidatedSpans = null; } if (TextView.IsClosed) { return; // already closed } if (invalidated != null) { var viewSnapshot = TextView.TextSnapshot; var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot); UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true); } } } protected void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags) { Contract.ThrowIfNull(changedSpanCollection); // this method should only run on UI thread as we do WPF here. Contract.ThrowIfFalse(TextView.VisualElement.Dispatcher.CheckAccess()); var viewLines = TextView.TextViewLines; if (viewLines == null || viewLines.Count == 0) { return; // nothing to draw on } // removing is a separate pass from adding so that new stuff is not removed. if (removeOldTags) { foreach (var changedSpan in changedSpanCollection) { // is there any effect on the view? if (viewLines.IntersectsBufferSpan(changedSpan)) { AdornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan); } } } AddAdornmentsToAdornmentLayer_CallOnlyOnUIThread(changedSpanCollection); } protected bool ShouldDrawTag(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var mappedPoint = GetMappedPoint(snapshotSpan, mappingTagSpan); if (mappedPoint is null) { return false; } if (!TryMapToSingleSnapshotSpan(mappingTagSpan.Span, TextView.TextSnapshot, out var span)) { return false; } if (!TextView.TextViewLines.IntersectsBufferSpan(span)) { return false; } return true; } protected SnapshotPoint? GetMappedPoint(SnapshotSpan snapshotSpan, IMappingTagSpan<GraphicsTag> mappingTagSpan) { var point = mappingTagSpan.Span.Start.GetPoint(snapshotSpan.Snapshot, PositionAffinity.Predecessor); if (point == null) { return null; } var mappedPoint = TextView.BufferGraph.MapUpToSnapshot( point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, TextView.VisualSnapshot); if (mappedPoint == null) { return null; } return mappedPoint; } // Map the mapping span to the visual snapshot. note that as a result of projection // topology, originally single span may be mapped into several spans. Visual adornments do // not make much sense on disjoint spans. We will not decorate spans that could not make it // in one piece. protected static bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span) { // IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple // lists and collection if the view buffer is same as anchor we could just map the // anchor to the viewSnapshot however, since the _anchor is not available, we have to // map start and end TODO: verify that affinity is correct. If it does not matter we // should use the cheapest. if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer) { var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value; var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value; span = new SnapshotSpan(mappedStart, mappedEnd); return true; } // TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su" // is it possible to cheaply detect cropping? var spans = mappingSpan.GetSpans(viewSnapshot); if (spans.Count != 1) { span = default; return false; // span is unmapped or disjoint. } span = spans[0]; return true; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/CSharp/Portable/ExtractMethod/CSharpSyntaxTriviaServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxTriviaServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => CSharpSyntaxTriviaService.Instance; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { [ExportLanguageServiceFactory(typeof(ISyntaxTriviaService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxTriviaServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxTriviaServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => CSharpSyntaxTriviaService.Instance; } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/Structure/MetadataAsSource/EventDeclarationStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class EventDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EventStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New EventDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C Event $$goo(x As Integer) End Class " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|hint:{|textspan:<Goo> |}Event $$goo(x As Integer)|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Event $$goo(x As Integer)|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Private Event $$goo(x As Integer)|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining.MetadataAsSource Public Class EventDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of EventStatementSyntax) Protected Overrides ReadOnly Property WorkspaceKind As String Get Return CodeAnalysis.WorkspaceKind.MetadataAsSource End Get End Property Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New EventDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function NoCommentsOrAttributes() As Task Dim code = " Class C Event $$goo(x As Integer) End Class " Await VerifyNoBlockSpansAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithAttributes() As Task Dim code = " Class C {|hint:{|textspan:<Goo> |}Event $$goo(x As Integer)|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAndAttributes() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Event $$goo(x As Integer)|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function <Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)> Public Async Function WithCommentsAttributesAndModifiers() As Task Dim code = " Class C {|hint:{|textspan:' Summary: ' This is a summary. <Goo> |}Private Event $$goo(x As Integer)|} End Class " Await VerifyBlockSpansAsync(code, Region("textspan", "hint", VisualBasicOutliningHelpers.Ellipsis, autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Analyzers/CSharp/Analyzers/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionConstants.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { internal static class ConvertSwitchStatementToExpressionConstants { public const string NodeToGenerateKey = nameof(NodeToGenerateKey); public const string ShouldRemoveNextStatementKey = nameof(ShouldRemoveNextStatementKey); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { internal static class ConvertSwitchStatementToExpressionConstants { public const string NodeToGenerateKey = nameof(NodeToGenerateKey); public const string ShouldRemoveNextStatementKey = nameof(ShouldRemoveNextStatementKey); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Core/CodeAnalysisTest/Collections/IndexOfTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/IndexOfTests.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public static class IndexOfTests { public static void IndexOfTest<TCollection>( Func<IEnumerable<int>, TCollection> factory, Func<TCollection, int, int> indexOfItem, Func<TCollection, int, int, int> indexOfItemIndex, Func<TCollection, int, int, int, int> indexOfItemIndexCount, Func<TCollection, int, int, int, IEqualityComparer<int>?, int> indexOfItemIndexCountEQ) where TCollection : notnull { var emptyCollection = factory(new int[0]); var collection1256 = factory(new[] { 1, 2, 5, 6 }); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, 20, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, -1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, 20, new CustomComparer(1))); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, -1, new CustomComparer(1))); Assert.Equal(-1, indexOfItem(emptyCollection, 5)); Assert.Equal(-1, indexOfItemIndex(emptyCollection, 5, 0)); Assert.Equal(2, indexOfItemIndex(collection1256, 5, 1)); Assert.Equal(-1, indexOfItemIndexCount(emptyCollection, 5, 0, 0)); Assert.Equal(-1, indexOfItemIndexCount(collection1256, 5, 1, 1)); Assert.Equal(2, indexOfItemIndexCount(collection1256, 5, 1, 2)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, indexOfItem(factory(list), 6)); Assert.Equal(2, indexOfItemIndexCountEQ(factory(list), 102, 0, 4, null)); if (factory(list) is IList) { Assert.Equal(-1, ((IList)factory(list)).IndexOf(6)); } for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int match in list.Concat(new[] { 88 })) { int expected = bclList.IndexOf(match, idx, count); int actual = indexOfItemIndexCount(factory(list), match, idx, count); Assert.Equal(expected, actual); actual = indexOfItemIndexCountEQ(factory(list), match, idx, count, new CustomComparer(count)); Assert.Equal(count > 0 ? idx + count - 1 : -1, actual); if (count == list.Count) { // Also test the IndexOf overload that takes no count parameter. actual = indexOfItemIndex(factory(list), match, idx); Assert.Equal(expected, actual); if (idx == 0) { // Also test the IndexOf overload that takes no index parameter. actual = indexOfItem(factory(list), match); Assert.Equal(expected, actual); } } } } } } public static void LastIndexOfTest<TCollection>( Func<IEnumerable<int>, TCollection> factory, Func<TCollection, int, int> lastIndexOfItem, Func<TCollection, int, IEqualityComparer<int>, int> lastIndexOfItemEQ, Func<TCollection, int, int, int> lastIndexOfItemIndex, Func<TCollection, int, int, int, int> lastIndexOfItemIndexCount, Func<TCollection, int, int, int, IEqualityComparer<int>?, int> lastIndexOfItemIndexCountEQ) { var emptyCollection = factory(new int[0]); var collection1256 = factory(new[] { 1, 2, 5, 6 }); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, 20, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, -1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, 20, new CustomComparer(1))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, -1, new CustomComparer(1))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndex(collection1256, 2, 5)); Assert.Equal(-1, lastIndexOfItem(emptyCollection, 5)); Assert.Equal(-1, lastIndexOfItemEQ(emptyCollection, 5, EqualityComparer<int>.Default)); Assert.Equal(-1, lastIndexOfItemIndex(emptyCollection, 5, 0)); Assert.Equal(-1, lastIndexOfItemIndexCount(emptyCollection, 5, 0, 0)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, lastIndexOfItem(factory(list), 6)); Assert.Equal(2, lastIndexOfItemIndexCountEQ(factory(list), 102, 6, 5, null)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int match in list.Concat(new[] { 88 })) { int expected = bclList.LastIndexOf(match, idx, count); int actual = lastIndexOfItemIndexCount(factory(list), match, idx, count); Assert.Equal(expected, actual); expected = bclList.LastIndexOf(match); actual = lastIndexOfItemEQ(factory(list), match, EqualityComparer<int>.Default); Assert.Equal(expected, actual); actual = lastIndexOfItemIndexCountEQ(factory(list), match, idx, count, new CustomComparer(count)); Assert.Equal(count > 0 ? (idx - count + 1) : -1, actual); if (count == list.Count) { // Also test the LastIndexOf overload that takes no count parameter. actual = lastIndexOfItemIndex(factory(list), match, idx); Assert.Equal(expected, actual); if (idx == list.Count - 1) { // Also test the LastIndexOf overload that takes no index parameter. actual = lastIndexOfItem(factory(list), match); Assert.Equal(expected, actual); } } } } } } private class CustomComparer : IEqualityComparer<int> { private readonly int _matchOnXIteration; private int _iteration; public CustomComparer(int matchOnXIteration) { _matchOnXIteration = matchOnXIteration; } public bool Equals(int x, int y) { return ++_iteration == _matchOnXIteration; } public int GetHashCode(int obj) { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://raw.githubusercontent.com/dotnet/runtime/v6.0.0-preview.5.21301.5/src/libraries/System.Collections.Immutable/tests/IndexOfTests.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public static class IndexOfTests { public static void IndexOfTest<TCollection>( Func<IEnumerable<int>, TCollection> factory, Func<TCollection, int, int> indexOfItem, Func<TCollection, int, int, int> indexOfItemIndex, Func<TCollection, int, int, int, int> indexOfItemIndexCount, Func<TCollection, int, int, int, IEqualityComparer<int>?, int> indexOfItemIndexCountEQ) where TCollection : notnull { var emptyCollection = factory(new int[0]); var collection1256 = factory(new[] { 1, 2, 5, 6 }); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, 20, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, -1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, 20, new CustomComparer(1))); Assert.Throws<ArgumentOutOfRangeException>(() => indexOfItemIndexCountEQ(collection1256, 100, 1, -1, new CustomComparer(1))); Assert.Equal(-1, indexOfItem(emptyCollection, 5)); Assert.Equal(-1, indexOfItemIndex(emptyCollection, 5, 0)); Assert.Equal(2, indexOfItemIndex(collection1256, 5, 1)); Assert.Equal(-1, indexOfItemIndexCount(emptyCollection, 5, 0, 0)); Assert.Equal(-1, indexOfItemIndexCount(collection1256, 5, 1, 1)); Assert.Equal(2, indexOfItemIndexCount(collection1256, 5, 1, 2)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, indexOfItem(factory(list), 6)); Assert.Equal(2, indexOfItemIndexCountEQ(factory(list), 102, 0, 4, null)); if (factory(list) is IList) { Assert.Equal(-1, ((IList)factory(list)).IndexOf(6)); } for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int match in list.Concat(new[] { 88 })) { int expected = bclList.IndexOf(match, idx, count); int actual = indexOfItemIndexCount(factory(list), match, idx, count); Assert.Equal(expected, actual); actual = indexOfItemIndexCountEQ(factory(list), match, idx, count, new CustomComparer(count)); Assert.Equal(count > 0 ? idx + count - 1 : -1, actual); if (count == list.Count) { // Also test the IndexOf overload that takes no count parameter. actual = indexOfItemIndex(factory(list), match, idx); Assert.Equal(expected, actual); if (idx == 0) { // Also test the IndexOf overload that takes no index parameter. actual = indexOfItem(factory(list), match); Assert.Equal(expected, actual); } } } } } } public static void LastIndexOfTest<TCollection>( Func<IEnumerable<int>, TCollection> factory, Func<TCollection, int, int> lastIndexOfItem, Func<TCollection, int, IEqualityComparer<int>, int> lastIndexOfItemEQ, Func<TCollection, int, int, int> lastIndexOfItemIndex, Func<TCollection, int, int, int, int> lastIndexOfItemIndexCount, Func<TCollection, int, int, int, IEqualityComparer<int>?, int> lastIndexOfItemIndexCountEQ) { var emptyCollection = factory(new int[0]); var collection1256 = factory(new[] { 1, 2, 5, 6 }); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, 20, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, -1, EqualityComparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, 1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(emptyCollection, 100, -1, 1, new CustomComparer(50))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, 20, new CustomComparer(1))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndexCountEQ(collection1256, 100, 1, -1, new CustomComparer(1))); Assert.Throws<ArgumentOutOfRangeException>(() => lastIndexOfItemIndex(collection1256, 2, 5)); Assert.Equal(-1, lastIndexOfItem(emptyCollection, 5)); Assert.Equal(-1, lastIndexOfItemEQ(emptyCollection, 5, EqualityComparer<int>.Default)); Assert.Equal(-1, lastIndexOfItemIndex(emptyCollection, 5, 0)); Assert.Equal(-1, lastIndexOfItemIndexCount(emptyCollection, 5, 0, 0)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableSegmentedList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, lastIndexOfItem(factory(list), 6)); Assert.Equal(2, lastIndexOfItemIndexCountEQ(factory(list), 102, 6, 5, null)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int match in list.Concat(new[] { 88 })) { int expected = bclList.LastIndexOf(match, idx, count); int actual = lastIndexOfItemIndexCount(factory(list), match, idx, count); Assert.Equal(expected, actual); expected = bclList.LastIndexOf(match); actual = lastIndexOfItemEQ(factory(list), match, EqualityComparer<int>.Default); Assert.Equal(expected, actual); actual = lastIndexOfItemIndexCountEQ(factory(list), match, idx, count, new CustomComparer(count)); Assert.Equal(count > 0 ? (idx - count + 1) : -1, actual); if (count == list.Count) { // Also test the LastIndexOf overload that takes no count parameter. actual = lastIndexOfItemIndex(factory(list), match, idx); Assert.Equal(expected, actual); if (idx == list.Count - 1) { // Also test the LastIndexOf overload that takes no index parameter. actual = lastIndexOfItem(factory(list), match); Assert.Equal(expected, actual); } } } } } } private class CustomComparer : IEqualityComparer<int> { private readonly int _matchOnXIteration; private int _iteration; public CustomComparer(int matchOnXIteration) { _matchOnXIteration = matchOnXIteration; } public bool Equals(int x, int y) { return ++_iteration == _matchOnXIteration; } public int GetHashCode(int obj) { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/CSharp/Impl/Options/Formatting/WrappingViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingWrappingOptionPage.xaml /// </summary> internal class WrappingViewModel : AbstractOptionPreviewViewModel { private const string s_blockPreview = @" class C { //[ public int Goo { get; set; } //] }"; private const string s_declarationPreview = @" class C{ void goo() { //[ int i = 0; string name = ""John""; //] } }"; public WrappingViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingPreserveSingleLine, CSharpVSResources.Leave_block_on_single_line, s_blockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, CSharpVSResources.Leave_statements_and_member_declarations_on_the_same_line, s_declarationPreview, this, optionStore)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingWrappingOptionPage.xaml /// </summary> internal class WrappingViewModel : AbstractOptionPreviewViewModel { private const string s_blockPreview = @" class C { //[ public int Goo { get; set; } //] }"; private const string s_declarationPreview = @" class C{ void goo() { //[ int i = 0; string name = ""John""; //] } }"; public WrappingViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingPreserveSingleLine, CSharpVSResources.Leave_block_on_single_line, s_blockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, CSharpVSResources.Leave_statements_and_member_declarations_on_the_same_line, s_declarationPreview, this, optionStore)); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateType/GenerateTypeTests_Dialog.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.GenerateType Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateType Partial Public Class GenerateTypeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest #Region "Same Project" #Region "SameProject SameFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDefaultValues() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|$$Goo|] End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As Goo End Sub End Class Class Goo End Class </Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInsideNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.Goo$$|] End Sub End Class Namespace A End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.Goo End Sub End Class Namespace A Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInsideQualifiedNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.Goo End Sub End Class Namespace A.B Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithinQualifiedNestedNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A.B Namespace C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A.B Namespace C Class Goo End Class End Namespace End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithinNestedQualifiedNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A Namespace B.C Class Goo End Class End Namespace End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithConstructorMembers() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f = New [|$$Goo|](bar:=1, baz:=2) End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f = New Goo(bar:=1, baz:=2) End Sub End Class Class Goo Private bar As Integer Private baz As Integer Public Sub New(bar As Integer, baz As Integer) Me.bar = bar Me.baz = baz End Sub End Class </Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithBaseTypes() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Imports System.Collections.Generic Class Program Sub Main() Dim f As List(Of Integer) = New [|$$Goo|]() End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Imports System.Collections.Generic Class Program Sub Main() Dim f As List(Of Integer) = New Goo() End Sub End Class Class Goo Inherits List(Of Integer) End Class </Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithPublicInterface() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A Namespace B.C Public Interface Goo End Interface End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithInternalStruct() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A Namespace B.C Friend Structure Goo End Structure End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Friend, typeKind:=TypeKind.Structure, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithDefaultEnum() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A Namespace B End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.Goo End Sub End Class Namespace A Namespace B Enum Goo End Enum End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.NotApplicable, typeKind:=TypeKind.Enum, isNewFile:=False) End Function #End Region #Region "SameProject ExistingFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInExistingEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> <Document FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInExistingEmptyFile_Usings_Folders() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class</Document> <Document Folders="outer\inner" FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> <Document FilePath="Test2.vb" Folders="outer\inner"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Function #End Region #Region "SameProject NewFile" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray(Of String).Empty, newFileName:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsNotNeeded_InNewFile_InFolder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Namespace outer Namespace inner Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), newFileName:="Test2.vb") End Function <WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_InValidFolderNameNotMadeNamespace() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Namespace outer Namespace inner Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Public Interface Goo End Interface </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("@@@@@", "#####"), areFoldersValidIdentifiers:=False, newFileName:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WorkItem(907454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907454")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsNeeded_InNewFile_InFolder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|$$Goo|] End Sub End Class</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports BarBaz.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), newFileName:="Test2.vb") End Function <WorkItem(907454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907454")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsPresentAlready_InNewFile_InFolder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb" Folders="outer"> Imports BarBaz.outer Class Program Sub Main() Dim f As [|$$Goo|] End Sub End Class</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports BarBaz.outer Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer"), newFileName:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), newFileName:="Test2.vb") End Function #End Region #End Region #Region "SameLanguage DifferentProject" #Region "SameLanguage DifferentProject ExistingFile" <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectExistingFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb" Folders="outer\inner">Namespace Global.BarBaz.A Namespace B End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.BarBaz.A Namespace B Public Interface Goo End Interface End Namespace End Namespace</Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb" Folders="outer\inner">Namespace A Namespace B End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A Namespace B End Namespace End Namespace Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports Zoozoo.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Function #End Region #Region "SameLanguage DifferentProject NewFile" <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports Zoozoo.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.BarBaz.A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_ProjectReference() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb"> Namespace A.B Public Class Bar End Class End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <ProjectReference>Assembly2</ProjectReference> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Zoozoo.A.B.Goo$$|] End Sub End Class</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=False, expectedTextWithUsings:=<Text></Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test3.vb", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function #End Region #End Region #Region "Different Language" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace outer.inner { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports_DefaultNamespace() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace ConsoleApplication.outer.inner { public class Goo { } }</Text>.NormalizedValue, defaultNamespace:="ConsoleApplication", checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports ConsoleApplication.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName_DefaultNamespace() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace BarBaz.A.B { public class Goo { } }</Text>.NormalizedValue, defaultNamespace:="ConsoleApplication", checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document Folders="outer\inner" FilePath="Test2.cs"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingEmptyFile_Imports_Folder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document Folders="outer\inner" FilePath="Test2.cs"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace outer.inner { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.cs"> namespace A { }</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> namespace A { } namespace A.B { public class Goo { } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingTargetFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.cs">namespace A { namespace B { } }</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A { namespace B { public class Goo { } } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFileAdjustTheFileExtension() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function #End Region #Region "Bugfix" <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <WorkItem(873066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/873066")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Class C Implements [|$$D|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="D", expected:=<Text>Public Class C Implements D End Class Public Interface D End Interface </Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Interface, accessibility:=Accessibility.Public, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Class CC Inherits [|$$DD|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DD", expected:=<Text>Public Class CC Inherits DD End Class Class DD End Class </Text>.NormalizedValue, isNewFile:=False, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Class)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Interface CCC Inherits [|$$DDD|] End Interface</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DDD", expected:=<Text>Public Interface CCC Inherits DDD End Interface Interface DDD End Interface </Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Interface, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_4() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Structure CCC Implements [|$$DDD|] End Structure</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DDD", expected:=<Text>Public Structure CCC Implements DDD End Structure Public Interface DDD End Interface </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <WorkItem(869593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869593")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithModuleOption() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s as [|$$A.B.C|] End Sub End Module Namespace A End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Module Program Sub Main(args As String()) Dim s as A.B.C End Sub End Module Namespace A Module B End Module End Namespace</Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$A.B|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="A", expected:=<Text>Module Program Sub Main(args As String()) Dim s = A.B End Sub End Module Public Module A End Module </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessExpressionWithNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Namespace A Module Program Sub Main(args As String()) Dim s = [|$$A.B.C|] End Sub End Module End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Namespace A Module Program Sub Main(args As String()) Dim s = A.B.C End Sub End Module Public Module B End Module End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <WorkItem(876202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876202")> <WorkItem(883531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883531")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_NoParameterLessConstructor() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = new [|$$Goo|]() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Module Program Sub Main(args As String()) Dim s = new Goo() End Sub End Module Public Structure B End Structure </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Structure, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithoutEnumForGenericsInMemberAccessExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Goo(Of Bar).D|] End Sub End Module Class Bar End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Goo(Of Bar).D End Sub End Module Class Bar End Class Public Class Goo(Of T) End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithoutEnumForGenericsInNameContext() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s As [|$$Goo(Of Bar)|] End Sub End Module Class Bar End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Module Program Sub Main(args As String()) Dim s As Goo(Of Bar) End Sub End Module Class Bar End Class Public Class Goo(Of T) End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessWithNSForModule() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Goo.Bar|].Baz End Sub End Module Namespace Goo End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Goo.Bar.Baz End Sub End Module Namespace Goo Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessWithGlobalNSForModule() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Bar|].Baz End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Bar.Baz End Sub End Module Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessWithoutNS() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Bar|].Baz End Sub End Module Namespace Bar End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", isMissing:=True) End Function #End Region #Region "Delegates" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = New [|$$MyD|](AddressOf goo) End Sub Sub goo() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim s = New MyD(AddressOf goo) End Sub Sub goo() End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpressionIntoNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New NS.[|$$MyD|](Sub() End Sub) End Sub End Module Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New NS.MyD(Sub() End Sub) End Sub End Module Namespace NS Public Delegate Sub MyD() End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New [|$$NS.MyD|](Function(n) n) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New NS.MyD(Function(n) n) End Sub End Module Namespace NS Public Delegate Function MyD(n As Object) As Object End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New [|$$MyD|](Sub() System.Console.WriteLine(1)) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New MyD(Sub() System.Console.WriteLine(1)) End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New [|$$MyD|](Function(n As Integer) Return n + n End Function) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New MyD(Function(n As Integer) Return n + n End Function) End Sub End Module Public Delegate Function MyD(n As Integer) As Integer </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD(Of Integer)|] = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD(Of Integer) = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithNoInitializer() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_MultiLineFunction() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = Function() Return 0 End Function End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = Function() Return 0 End Function End Sub End Module Public Delegate Function MyD() As Integer </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_SingleLineFunction() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a As [|$$MyD|] = Function(n As Integer) "" End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim a As MyD = Function(n As Integer) "" End Sub End Module Public Delegate Function MyD(n As Integer) As String </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_MultiLineSub() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = Sub() End Sub End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = Sub() End Sub End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_SingleLineSub() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a As [|$$MyD|] = Sub(n As Double) Console.WriteLine(0) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim a As MyD = Sub(n As Double) Console.WriteLine(0) End Sub End Module Public Delegate Sub MyD(n As Double) </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithCast() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, [|$$MyD|]) End Sub Public Sub goo() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, MyD) End Sub Public Sub goo() End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithCastAndError() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, [|$$MyD|]) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, MyD) End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateDelegateTypeIntoDifferentLanguageNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Module Program Sub Main(args As String()) Dim gooGoo = DirectCast(AddressOf Main, [|$$Bar|]) End Sub End Module</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>public delegate void Bar(string[] args); </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(860210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860210")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegate_NoInfo() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s as [|$$MyD(Of Integer)|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim s as MyD(Of Integer) End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate) End Function #End Region #Region "Dev12Filtering" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_0() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a = [|$$Baz.Goo|].Bar() End Sub End Module Namespace Baz End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Module Program Sub Main(args As String()) Dim a = Baz.Goo.Bar() End Sub End Module Namespace Baz Public Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a = [|$$Goo.Bar|]() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim a = Goo.Bar() End Sub End Module Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class C Custom Event E As Action AddHandler(value As [|$$Goo|]) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class C Custom Event E As Action AddHandler(value As Goo) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Goo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate}, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class C Custom Event E As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As [|$$Goo|]) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class C Custom Event E As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Goo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate}, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_4() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Imports System Module Program Sub Main(args As String()) Dim s As Action = AddressOf [|NS.Bar$$|].Method End Sub End Module Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Imports System Module Program Sub Main(args As String()) Dim s As Action = AddressOf NS.Bar.Method End Sub End Module Namespace NS Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_TypeConstraint_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Goo(Of T As [|$$Bar|]) End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class Goo(Of T As Bar) End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_TypeConstraint_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Outer Public Class Goo(Of T As [|$$Bar|]) End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Outer Public Class Goo(Of T As Bar) End Class End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_TypeConstraint_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class OuterOuter Public Class Outer Public Class Goo(Of T As [|$$Bar|]) End Class End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class OuterOuter Public Class Outer Public Class Goo(Of T As Bar) End Class End Class End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$Goo|] AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> Class C1 Custom Event E As Goo AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Goo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$NS.Goo|] AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> Class C1 Custom Event E As NS.Goo AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS Public Delegate Sub Goo() End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$NS.Goo.MyDel|] AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> Class C1 Custom Event E As NS.Goo.MyDel AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS Public Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_4() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Goo Public Event F As [|$$Bar|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Goo Public Event F As Bar End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_5() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Goo Public Event F As [|$$NS.Bar|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Goo Public Event F As NS.Bar End Class Namespace NS Public Delegate Sub Bar() End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_6() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Goo Public Event F As [|$$NS.Bar.MyDel|] End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Goo Public Event F As NS.Bar.MyDel End Class Namespace NS Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_7() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$Delegate1|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As Delegate1 End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_8() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$NS.Delegate1|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As NS.Delegate1 End Class Namespace NS Public Class Delegate1 End Class End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_9() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$NS.Delegate1.MyDel|] End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As NS.Delegate1.MyDel End Class Namespace NS Public Class Delegate1 End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_10() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Baz Public Class Goo Public Event F As [|$$Bar|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Baz Public Class Goo Public Event F As Bar End Class End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_11() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Baz Public Class Goo Public Event F As [|$$Bar|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class Baz Public Class Goo Public Event F As Bar End Class End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_12() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Baz Public Class Bar Public WithEvents G As [|$$Delegate1|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Baz Public Class Bar Public WithEvents G As Delegate1 End Class End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_13() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Baz Public Class Bar Public WithEvents G As [|$$Delegate1|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Public Class Baz Public Class Bar Public WithEvents G As Delegate1 End Class End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.GenerateType Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateType Partial Public Class GenerateTypeTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest #Region "Same Project" #Region "SameProject SameFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDefaultValues() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|$$Goo|] End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As Goo End Sub End Class Class Goo End Class </Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInsideNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.Goo$$|] End Sub End Class Namespace A End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.Goo End Sub End Class Namespace A Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInsideQualifiedNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.Goo End Sub End Class Namespace A.B Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithinQualifiedNestedNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A.B Namespace C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A.B Namespace C Class Goo End Class End Namespace End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithinNestedQualifiedNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A Namespace B.C Class Goo End Class End Namespace End Namespace</Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithConstructorMembers() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f = New [|$$Goo|](bar:=1, baz:=2) End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f = New Goo(bar:=1, baz:=2) End Sub End Class Class Goo Private bar As Integer Private baz As Integer Public Sub New(bar As Integer, baz As Integer) Me.bar = bar Me.baz = baz End Sub End Class </Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithBaseTypes() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Imports System.Collections.Generic Class Program Sub Main() Dim f As List(Of Integer) = New [|$$Goo|]() End Sub End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Imports System.Collections.Generic Class Program Sub Main() Dim f As List(Of Integer) = New Goo() End Sub End Class Class Goo Inherits List(Of Integer) End Class </Text>.NormalizedValue, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithPublicInterface() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A Namespace B.C Public Interface Goo End Interface End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithInternalStruct() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.C.Goo$$|] End Sub End Class Namespace A Namespace B.C End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.C.Goo End Sub End Class Namespace A Namespace B.C Friend Structure Goo End Structure End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Friend, typeKind:=TypeKind.Structure, isNewFile:=False) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithDefaultEnum() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A Namespace B End Namespace End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class Program Sub Main() Dim f As A.B.Goo End Sub End Class Namespace A Namespace B Enum Goo End Enum End Namespace End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.NotApplicable, typeKind:=TypeKind.Enum, isNewFile:=False) End Function #End Region #Region "SameProject ExistingFile" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInExistingEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> <Document FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInExistingEmptyFile_Usings_Folders() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class</Document> <Document Folders="outer\inner" FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInExistingEmptyFile_NoUsings_Folders_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> <Document FilePath="Test2.vb" Folders="outer\inner"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb") End Function #End Region #Region "SameProject NewFile" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray(Of String).Empty, newFileName:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsNotNeeded_InNewFile_InFolder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Namespace outer Namespace inner Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), newFileName:="Test2.vb") End Function <WorkItem(898452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/898452")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_InValidFolderNameNotMadeNamespace() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Namespace outer Namespace inner Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Public Interface Goo End Interface </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("@@@@@", "#####"), areFoldersValidIdentifiers:=False, newFileName:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WorkItem(907454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907454")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsNeeded_InNewFile_InFolder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|$$Goo|] End Sub End Class</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports BarBaz.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), newFileName:="Test2.vb") End Function <WorkItem(907454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/907454")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsPresentAlready_InNewFile_InFolder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb" Folders="outer"> Imports BarBaz.outer Class Program Sub Main() Dim f As [|$$Goo|] End Sub End Class</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports BarBaz.outer Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer"), newFileName:="Test2.vb") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_UsingsNotNeeded_InNewFile_InFolder_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), newFileName:="Test2.vb") End Function #End Region #End Region #Region "SameLanguage DifferentProject" #Region "SameLanguage DifferentProject ExistingFile" <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.vb"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectExistingFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb" Folders="outer\inner">Namespace Global.BarBaz.A Namespace B End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.BarBaz.A Namespace B Public Interface Goo End Interface End Namespace End Namespace</Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectExistingFile_Usings_Folders() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb" Folders="outer\inner">Namespace A Namespace B End Namespace End Namespace</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A Namespace B End Namespace End Namespace Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports Zoozoo.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=False, existingFilename:="Test2.vb", projectName:="Assembly2") End Function #End Region #Region "SameLanguage DifferentProject NewFile" <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_Usings() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace outer.inner Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports Zoozoo.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace Global.BarBaz.A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test2.vb", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoSameLanguageDifferentProjectNewFile_Folders_NoUsings_NotSimpleName_ProjectReference() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> <Document FilePath="Test2.vb"> Namespace A.B Public Class Bar End Class End Namespace</Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <ProjectReference>Assembly2</ProjectReference> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Zoozoo.A.B.Goo$$|] End Sub End Class</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Namespace A.B Public Interface Goo End Interface End Namespace </Text>.NormalizedValue, checkIfUsingsNotIncluded:=False, expectedTextWithUsings:=<Text></Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, isNewFile:=True, newFileName:="Test3.vb", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function #End Region #End Region #Region "Different Language" <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <CompilationOptions RootNamespace="Zoozoo"/> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace outer.inner { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_Imports_DefaultNamespace() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace ConsoleApplication.outer.inner { public class Goo { } }</Text>.NormalizedValue, defaultNamespace:="ConsoleApplication", checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports ConsoleApplication.outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class Namespace A.B End Namespace</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFile_Folders_NoImports_NotSimpleName_DefaultNamespace() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <CompilationOptions RootNamespace="BarBaz"/> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace BarBaz.A.B { public class Goo { } }</Text>.NormalizedValue, defaultNamespace:="ConsoleApplication", checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray.Create("outer", "inner"), projectName:="Assembly2") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document Folders="outer\inner" FilePath="Test2.cs"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsNotIncluded:=True, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <WorkItem(850101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850101")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingEmptyFile_Imports_Folder() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|Goo$$|] End Sub End Class</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document Folders="outer\inner" FilePath="Test2.cs"> </Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace outer.inner { public class Goo { } }</Text>.NormalizedValue, checkIfUsingsIncluded:=True, expectedTextWithUsings:=<Text> Imports outer.inner Class Program Sub Main() Dim f As Goo End Sub End Class</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingNonEmptyFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.cs"> namespace A { }</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> namespace A { } namespace A.B { public class Goo { } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageExistingTargetFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> <Document FilePath="Test2.cs">namespace A { namespace B { } }</Document> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A { namespace B { public class Goo { } } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=False, existingFilename:="Test2.cs", projectName:="Assembly2") End Function <WorkItem(858826, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858826")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeIntoDifferentLanguageNewFileAdjustTheFileExtension() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Class Program Sub Main() Dim f As [|A.B.Goo$$|] End Sub End Class Namespace A.B End Namespace</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>namespace A.B { public class Goo { } }</Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function #End Region #Region "Bugfix" <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <WorkItem(873066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/873066")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Class C Implements [|$$D|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="D", expected:=<Text>Public Class C Implements D End Class Public Interface D End Interface </Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Interface, accessibility:=Accessibility.Public, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Class CC Inherits [|$$DD|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DD", expected:=<Text>Public Class CC Inherits DD End Class Class DD End Class </Text>.NormalizedValue, isNewFile:=False, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Class)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Interface CCC Inherits [|$$DDD|] End Interface</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DDD", expected:=<Text>Public Interface CCC Inherits DDD End Interface Interface DDD End Interface </Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Interface, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Function <WorkItem(861462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861462")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithProperAccessibilityAndTypeKind_4() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Public Structure CCC Implements [|$$DDD|] End Structure</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="DDD", expected:=<Text>Public Structure CCC Implements DDD End Structure Public Interface DDD End Interface </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Interface, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Interface)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <WorkItem(869593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/869593")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithModuleOption() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s as [|$$A.B.C|] End Sub End Module Namespace A End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Module Program Sub Main(args As String()) Dim s as A.B.C End Sub End Module Namespace A Module B End Module End Namespace</Text>.NormalizedValue, isNewFile:=False, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$A.B|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="A", expected:=<Text>Module Program Sub Main(args As String()) Dim s = A.B End Sub End Module Public Module A End Module </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <WorkItem(861362, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861362")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessExpressionWithNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Namespace A Module Program Sub Main(args As String()) Dim s = [|$$A.B.C|] End Sub End Module End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Namespace A Module Program Sub Main(args As String()) Dim s = A.B.C End Sub End Module Public Module B End Module End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Module, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <WorkItem(876202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876202")> <WorkItem(883531, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883531")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_NoParameterLessConstructor() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = new [|$$Goo|]() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="B", expected:=<Text>Module Program Sub Main(args As String()) Dim s = new Goo() End Sub End Module Public Structure B End Structure </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Structure, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithoutEnumForGenericsInMemberAccessExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Goo(Of Bar).D|] End Sub End Module Class Bar End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Goo(Of Bar).D End Sub End Module Class Bar End Class Public Class Goo(Of T) End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeWithoutEnumForGenericsInNameContext() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s As [|$$Goo(Of Bar)|] End Sub End Module Class Bar End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Module Program Sub Main(args As String()) Dim s As Goo(Of Bar) End Sub End Module Class Bar End Class Public Class Goo(Of T) End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessWithNSForModule() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Goo.Bar|].Baz End Sub End Module Namespace Goo End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Goo.Bar.Baz End Sub End Module Namespace Goo Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <WorkItem(861600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/861600")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessWithGlobalNSForModule() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Bar|].Baz End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim s = Bar.Baz End Sub End Module Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.MemberAccessWithNamespace)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeInMemberAccessWithoutNS() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = [|$$Bar|].Baz End Sub End Module Namespace Bar End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", isMissing:=True) End Function #End Region #Region "Delegates" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s = New [|$$MyD|](AddressOf goo) End Sub Sub goo() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim s = New MyD(AddressOf goo) End Sub Sub goo() End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpressionIntoNamespace() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New NS.[|$$MyD|](Sub() End Sub) End Sub End Module Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New NS.MyD(Sub() End Sub) End Sub End Module Namespace NS Public Delegate Sub MyD() End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New [|$$NS.MyD|](Function(n) n) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New NS.MyD(Function(n) n) End Sub End Module Namespace NS Public Delegate Function MyD(n As Object) As Object End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New [|$$MyD|](Sub() System.Console.WriteLine(1)) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New MyD(Sub() System.Console.WriteLine(1)) End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateFromObjectCreationExpression_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim goo = New [|$$MyD|](Function(n As Integer) Return n + n End Function) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim goo = New MyD(Function(n As Integer) Return n + n End Function) End Sub End Module Public Delegate Function MyD(n As Integer) As Integer </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpression() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD(Of Integer)|] = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD(Of Integer) = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Interface Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf goo(Of Integer) End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateAddressOfExpressionWrongTypeArgument_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = AddressOf goo End Sub Public Sub goo(Of T)() End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithNoInitializer() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_MultiLineFunction() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = Function() Return 0 End Function End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = Function() Return 0 End Function End Sub End Module Public Delegate Function MyD() As Integer </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_SingleLineFunction() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a As [|$$MyD|] = Function(n As Integer) "" End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim a As MyD = Function(n As Integer) "" End Sub End Module Public Delegate Function MyD(n As Integer) As String </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_MultiLineSub() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar As [|$$MyD|] = Sub() End Sub End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar As MyD = Sub() End Sub End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithLambda_SingleLineSub() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a As [|$$MyD|] = Sub(n As Double) Console.WriteLine(0) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim a As MyD = Sub(n As Double) Console.WriteLine(0) End Sub End Module Public Delegate Sub MyD(n As Double) </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithCast() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, [|$$MyD|]) End Sub Public Sub goo() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, MyD) End Sub Public Sub goo() End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegateWithCastAndError() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, [|$$MyD|]) End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim bar = DirectCast(AddressOf goo, MyD) End Sub End Module Public Delegate Sub MyD() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.AllOptions Or TypeKindOptions.Delegate)) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateDelegateTypeIntoDifferentLanguageNewFile() As Task Dim markupString = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document FilePath="Test1.vb"> Module Program Sub Main(args As String()) Dim gooGoo = DirectCast(AddressOf Main, [|$$Bar|]) End Sub End Module</Document> </Project> <Project Language="C#" AssemblyName="Assembly2" CommonReferences="true"> </Project> </Workspace>.ToString() Await TestWithMockedGenerateTypeDialog( initial:=markupString, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>public delegate void Bar(string[] args); </Text>.NormalizedValue, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, isNewFile:=True, newFileName:="Test2.cs", newFileFolderContainers:=ImmutableArray(Of String).Empty, projectName:="Assembly2") End Function <WorkItem(860210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860210")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateTypeDelegate_NoInfo() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim s as [|$$MyD(Of Integer)|] End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="MyD", expected:=<Text>Module Program Sub Main(args As String()) Dim s as MyD(Of Integer) End Sub End Module Public Delegate Sub MyD(Of T)() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate) End Function #End Region #Region "Dev12Filtering" <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_0() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a = [|$$Baz.Goo|].Bar() End Sub End Module Namespace Baz End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Module Program Sub Main(args As String()) Dim a = Baz.Goo.Bar() End Sub End Module Namespace Baz Public Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Module Program Sub Main(args As String()) Dim a = [|$$Goo.Bar|]() End Sub End Module</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Module Program Sub Main(args As String()) Dim a = Goo.Bar() End Sub End Module Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class C Custom Event E As Action AddHandler(value As [|$$Goo|]) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class C Custom Event E As Action AddHandler(value As Goo) End AddHandler RemoveHandler(value As Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Goo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate}, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Class C Custom Event E As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As [|$$Goo|]) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text>Class C Custom Event E As Action AddHandler(value As Action) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Goo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertTypeKindPresent:=New TypeKindOptions() {TypeKindOptions.Delegate}, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Invocation_NoEnum_4() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text>Imports System Module Program Sub Main(args As String()) Dim s As Action = AddressOf [|NS.Bar$$|].Method End Sub End Module Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text>Imports System Module Program Sub Main(args As String()) Dim s As Action = AddressOf NS.Bar.Method End Sub End Module Namespace NS Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertTypeKindAbsent:=New TypeKindOptions() {TypeKindOptions.Enum}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_TypeConstraint_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Goo(Of T As [|$$Bar|]) End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class Goo(Of T As Bar) End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_TypeConstraint_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Outer Public Class Goo(Of T As [|$$Bar|]) End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Outer Public Class Goo(Of T As Bar) End Class End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_TypeConstraint_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class OuterOuter Public Class Outer Public Class Goo(Of T As [|$$Bar|]) End Class End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class OuterOuter Public Class Outer Public Class Goo(Of T As Bar) End Class End Class End Class Public Class Bar End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_1() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$Goo|] AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> Class C1 Custom Event E As Goo AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Public Delegate Sub Goo() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_2() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$NS.Goo|] AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> Class C1 Custom Event E As NS.Goo AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS Public Delegate Sub Goo() End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_3() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class C1 Custom Event E As [|$$NS.Goo.MyDel|] AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Goo", expected:=<Text> Class C1 Custom Event E As NS.Goo.MyDel AddHandler(value As Goo) End AddHandler RemoveHandler(value As Goo) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class Namespace NS Public Class Goo End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_4() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Goo Public Event F As [|$$Bar|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Goo Public Event F As Bar End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_5() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Goo Public Event F As [|$$NS.Bar|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Goo Public Event F As NS.Bar End Class Namespace NS Public Delegate Sub Bar() End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_6() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Goo Public Event F As [|$$NS.Bar.MyDel|] End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Goo Public Event F As NS.Bar.MyDel End Class Namespace NS Public Class Bar End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Class Or TypeKindOptions.Structure Or TypeKindOptions.Module)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_7() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$Delegate1|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As Delegate1 End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_8() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$NS.Delegate1|] End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As NS.Delegate1 End Class Namespace NS Public Class Delegate1 End Class End Namespace </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_9() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Bar Public WithEvents G As [|$$NS.Delegate1.MyDel|] End Class Namespace NS End Namespace</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Bar Public WithEvents G As NS.Delegate1.MyDel End Class Namespace NS Public Class Delegate1 End Class End Namespace</Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_10() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Baz Public Class Goo Public Event F As [|$$Bar|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Class Baz Public Class Goo Public Event F As Bar End Class End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_11() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Baz Public Class Goo Public Event F As [|$$Bar|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Bar", expected:=<Text> Public Class Baz Public Class Goo Public Event F As Bar End Class End Class Public Delegate Sub Bar() </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Delegate, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.Delegate)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_12() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Class Baz Public Class Bar Public WithEvents G As [|$$Delegate1|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Class Baz Public Class Bar Public WithEvents G As Delegate1 End Class End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(False, TypeKindOptions.BaseList)) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateType)> Public Async Function GenerateType_Event_13() As Task Await TestWithMockedGenerateTypeDialog( initial:=<Text> Public Class Baz Public Class Bar Public WithEvents G As [|$$Delegate1|] End Class End Class</Text>.NormalizedValue, languageName:=LanguageNames.VisualBasic, typeName:="Delegate1", expected:=<Text> Public Class Baz Public Class Bar Public WithEvents G As Delegate1 End Class End Class Public Class Delegate1 End Class </Text>.NormalizedValue, isNewFile:=False, accessibility:=Accessibility.Public, typeKind:=TypeKind.Class, assertGenerateTypeDialogOptions:=New GenerateTypeDialogOptions(True, TypeKindOptions.BaseList)) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/StatementTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class StatementTests Inherits ExpressionCompilerTestBase <Fact> Public Sub AddAssignmentStatement() Const source = " Class C Sub M() Dim d As Double = 0 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="d += 1.1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 13 (0xd) .maxstack 2 .locals init (Double V_0) //d IL_0000: ldloc.0 IL_0001: ldc.r8 1.1 IL_000a: add IL_000b: stloc.0 IL_000c: ret } ") End Sub <Fact> Public Sub AddHandlerStatement() Const source = " Class C Event a() Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:=" AddHandler a, AddressOf System.Console.WriteLine", errorMessage:=errorMessage) 'Statements of type 'AddHandlerStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.AddHandlerStatement), errorMessage) End Sub <Fact> Public Sub ArrayAccess() Const source = " Module Module1 Sub Main(args() As String) End Sub End Module " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="args(1)", errorMessage:=errorMessage) Assert.Equal("error BC30454: Expression is not a method.", errorMessage) testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="args(1) = ""Hi""", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldstr ""Hi"" IL_0007: stelem.ref IL_0008: ret } ") testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="?args(1)", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 4 (0x4) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldelem.ref IL_0003: ret } ") testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="?args(1) = ""Hi""", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 18 (0x12) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldelem.ref IL_0003: ldstr ""Hi"" IL_0008: ldc.i4.0 IL_0009: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"" IL_000e: ldc.i4.0 IL_000f: ceq IL_0011: ret } ") End Sub <Fact> Public Sub CallStatement() Const source = " Class C Private member As Integer = 1 Public Sub Increment() member += 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.Increment", expr:="Call (New C).Increment()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 11 (0xb) .maxstack 1 .locals init (Integer& V_0) IL_0000: newobj ""Sub C..ctor()"" IL_0005: call ""Sub C.Increment()"" IL_000a: ret } ") End Sub <Fact> Public Sub ConcatenateAssignmentStatement() Const source = " Module Module1 Sub M() Dim s As String = ""a"" End Sub End Module " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="Module1.M", expr:="s &= 1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 14 (0xe) .maxstack 2 .locals init (String V_0) //s IL_0000: ldloc.0 IL_0001: ldc.i4.1 IL_0002: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"" IL_0007: call ""Function String.Concat(String, String) As String"" IL_000c: stloc.0 IL_000d: ret } ") End Sub <Fact> Public Sub DivideAssignmentStatement() Const source = " Class C Sub M() Dim b As Byte = 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="b /= 0", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 20 (0x14) .maxstack 2 .locals init (Byte V_0) //b IL_0000: ldloc.0 IL_0001: conv.r8 IL_0002: ldc.r8 0 IL_000b: div IL_000c: call ""Function System.Math.Round(Double) As Double"" IL_0011: conv.ovf.u1 IL_0012: stloc.0 IL_0013: ret } ") End Sub <Fact> Public Sub EmptyStatement() Const source = " Class C Sub M() End Sub End Class " ' We should never hit this case in the VS scenario, but testing to make ' sure we do something reasonable if we ever did. Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="", errorMessage:=errorMessage) 'Statements of type 'EmptyStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.EmptyStatement), errorMessage) End Sub <Fact> Public Sub EndStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="End", errorMessage:=errorMessage) 'Statements of type 'EndStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.EndStatement), errorMessage) End Sub <Fact> Public Sub ExponentiateAssignmentStatement() Const source = " Class C Sub M() Dim m As Decimal End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="m ^= 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 28 (0x1c) .maxstack 3 .locals init (Decimal V_0) //m IL_0000: ldloca.s V_0 IL_0002: ldloc.0 IL_0003: call ""Function System.Convert.ToDouble(Decimal) As Double"" IL_0008: ldc.r8 2 IL_0011: call ""Function System.Math.Pow(Double, Double) As Double"" IL_0016: call ""Sub Decimal..ctor(Double)"" IL_001b: ret } ") End Sub <Fact> Public Sub ExpressionStatement() Const source = " Class C Public Sub M() Dim x As Integer = 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="System.Console.WriteLine()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 0 .locals init (Integer V_0) //x IL_0000: call ""Sub System.Console.WriteLine()"" IL_0005: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="System.Console.Read()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0) //x IL_0000: call ""Function System.Console.Read() As Integer"" IL_0005: pop IL_0006: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="x", errorMessage:=errorMessage) Assert.Equal("error BC30454: Expression is not a method.", errorMessage) End Sub <Fact> Public Sub IfStatement() Const source = " Class C Sub M() Dim x As Integer = 0 End Sub End Class " ' The old EE used to support single-line If statements, but Roslyn does not. This is because Parser.ParseStatementInMethodBody ' does directly handle the single-line case. If we end up needing to support single-line if, then we either need to fix parsing ' of single-line Ifs in ParseStatementInMethodBody (ADGreen knows more), or we need to duplicate the parser logic for handling ' them in the EE. Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:=" If True Then x = 1", errorMessage:=errorMessage) Assert.Equal("error BC30035: Syntax error.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:=" If True Then x = 1 Else x = 2", errorMessage:=errorMessage) Assert.Equal("error BC30035: Syntax error.", errorMessage) End Sub <Fact> Public Sub IntegerDivideAssignmentStatement() Const source = " Class C Sub M() Dim odd As UInteger End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="odd \= 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 8 (0x8) .maxstack 2 .locals init (UInteger V_0) //odd IL_0000: ldloc.0 IL_0001: conv.u8 IL_0002: ldc.i4.2 IL_0003: conv.i8 IL_0004: div IL_0005: conv.ovf.u4 IL_0006: stloc.0 IL_0007: ret } ") End Sub <Fact> Public Sub LeftShiftAssignmentStatement() Const source = " Class C Sub M() Dim s As Short End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="s <<= 16", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 10 (0xa) .maxstack 3 .locals init (Short V_0) //s IL_0000: ldloc.0 IL_0001: ldc.i4.s 16 IL_0003: ldc.i4.s 15 IL_0005: and IL_0006: shl IL_0007: conv.i2 IL_0008: stloc.0 IL_0009: ret } ") End Sub <Fact> Public Sub MultiplyAssignmentStatement() Const source = " Class C Sub M() Dim l As ULong End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="l *= l", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 5 (0x5) .maxstack 2 .locals init (ULong V_0) //l IL_0000: ldloc.0 IL_0001: ldloc.0 IL_0002: mul.ovf.un IL_0003: stloc.0 IL_0004: ret } ") End Sub <Fact> Public Sub OnErrorResumeNextStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="On Error Resume Next", errorMessage:=errorMessage) 'Statements of type 'OnErrorResumeNextStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.OnErrorResumeNextStatement), errorMessage) End Sub <Fact> Public Sub PrintStatement() Const source = " Class C Public Sub M() Dim x As Integer = 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="?x = 1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 5 (0x5) .maxstack 2 .locals init (Integer V_0) //x IL_0000: ldloc.0 IL_0001: ldc.i4.1 IL_0002: ceq IL_0004: ret } ") ' We should never hit this case in the VS scenario, but testing to make ' sure we do something reasonable if we ever did. testData = EvaluateStatement( source, methodName:="C.M", expr:="? ", errorMessage:=errorMessage) Assert.Equal("error BC30201: Expression expected.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:="??x = 1", errorMessage:=errorMessage) Assert.Equal("error BC30201: Expression expected.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:="?System.Console.WriteLine()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 0 .locals init (Integer V_0) //x IL_0000: call ""Sub System.Console.WriteLine()"" IL_0005: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="?System.Console.Read()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 1 .locals init (Integer V_0) //x IL_0000: call ""Function System.Console.Read() As Integer"" IL_0005: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="?AddressOf System.Console.WriteLine", errorMessage:=errorMessage) Assert.Equal("error BC30491: Expression does not produce a value.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:="?x += 1", errorMessage:=errorMessage) Assert.Equal("error BC37237: '+=' is not a valid format specifier", errorMessage) ' not the best error, but not worth modifying parsing to improve... End Sub <Fact> Public Sub RedimStatement() Const source = " Class C Public Sub M() Dim a(1) As Integer End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="ReDim a(2), a(3)", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 15 (0xf) .maxstack 1 .locals init (Integer() V_0) //a IL_0000: ldc.i4.3 IL_0001: newarr ""Integer"" IL_0006: stloc.0 IL_0007: ldc.i4.4 IL_0008: newarr ""Integer"" IL_000d: stloc.0 IL_000e: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="?ReDim a(2), a(3)", errorMessage:=errorMessage) Assert.Equal("error BC30201: Expression expected.", errorMessage) End Sub <Fact> Public Sub RedimPreserveStatement() Const source = " Module Module1 Public Sub M() Dim a(1) As Integer End Sub End Module " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="Module1.M", expr:="ReDim Preserve a(2)", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 19 (0x13) .maxstack 2 .locals init (Integer() V_0) //a IL_0000: ldloc.0 IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"" IL_000c: castclass ""Integer()"" IL_0011: stloc.0 IL_0012: ret } ") End Sub <Fact> Public Sub RightShiftAssignmentStatement() Const source = " Class C Sub M() Dim u As UShort = &H8000 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="u >>= &H1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 2 .locals init (UShort V_0) //u IL_0000: ldloc.0 IL_0001: ldc.i4.1 IL_0002: shr.un IL_0003: conv.u2 IL_0004: stloc.0 IL_0005: ret } ") End Sub <Fact> Public Sub SimpleAssignmentStatement() Const source = " Class C Private field As Integer = 1 Property Prop As C Public Sub M() Dim c1 As New C() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="field = 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 8 (0x8) .maxstack 2 .locals init (C V_0) //c1 IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: stfld ""C.field As Integer"" IL_0007: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="c1.Prop.field = 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 13 (0xd) .maxstack 2 .locals init (C V_0) //c1 IL_0000: ldloc.0 IL_0001: callvirt ""Function C.get_Prop() As C"" IL_0006: ldc.i4.2 IL_0007: stfld ""C.field As Integer"" IL_000c: ret } ") End Sub <Fact> Public Sub StopStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="Stop", errorMessage:=errorMessage) 'Statements of type 'StopStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.StopStatement), errorMessage) End Sub <Fact> Public Sub SubtractAssignmentStatement() Const source = " Class C Property D As Decimal Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="d -= 3.14159D", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 34 (0x22) .maxstack 7 .locals init (C V_0) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: callvirt ""Function C.get_D() As Decimal"" IL_0009: ldc.i4 0x4cb2f IL_000e: ldc.i4.0 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldc.i4.5 IL_0012: newobj ""Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"" IL_0017: call ""Function Decimal.Subtract(Decimal, Decimal) As Decimal"" IL_001c: callvirt ""Sub C.set_D(Decimal)"" IL_0021: ret } ") End Sub <Fact> Public Sub WhileStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:=" While True :: End While", errorMessage:=errorMessage) Assert.Equal("error BC30035: Syntax error.", errorMessage) ' not the best error, but not worth modifying parsing to improve... End Sub Private Function EvaluateStatement(source As String, methodName As String, expr As String, <Out> ByRef errorMessage As String, Optional atLineNumber As Integer = -1) As CompilationTestData Dim compilationFlags = DkmEvaluationFlags.None If expr IsNot Nothing AndAlso expr.StartsWith("?", StringComparison.Ordinal) Then ' This mimics Immediate Window behavior... compilationFlags = DkmEvaluationFlags.TreatAsExpression expr = expr.Substring(1) End If Dim compilation0 = CreateEmptyCompilationWithReferences( {Parse(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef, MsvbRef}, options:=TestOptions.DebugDll) Dim runtime = CreateRuntimeInstance(compilation0) Dim context = CreateMethodContext(runtime, methodName, atLineNumber) Dim testData = New CompilationTestData() Dim resultProperties As ResultProperties = Nothing Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing Dim result = context.CompileExpression( expr, compilationFlags, NoAliases, DebuggerDiagnosticFormatter.Instance, resultProperties, errorMessage, missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData) Assert.Empty(missingAssemblyIdentities) Return testData End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Microsoft.VisualStudio.Debugger.Evaluation Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class StatementTests Inherits ExpressionCompilerTestBase <Fact> Public Sub AddAssignmentStatement() Const source = " Class C Sub M() Dim d As Double = 0 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="d += 1.1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 13 (0xd) .maxstack 2 .locals init (Double V_0) //d IL_0000: ldloc.0 IL_0001: ldc.r8 1.1 IL_000a: add IL_000b: stloc.0 IL_000c: ret } ") End Sub <Fact> Public Sub AddHandlerStatement() Const source = " Class C Event a() Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:=" AddHandler a, AddressOf System.Console.WriteLine", errorMessage:=errorMessage) 'Statements of type 'AddHandlerStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.AddHandlerStatement), errorMessage) End Sub <Fact> Public Sub ArrayAccess() Const source = " Module Module1 Sub Main(args() As String) End Sub End Module " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="args(1)", errorMessage:=errorMessage) Assert.Equal("error BC30454: Expression is not a method.", errorMessage) testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="args(1) = ""Hi""", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldstr ""Hi"" IL_0007: stelem.ref IL_0008: ret } ") testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="?args(1)", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 4 (0x4) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldelem.ref IL_0003: ret } ") testData = EvaluateStatement( source, methodName:="Module1.Main", expr:="?args(1) = ""Hi""", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 18 (0x12) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: ldelem.ref IL_0003: ldstr ""Hi"" IL_0008: ldc.i4.0 IL_0009: call ""Function Microsoft.VisualBasic.CompilerServices.Operators.CompareString(String, String, Boolean) As Integer"" IL_000e: ldc.i4.0 IL_000f: ceq IL_0011: ret } ") End Sub <Fact> Public Sub CallStatement() Const source = " Class C Private member As Integer = 1 Public Sub Increment() member += 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.Increment", expr:="Call (New C).Increment()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 11 (0xb) .maxstack 1 .locals init (Integer& V_0) IL_0000: newobj ""Sub C..ctor()"" IL_0005: call ""Sub C.Increment()"" IL_000a: ret } ") End Sub <Fact> Public Sub ConcatenateAssignmentStatement() Const source = " Module Module1 Sub M() Dim s As String = ""a"" End Sub End Module " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="Module1.M", expr:="s &= 1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 14 (0xe) .maxstack 2 .locals init (String V_0) //s IL_0000: ldloc.0 IL_0001: ldc.i4.1 IL_0002: call ""Function Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Integer) As String"" IL_0007: call ""Function String.Concat(String, String) As String"" IL_000c: stloc.0 IL_000d: ret } ") End Sub <Fact> Public Sub DivideAssignmentStatement() Const source = " Class C Sub M() Dim b As Byte = 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="b /= 0", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 20 (0x14) .maxstack 2 .locals init (Byte V_0) //b IL_0000: ldloc.0 IL_0001: conv.r8 IL_0002: ldc.r8 0 IL_000b: div IL_000c: call ""Function System.Math.Round(Double) As Double"" IL_0011: conv.ovf.u1 IL_0012: stloc.0 IL_0013: ret } ") End Sub <Fact> Public Sub EmptyStatement() Const source = " Class C Sub M() End Sub End Class " ' We should never hit this case in the VS scenario, but testing to make ' sure we do something reasonable if we ever did. Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="", errorMessage:=errorMessage) 'Statements of type 'EmptyStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.EmptyStatement), errorMessage) End Sub <Fact> Public Sub EndStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="End", errorMessage:=errorMessage) 'Statements of type 'EndStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.EndStatement), errorMessage) End Sub <Fact> Public Sub ExponentiateAssignmentStatement() Const source = " Class C Sub M() Dim m As Decimal End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="m ^= 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 28 (0x1c) .maxstack 3 .locals init (Decimal V_0) //m IL_0000: ldloca.s V_0 IL_0002: ldloc.0 IL_0003: call ""Function System.Convert.ToDouble(Decimal) As Double"" IL_0008: ldc.r8 2 IL_0011: call ""Function System.Math.Pow(Double, Double) As Double"" IL_0016: call ""Sub Decimal..ctor(Double)"" IL_001b: ret } ") End Sub <Fact> Public Sub ExpressionStatement() Const source = " Class C Public Sub M() Dim x As Integer = 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="System.Console.WriteLine()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 0 .locals init (Integer V_0) //x IL_0000: call ""Sub System.Console.WriteLine()"" IL_0005: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="System.Console.Read()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 7 (0x7) .maxstack 1 .locals init (Integer V_0) //x IL_0000: call ""Function System.Console.Read() As Integer"" IL_0005: pop IL_0006: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="x", errorMessage:=errorMessage) Assert.Equal("error BC30454: Expression is not a method.", errorMessage) End Sub <Fact> Public Sub IfStatement() Const source = " Class C Sub M() Dim x As Integer = 0 End Sub End Class " ' The old EE used to support single-line If statements, but Roslyn does not. This is because Parser.ParseStatementInMethodBody ' does directly handle the single-line case. If we end up needing to support single-line if, then we either need to fix parsing ' of single-line Ifs in ParseStatementInMethodBody (ADGreen knows more), or we need to duplicate the parser logic for handling ' them in the EE. Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:=" If True Then x = 1", errorMessage:=errorMessage) Assert.Equal("error BC30035: Syntax error.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:=" If True Then x = 1 Else x = 2", errorMessage:=errorMessage) Assert.Equal("error BC30035: Syntax error.", errorMessage) End Sub <Fact> Public Sub IntegerDivideAssignmentStatement() Const source = " Class C Sub M() Dim odd As UInteger End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="odd \= 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 8 (0x8) .maxstack 2 .locals init (UInteger V_0) //odd IL_0000: ldloc.0 IL_0001: conv.u8 IL_0002: ldc.i4.2 IL_0003: conv.i8 IL_0004: div IL_0005: conv.ovf.u4 IL_0006: stloc.0 IL_0007: ret } ") End Sub <Fact> Public Sub LeftShiftAssignmentStatement() Const source = " Class C Sub M() Dim s As Short End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="s <<= 16", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 10 (0xa) .maxstack 3 .locals init (Short V_0) //s IL_0000: ldloc.0 IL_0001: ldc.i4.s 16 IL_0003: ldc.i4.s 15 IL_0005: and IL_0006: shl IL_0007: conv.i2 IL_0008: stloc.0 IL_0009: ret } ") End Sub <Fact> Public Sub MultiplyAssignmentStatement() Const source = " Class C Sub M() Dim l As ULong End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="l *= l", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 5 (0x5) .maxstack 2 .locals init (ULong V_0) //l IL_0000: ldloc.0 IL_0001: ldloc.0 IL_0002: mul.ovf.un IL_0003: stloc.0 IL_0004: ret } ") End Sub <Fact> Public Sub OnErrorResumeNextStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="On Error Resume Next", errorMessage:=errorMessage) 'Statements of type 'OnErrorResumeNextStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.OnErrorResumeNextStatement), errorMessage) End Sub <Fact> Public Sub PrintStatement() Const source = " Class C Public Sub M() Dim x As Integer = 1 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="?x = 1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 5 (0x5) .maxstack 2 .locals init (Integer V_0) //x IL_0000: ldloc.0 IL_0001: ldc.i4.1 IL_0002: ceq IL_0004: ret } ") ' We should never hit this case in the VS scenario, but testing to make ' sure we do something reasonable if we ever did. testData = EvaluateStatement( source, methodName:="C.M", expr:="? ", errorMessage:=errorMessage) Assert.Equal("error BC30201: Expression expected.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:="??x = 1", errorMessage:=errorMessage) Assert.Equal("error BC30201: Expression expected.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:="?System.Console.WriteLine()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 0 .locals init (Integer V_0) //x IL_0000: call ""Sub System.Console.WriteLine()"" IL_0005: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="?System.Console.Read()", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 1 .locals init (Integer V_0) //x IL_0000: call ""Function System.Console.Read() As Integer"" IL_0005: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="?AddressOf System.Console.WriteLine", errorMessage:=errorMessage) Assert.Equal("error BC30491: Expression does not produce a value.", errorMessage) testData = EvaluateStatement( source, methodName:="C.M", expr:="?x += 1", errorMessage:=errorMessage) Assert.Equal("error BC37237: '+=' is not a valid format specifier", errorMessage) ' not the best error, but not worth modifying parsing to improve... End Sub <Fact> Public Sub RedimStatement() Const source = " Class C Public Sub M() Dim a(1) As Integer End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="ReDim a(2), a(3)", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 15 (0xf) .maxstack 1 .locals init (Integer() V_0) //a IL_0000: ldc.i4.3 IL_0001: newarr ""Integer"" IL_0006: stloc.0 IL_0007: ldc.i4.4 IL_0008: newarr ""Integer"" IL_000d: stloc.0 IL_000e: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="?ReDim a(2), a(3)", errorMessage:=errorMessage) Assert.Equal("error BC30201: Expression expected.", errorMessage) End Sub <Fact> Public Sub RedimPreserveStatement() Const source = " Module Module1 Public Sub M() Dim a(1) As Integer End Sub End Module " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="Module1.M", expr:="ReDim Preserve a(2)", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 19 (0x13) .maxstack 2 .locals init (Integer() V_0) //a IL_0000: ldloc.0 IL_0001: ldc.i4.3 IL_0002: newarr ""Integer"" IL_0007: call ""Function Microsoft.VisualBasic.CompilerServices.Utils.CopyArray(System.Array, System.Array) As System.Array"" IL_000c: castclass ""Integer()"" IL_0011: stloc.0 IL_0012: ret } ") End Sub <Fact> Public Sub RightShiftAssignmentStatement() Const source = " Class C Sub M() Dim u As UShort = &H8000 End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="u >>= &H1", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 6 (0x6) .maxstack 2 .locals init (UShort V_0) //u IL_0000: ldloc.0 IL_0001: ldc.i4.1 IL_0002: shr.un IL_0003: conv.u2 IL_0004: stloc.0 IL_0005: ret } ") End Sub <Fact> Public Sub SimpleAssignmentStatement() Const source = " Class C Private field As Integer = 1 Property Prop As C Public Sub M() Dim c1 As New C() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="field = 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 8 (0x8) .maxstack 2 .locals init (C V_0) //c1 IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: stfld ""C.field As Integer"" IL_0007: ret } ") testData = EvaluateStatement( source, methodName:="C.M", expr:="c1.Prop.field = 2", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 13 (0xd) .maxstack 2 .locals init (C V_0) //c1 IL_0000: ldloc.0 IL_0001: callvirt ""Function C.get_Prop() As C"" IL_0006: ldc.i4.2 IL_0007: stfld ""C.field As Integer"" IL_000c: ret } ") End Sub <Fact> Public Sub StopStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="Stop", errorMessage:=errorMessage) 'Statements of type 'StopStatement' are not allowed in the Immediate window. Assert.Equal(String.Format(ExpressionEvaluator.Resources.InvalidDebuggerStatement, SyntaxKind.StopStatement), errorMessage) End Sub <Fact> Public Sub SubtractAssignmentStatement() Const source = " Class C Property D As Decimal Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:="d -= 3.14159D", errorMessage:=errorMessage) Assert.Null(errorMessage) testData.GetMethodData("<>x.<>m0").VerifyIL(" { // Code size 34 (0x22) .maxstack 7 .locals init (C V_0) IL_0000: ldarg.0 IL_0001: dup IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: callvirt ""Function C.get_D() As Decimal"" IL_0009: ldc.i4 0x4cb2f IL_000e: ldc.i4.0 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldc.i4.5 IL_0012: newobj ""Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)"" IL_0017: call ""Function Decimal.Subtract(Decimal, Decimal) As Decimal"" IL_001c: callvirt ""Sub C.set_D(Decimal)"" IL_0021: ret } ") End Sub <Fact> Public Sub WhileStatement() Const source = " Class C Sub M() End Sub End Class " Dim errorMessage As String = Nothing Dim testData = EvaluateStatement( source, methodName:="C.M", expr:=" While True :: End While", errorMessage:=errorMessage) Assert.Equal("error BC30035: Syntax error.", errorMessage) ' not the best error, but not worth modifying parsing to improve... End Sub Private Function EvaluateStatement(source As String, methodName As String, expr As String, <Out> ByRef errorMessage As String, Optional atLineNumber As Integer = -1) As CompilationTestData Dim compilationFlags = DkmEvaluationFlags.None If expr IsNot Nothing AndAlso expr.StartsWith("?", StringComparison.Ordinal) Then ' This mimics Immediate Window behavior... compilationFlags = DkmEvaluationFlags.TreatAsExpression expr = expr.Substring(1) End If Dim compilation0 = CreateEmptyCompilationWithReferences( {Parse(source)}, {MscorlibRef_v4_0_30316_17626, SystemRef, MsvbRef}, options:=TestOptions.DebugDll) Dim runtime = CreateRuntimeInstance(compilation0) Dim context = CreateMethodContext(runtime, methodName, atLineNumber) Dim testData = New CompilationTestData() Dim resultProperties As ResultProperties = Nothing Dim missingAssemblyIdentities As ImmutableArray(Of AssemblyIdentity) = Nothing Dim result = context.CompileExpression( expr, compilationFlags, NoAliases, DebuggerDiagnosticFormatter.Instance, resultProperties, errorMessage, missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData) Assert.Empty(missingAssemblyIdentities) Return testData End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Core/Portable/StrongName/StrongNameKeys.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class StrongNameKeys { /// <summary> /// The strong name key associated with the identity of this assembly. /// This contains the contents of the user-supplied key file exactly as extracted. /// </summary> internal readonly ImmutableArray<byte> KeyPair; /// <summary> /// Determines source assembly identity. /// </summary> internal readonly ImmutableArray<byte> PublicKey; /// <summary> /// The Private key information that will exist if it was a private key file that was parsed. /// </summary> internal readonly RSAParameters? PrivateKey; /// <summary> /// A diagnostic created in the process of determining the key. /// </summary> internal readonly Diagnostic? DiagnosticOpt; /// <summary> /// The CSP key container containing the public key used to produce the key, /// or null if the key was retrieved from <see cref="KeyFilePath"/>. /// </summary> /// <remarks> /// The original value as specified by <see cref="System.Reflection.AssemblyKeyNameAttribute"/> or /// <see cref="CompilationOptions.CryptoKeyContainer"/>. /// </remarks> internal readonly string? KeyContainer; /// <summary> /// Original key file path, or null if the key is provided by the <see cref="KeyContainer"/>. /// </summary> /// <remarks> /// The original value as specified by <see cref="System.Reflection.AssemblyKeyFileAttribute"/> or /// <see cref="CompilationOptions.CryptoKeyFile"/> /// </remarks> internal readonly string? KeyFilePath; /// <summary> /// True when the assembly contains a <see cref="System.Reflection.AssemblySignatureKeyAttribute"/> value /// and hence signing requires counter signature verification. /// </summary> internal readonly bool HasCounterSignature; internal static readonly StrongNameKeys None = new StrongNameKeys(); private StrongNameKeys() { } internal StrongNameKeys(Diagnostic diagnostic) { Debug.Assert(diagnostic != null); this.DiagnosticOpt = diagnostic; } internal StrongNameKeys(ImmutableArray<byte> keyPair, ImmutableArray<byte> publicKey, RSAParameters? privateKey, string? keyContainerName, string? keyFilePath, bool hasCounterSignature) { Debug.Assert(keyContainerName == null || keyPair.IsDefault); Debug.Assert(keyPair.IsDefault || keyFilePath != null); this.KeyPair = keyPair; this.PublicKey = publicKey; this.PrivateKey = privateKey; this.KeyContainer = keyContainerName; this.KeyFilePath = keyFilePath; this.HasCounterSignature = hasCounterSignature; } internal static StrongNameKeys Create(ImmutableArray<byte> publicKey, RSAParameters? privateKey, bool hasCounterSignature, CommonMessageProvider messageProvider) { Debug.Assert(!publicKey.IsDefaultOrEmpty); if (MetadataHelpers.IsValidPublicKey(publicKey)) { return new StrongNameKeys(keyPair: default, publicKey, privateKey, keyContainerName: null, keyFilePath: null, hasCounterSignature); } else { return new StrongNameKeys(messageProvider.CreateDiagnostic(messageProvider.ERR_BadCompilationOptionValue, Location.None, nameof(CompilationOptions.CryptoPublicKey), BitConverter.ToString(publicKey.ToArray()))); } } internal static StrongNameKeys Create(string? keyFilePath, CommonMessageProvider messageProvider) { if (string.IsNullOrEmpty(keyFilePath)) { return None; } try { var fileContent = ImmutableArray.Create(File.ReadAllBytes(keyFilePath)); return CreateHelper(fileContent, keyFilePath, hasCounterSignature: false); } catch (IOException ex) { return new StrongNameKeys(GetKeyFileError(messageProvider, keyFilePath, ex.Message)); } } //Last seen key file blob and corresponding public key. //In IDE typing scenarios we often need to infer public key from the same //key file blob repeatedly and it is relatively expensive. //So we will store last seen blob and corresponding key here. private static Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>? s_lastSeenKeyPair; // Note: Errors are reported by throwing an IOException internal static StrongNameKeys CreateHelper(ImmutableArray<byte> keyFileContent, string keyFilePath, bool hasCounterSignature) { ImmutableArray<byte> keyPair; ImmutableArray<byte> publicKey; RSAParameters? privateKey = null; // Check the key pair cache var cachedKeyPair = s_lastSeenKeyPair; if (cachedKeyPair != null && keyFileContent == cachedKeyPair.Item1) { keyPair = cachedKeyPair.Item1; publicKey = cachedKeyPair.Item2; privateKey = cachedKeyPair.Item3; } else { if (MetadataHelpers.IsValidPublicKey(keyFileContent)) { publicKey = keyFileContent; keyPair = default; } else if (CryptoBlobParser.TryParseKey(keyFileContent, out publicKey, out privateKey)) { keyPair = keyFileContent; } else { throw new IOException(CodeAnalysisResources.InvalidPublicKey); } // Cache the key pair cachedKeyPair = new Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>(keyPair, publicKey, privateKey); Interlocked.Exchange(ref s_lastSeenKeyPair, cachedKeyPair); } return new StrongNameKeys(keyPair, publicKey, privateKey, null, keyFilePath, hasCounterSignature); } internal static StrongNameKeys Create(StrongNameProvider? providerOpt, string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) { if (string.IsNullOrEmpty(keyFilePath) && string.IsNullOrEmpty(keyContainerName)) { return None; } if (providerOpt == null) { var diagnostic = GetError(keyFilePath, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)), messageProvider); return new StrongNameKeys(diagnostic); } return providerOpt.CreateKeys(keyFilePath, keyContainerName, hasCounterSignature, messageProvider); } /// <summary> /// True if the compilation can be signed using these keys. /// </summary> internal bool CanSign { get { return !KeyPair.IsDefault || KeyContainer != null; } } /// <summary> /// True if a strong name can be created for the compilation using these keys. /// </summary> internal bool CanProvideStrongName { get { return CanSign || !PublicKey.IsDefault; } } internal static Diagnostic GetError(string? keyFilePath, string? keyContainerName, object message, CommonMessageProvider messageProvider) { if (keyContainerName != null) { return GetContainerError(messageProvider, keyContainerName, message); } else { Debug.Assert(keyFilePath is object); return GetKeyFileError(messageProvider, keyFilePath, message); } } internal static Diagnostic GetContainerError(CommonMessageProvider messageProvider, string name, object message) { return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyContainerFailure, Location.None, name, message); } internal static Diagnostic GetKeyFileError(CommonMessageProvider messageProvider, string path, object message) { return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyFileFailure, Location.None, path, message); } internal static bool IsValidPublicKeyString(string? publicKey) { if (string.IsNullOrEmpty(publicKey) || publicKey.Length % 2 != 0) { return false; } foreach (char c in publicKey) { if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) { return false; } } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; namespace Microsoft.CodeAnalysis { internal sealed class StrongNameKeys { /// <summary> /// The strong name key associated with the identity of this assembly. /// This contains the contents of the user-supplied key file exactly as extracted. /// </summary> internal readonly ImmutableArray<byte> KeyPair; /// <summary> /// Determines source assembly identity. /// </summary> internal readonly ImmutableArray<byte> PublicKey; /// <summary> /// The Private key information that will exist if it was a private key file that was parsed. /// </summary> internal readonly RSAParameters? PrivateKey; /// <summary> /// A diagnostic created in the process of determining the key. /// </summary> internal readonly Diagnostic? DiagnosticOpt; /// <summary> /// The CSP key container containing the public key used to produce the key, /// or null if the key was retrieved from <see cref="KeyFilePath"/>. /// </summary> /// <remarks> /// The original value as specified by <see cref="System.Reflection.AssemblyKeyNameAttribute"/> or /// <see cref="CompilationOptions.CryptoKeyContainer"/>. /// </remarks> internal readonly string? KeyContainer; /// <summary> /// Original key file path, or null if the key is provided by the <see cref="KeyContainer"/>. /// </summary> /// <remarks> /// The original value as specified by <see cref="System.Reflection.AssemblyKeyFileAttribute"/> or /// <see cref="CompilationOptions.CryptoKeyFile"/> /// </remarks> internal readonly string? KeyFilePath; /// <summary> /// True when the assembly contains a <see cref="System.Reflection.AssemblySignatureKeyAttribute"/> value /// and hence signing requires counter signature verification. /// </summary> internal readonly bool HasCounterSignature; internal static readonly StrongNameKeys None = new StrongNameKeys(); private StrongNameKeys() { } internal StrongNameKeys(Diagnostic diagnostic) { Debug.Assert(diagnostic != null); this.DiagnosticOpt = diagnostic; } internal StrongNameKeys(ImmutableArray<byte> keyPair, ImmutableArray<byte> publicKey, RSAParameters? privateKey, string? keyContainerName, string? keyFilePath, bool hasCounterSignature) { Debug.Assert(keyContainerName == null || keyPair.IsDefault); Debug.Assert(keyPair.IsDefault || keyFilePath != null); this.KeyPair = keyPair; this.PublicKey = publicKey; this.PrivateKey = privateKey; this.KeyContainer = keyContainerName; this.KeyFilePath = keyFilePath; this.HasCounterSignature = hasCounterSignature; } internal static StrongNameKeys Create(ImmutableArray<byte> publicKey, RSAParameters? privateKey, bool hasCounterSignature, CommonMessageProvider messageProvider) { Debug.Assert(!publicKey.IsDefaultOrEmpty); if (MetadataHelpers.IsValidPublicKey(publicKey)) { return new StrongNameKeys(keyPair: default, publicKey, privateKey, keyContainerName: null, keyFilePath: null, hasCounterSignature); } else { return new StrongNameKeys(messageProvider.CreateDiagnostic(messageProvider.ERR_BadCompilationOptionValue, Location.None, nameof(CompilationOptions.CryptoPublicKey), BitConverter.ToString(publicKey.ToArray()))); } } internal static StrongNameKeys Create(string? keyFilePath, CommonMessageProvider messageProvider) { if (string.IsNullOrEmpty(keyFilePath)) { return None; } try { var fileContent = ImmutableArray.Create(File.ReadAllBytes(keyFilePath)); return CreateHelper(fileContent, keyFilePath, hasCounterSignature: false); } catch (IOException ex) { return new StrongNameKeys(GetKeyFileError(messageProvider, keyFilePath, ex.Message)); } } //Last seen key file blob and corresponding public key. //In IDE typing scenarios we often need to infer public key from the same //key file blob repeatedly and it is relatively expensive. //So we will store last seen blob and corresponding key here. private static Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>? s_lastSeenKeyPair; // Note: Errors are reported by throwing an IOException internal static StrongNameKeys CreateHelper(ImmutableArray<byte> keyFileContent, string keyFilePath, bool hasCounterSignature) { ImmutableArray<byte> keyPair; ImmutableArray<byte> publicKey; RSAParameters? privateKey = null; // Check the key pair cache var cachedKeyPair = s_lastSeenKeyPair; if (cachedKeyPair != null && keyFileContent == cachedKeyPair.Item1) { keyPair = cachedKeyPair.Item1; publicKey = cachedKeyPair.Item2; privateKey = cachedKeyPair.Item3; } else { if (MetadataHelpers.IsValidPublicKey(keyFileContent)) { publicKey = keyFileContent; keyPair = default; } else if (CryptoBlobParser.TryParseKey(keyFileContent, out publicKey, out privateKey)) { keyPair = keyFileContent; } else { throw new IOException(CodeAnalysisResources.InvalidPublicKey); } // Cache the key pair cachedKeyPair = new Tuple<ImmutableArray<byte>, ImmutableArray<byte>, RSAParameters?>(keyPair, publicKey, privateKey); Interlocked.Exchange(ref s_lastSeenKeyPair, cachedKeyPair); } return new StrongNameKeys(keyPair, publicKey, privateKey, null, keyFilePath, hasCounterSignature); } internal static StrongNameKeys Create(StrongNameProvider? providerOpt, string? keyFilePath, string? keyContainerName, bool hasCounterSignature, CommonMessageProvider messageProvider) { if (string.IsNullOrEmpty(keyFilePath) && string.IsNullOrEmpty(keyContainerName)) { return None; } if (providerOpt == null) { var diagnostic = GetError(keyFilePath, keyContainerName, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.AssemblySigningNotSupported)), messageProvider); return new StrongNameKeys(diagnostic); } return providerOpt.CreateKeys(keyFilePath, keyContainerName, hasCounterSignature, messageProvider); } /// <summary> /// True if the compilation can be signed using these keys. /// </summary> internal bool CanSign { get { return !KeyPair.IsDefault || KeyContainer != null; } } /// <summary> /// True if a strong name can be created for the compilation using these keys. /// </summary> internal bool CanProvideStrongName { get { return CanSign || !PublicKey.IsDefault; } } internal static Diagnostic GetError(string? keyFilePath, string? keyContainerName, object message, CommonMessageProvider messageProvider) { if (keyContainerName != null) { return GetContainerError(messageProvider, keyContainerName, message); } else { Debug.Assert(keyFilePath is object); return GetKeyFileError(messageProvider, keyFilePath, message); } } internal static Diagnostic GetContainerError(CommonMessageProvider messageProvider, string name, object message) { return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyContainerFailure, Location.None, name, message); } internal static Diagnostic GetKeyFileError(CommonMessageProvider messageProvider, string path, object message) { return messageProvider.CreateDiagnostic(messageProvider.ERR_PublicKeyFileFailure, Location.None, path, message); } internal static bool IsValidPublicKeyString(string? publicKey) { if (string.IsNullOrEmpty(publicKey) || publicKey.Length % 2 != 0) { return false; } foreach (char c in publicKey) { if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) { return false; } } return true; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/InlineMethod/AbstractInlineMethodRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.InlineMethod { internal abstract partial class AbstractInlineMethodRefactoringProvider< TMethodDeclarationSyntax, TStatementSyntax, TExpressionSyntax, TInvocationSyntax> : CodeRefactoringProvider where TMethodDeclarationSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode where TInvocationSyntax : TExpressionSyntax { /// <summary> /// A preferred name used to generated a declaration when the /// inline method's body is not a valid expresion in ExpressionStatement /// Example: /// void Caller() /// { /// Callee(); /// } /// int Callee() /// { /// return 1; /// }; /// After it should be: /// void Caller() /// { /// int temp = 1; /// } /// int Callee() /// { /// return 1; /// }; /// '1' is not a valid expression in ExpressionStatement so a declaration is needed to be generated. /// </summary> private const string TemporaryName = "temp"; private readonly ISyntaxFacts _syntaxFacts; private readonly ISemanticFactsService _semanticFactsService; protected abstract TExpressionSyntax? GetRawInlineExpression(TMethodDeclarationSyntax calleeMethodDeclarationSyntaxNode); protected abstract SyntaxNode GenerateTypeSyntax(ITypeSymbol symbol, bool allowVar); protected abstract TExpressionSyntax GenerateLiteralExpression(ITypeSymbol typeSymbol, object? value); protected abstract bool IsFieldDeclarationSyntax(SyntaxNode node); /// <summary> /// Check if <paramref name="expressionNode"/> could be used as an Expression in ExpressionStatement /// </summary> protected abstract bool IsValidExpressionUnderExpressionStatement(TExpressionSyntax expressionNode); /// <summary> /// Check if <paramref name="syntaxNode"/> could be replaced by ThrowExpression. /// For VB it always return false because ThrowExpression doesn't exist. /// </summary> protected abstract bool CanBeReplacedByThrowExpression(SyntaxNode syntaxNode); protected AbstractInlineMethodRefactoringProvider( ISyntaxFacts syntaxFacts, ISemanticFactsService semanticFactsService) { _syntaxFacts = syntaxFacts; _semanticFactsService = semanticFactsService; } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var calleeInvocationNode = await context.TryGetRelevantNodeAsync<TInvocationSyntax>().ConfigureAwait(false); if (calleeInvocationNode == null) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var calleeMethodSymbol = semanticModel.GetSymbolInfo(calleeInvocationNode, cancellationToken).GetAnySymbol() as IMethodSymbol; if (calleeMethodSymbol == null) { return; } if (calleeMethodSymbol.PartialImplementationPart != null) { calleeMethodSymbol = calleeMethodSymbol.PartialImplementationPart; } if (!calleeMethodSymbol.IsOrdinaryMethod() && !calleeMethodSymbol.IsExtensionMethod) { return; } if (calleeMethodSymbol.IsVararg) { return; } if (calleeMethodSymbol.DeclaredAccessibility != Accessibility.Private) { return; } var symbolDeclarationService = document.GetRequiredLanguageService<ISymbolDeclarationService>(); var calleeMethodDeclarationSyntaxReferences = symbolDeclarationService.GetDeclarations(calleeMethodSymbol); if (calleeMethodDeclarationSyntaxReferences.Length != 1) { return; } var calleeMethodDeclarationSyntaxReference = calleeMethodDeclarationSyntaxReferences[0]; var calleeMethodNode = await calleeMethodDeclarationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false) as TMethodDeclarationSyntax; if (calleeMethodNode == null) { return; } var inlineExpression = GetRawInlineExpression(calleeMethodNode); // Special case 1: AwaitExpression if (_syntaxFacts.IsAwaitExpression(inlineExpression)) { // 1. If Caller & callee both have 'await' make sure there is no duplicate 'await' // Example: // Before: // async Task Caller() => await Callee(); // async Task Callee() => await Task.CompletedTask; // After: // async Task Caller() => await Task.CompletedTask; // async Task Callee() => await Task.CompletedTask; // The original inline expression in callee will be 'await Task.CompletedTask' // The caller just need 'Task.CompletedTask' without the 'await' // // 2. If Caller doesn't have await but callee has. // Example: // Before: // void Caller() { Callee().Wait();} // async Task Callee() => await DoAsync(); // After: // void Caller() { DoAsync().Wait(); } // async Task Callee() => await DoAsync(); // What caller is expecting is an expression returns 'Task', which doesn't include the 'await' inlineExpression = _syntaxFacts.GetExpressionOfAwaitExpression(inlineExpression) as TExpressionSyntax; } if (inlineExpression == null) { return; } // Special case 2: ThrowStatement & ThrowExpresion if (_syntaxFacts.IsThrowStatement(inlineExpression.Parent) || _syntaxFacts.IsThrowExpression(inlineExpression)) { // If this is a throw statement, then it should be valid for // 1. If it is invoked as ExpressionStatement // Example: // Before: // void Caller() { Callee(); } // void Callee() { throw new Exception();} // After: // void Caller() { throw new Exception(); } // void Callee() { throw new Exception();} // 2. If it is invoked in a place allow throw expression // Example: // Before: // void Caller(bool flag) { var x = flag ? Callee() : 1; } // int Callee() { throw new Exception();} // After: // void Caller() { var x = flag ? throw new Exception() : 1; } // int Callee() { throw new Exception();} // Note here throw statement is changed to throw expression after inlining // If this is a throw expression, the check is the same // 1. If it is invoked as ExpressionStatement // Example: // Before: // void Caller() { Callee(); } // void Callee() => throw new Exception(); // After: // void Caller() { throw new Exception(); } // void Callee() => throw new Exception(); // Note here throw expression is converted to throw statement // 2. If it is invoked in a place allow throw expression // Example: // Before: // void Caller(bool flag) { var x = flag ? Callee() : 1; } // int Callee() => throw new Exception(); // After: // void Caller() { var x = flag ? throw new Exception() : 1; } // int Callee() => throw new Exception(); if (!CanBeReplacedByThrowExpression(calleeInvocationNode) && !_syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent)) { return; } } var callerSymbol = GetCallerSymbol(calleeInvocationNode, semanticModel, cancellationToken); if (callerSymbol == null) { return; } var callerReferences = symbolDeclarationService.GetDeclarations(callerSymbol); if (callerReferences.Length != 1) { return; } var callerDeclarationNode = await callerReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); var invocationOperation = semanticModel.GetOperation(calleeInvocationNode, cancellationToken) as IInvocationOperation; if (invocationOperation == null) { return; } var codeActions = GenerateCodeActions( document, calleeInvocationNode, calleeMethodSymbol, calleeMethodNode, callerSymbol, callerDeclarationNode, inlineExpression, invocationOperation); var nestedCodeAction = new CodeAction.CodeActionWithNestedActions( string.Format(FeaturesResources.Inline_0, calleeMethodSymbol.ToNameDisplayString()), codeActions, isInlinable: true); context.RegisterRefactoring(nestedCodeAction, calleeInvocationNode.Span); } private ImmutableArray<CodeAction> GenerateCodeActions(Document document, TInvocationSyntax calleeMethodInvocationNode, IMethodSymbol calleeMethodSymbol, TMethodDeclarationSyntax calleeMethodNode, ISymbol callerSymbol, SyntaxNode callerMethodNode, TExpressionSyntax inlineExpression, IInvocationOperation invocationOperation) { var calleeMethodName = calleeMethodSymbol.ToNameDisplayString(); var codeActionRemovesCallee = new MySolutionChangeAction( string.Format(FeaturesResources.Inline_0, calleeMethodName), cancellationToken => InlineMethodAsync( document, calleeMethodInvocationNode, calleeMethodSymbol, calleeMethodNode, callerSymbol, callerMethodNode, inlineExpression, invocationOperation, removeCalleeDeclarationNode: true, cancellationToken: cancellationToken)); var codeActionKeepsCallee = new MySolutionChangeAction( string.Format(FeaturesResources.Inline_and_keep_0, calleeMethodName), cancellationToken => InlineMethodAsync( document, calleeMethodInvocationNode, calleeMethodSymbol, calleeMethodNode, callerSymbol, callerMethodNode, inlineExpression, invocationOperation, removeCalleeDeclarationNode: false, cancellationToken: cancellationToken)); return ImmutableArray.Create<CodeAction>(codeActionRemovesCallee, codeActionKeepsCallee); } private async Task<Solution> InlineMethodAsync(Document document, TInvocationSyntax calleeInvocationNode, IMethodSymbol calleeMethodSymbol, TMethodDeclarationSyntax calleeMethodNode, ISymbol callerSymbol, SyntaxNode callerNode, TExpressionSyntax rawInlineExpression, IInvocationOperation invocationOperation, bool removeCalleeDeclarationNode, CancellationToken cancellationToken) { // Find the statement contains the invocation. This should happen when Callee is invoked in a block // example: // void Caller() // { // Action a = () => // { // var x = Callee(); // } // } (Local declaration x is the containing node) // Note: Stop the searching when it hits lambda or local function, because for this case below don't // treat the declaration of a is the containing node // void Caller() // { // Action a = () => Callee(); // } // it could be null if the caller is invoked as arrow function var statementContainsInvocation = calleeInvocationNode.GetAncestors() .TakeWhile(node => !_syntaxFacts.IsAnonymousFunction(node) && !_syntaxFacts.IsLocalFunction(node)) .FirstOrDefault(node => node is TStatementSyntax) as TStatementSyntax; var methodParametersInfo = await GetMethodParametersInfoAsync( document, calleeInvocationNode, calleeMethodNode, statementContainsInvocation, rawInlineExpression, invocationOperation, cancellationToken).ConfigureAwait(false); var inlineContext = await GetInlineMethodContextAsync( document, calleeMethodNode, calleeInvocationNode, calleeMethodSymbol, rawInlineExpression, methodParametersInfo, cancellationToken).ConfigureAwait(false); var solution = document.Project.Solution; var solutionEditor = new SolutionEditor(solution); if (removeCalleeDeclarationNode) { var calleeDocumentId = solution.GetDocumentId(calleeMethodNode.SyntaxTree); if (calleeDocumentId != null) { var calleeDocumentEditor = await solutionEditor.GetDocumentEditorAsync(calleeDocumentId, cancellationToken).ConfigureAwait(false); calleeDocumentEditor.RemoveNode(calleeMethodNode); } } var newCallerMethodNode = await GetChangedCallerAsync( document, calleeInvocationNode, calleeMethodSymbol, callerSymbol, callerNode, statementContainsInvocation, rawInlineExpression, methodParametersInfo, inlineContext, cancellationToken).ConfigureAwait(false); var callerDocumentEditor = await solutionEditor.GetDocumentEditorAsync(document.Id, cancellationToken).ConfigureAwait(false); callerDocumentEditor.ReplaceNode(callerNode, newCallerMethodNode); return solutionEditor.GetChangedSolution(); } private async Task<SyntaxNode> GetChangedCallerAsync(Document document, TInvocationSyntax calleeInvocationNode, IMethodSymbol calleeMethodSymbol, ISymbol callerSymbol, SyntaxNode callerDeclarationNode, TStatementSyntax? statementContainsInvocation, TExpressionSyntax rawInlineExpression, MethodParametersInfo methodParametersInfo, InlineMethodContext inlineMethodContext, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var callerNodeEditor = new SyntaxEditor(callerDeclarationNode, syntaxGenerator); if (inlineMethodContext.ContainsAwaitExpression) { // If the inline content has 'await' expression, then make sure the caller is changed to 'async' method // if its return type is awaitable. In all other cases, do nothing. if (callerSymbol is IMethodSymbol callerMethodSymbol && callerMethodSymbol.IsOrdinaryMethod() && !callerMethodSymbol.IsAsync && (callerMethodSymbol.ReturnsVoid || callerMethodSymbol.IsAwaitableNonDynamic(semanticModel, callerDeclarationNode.SpanStart))) { var declarationModifiers = DeclarationModifiers.From(callerSymbol).WithAsync(true); callerNodeEditor.SetModifiers(callerDeclarationNode, declarationModifiers); } } if (statementContainsInvocation != null) { foreach (var statement in inlineMethodContext.StatementsToInsertBeforeInvocationOfCallee) { // Add a CarriageReturn to make sure for VB the statement would be in different line. callerNodeEditor.InsertBefore(statementContainsInvocation, statement.WithAppendedTrailingTrivia(_syntaxFacts.ElasticCarriageReturnLineFeed)); } } var (nodeToReplace, inlineNode) = GetInlineNode( calleeInvocationNode, calleeMethodSymbol, statementContainsInvocation, rawInlineExpression, methodParametersInfo, inlineMethodContext, semanticModel, syntaxGenerator, cancellationToken); callerNodeEditor.ReplaceNode(nodeToReplace, (node, generator) => inlineNode); return callerNodeEditor.GetChangedRoot(); } private (SyntaxNode nodeToReplace, SyntaxNode inlineNode) GetInlineNode( TInvocationSyntax calleeInvocationNode, IMethodSymbol calleeMethodSymbol, TStatementSyntax? statementContainsInvocation, TExpressionSyntax rawInlineExpression, MethodParametersInfo methodParametersInfo, InlineMethodContext inlineMethodContext, SemanticModel semanticModel, SyntaxGenerator syntaxGenerator, CancellationToken cancellationToken) { if (statementContainsInvocation != null) { if (methodParametersInfo.MergeInlineContentAndVariableDeclarationArgument) { var rightHandSideValue = _syntaxFacts.GetRightHandSideOfAssignment(inlineMethodContext.InlineExpression); var (parameterSymbol, name) = methodParametersInfo.ParametersWithVariableDeclarationArgument.Single(); var declarationNode = (TStatementSyntax)syntaxGenerator .LocalDeclarationStatement(parameterSymbol.Type, name, rightHandSideValue); return (statementContainsInvocation, declarationNode.WithTriviaFrom(statementContainsInvocation)); } if (_syntaxFacts.IsThrowStatement(rawInlineExpression.Parent) && _syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent)) { var throwStatement = (TStatementSyntax)syntaxGenerator .ThrowStatement(inlineMethodContext.InlineExpression); return (statementContainsInvocation, throwStatement.WithTriviaFrom(statementContainsInvocation)); } if (_syntaxFacts.IsThrowExpression(rawInlineExpression) && _syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent)) { // Example: // Before: // void Caller() { Callee(); } // void Callee() => throw new Exception(); // After: // void Caller() { throw new Exception(); } // void Callee() => throw new Exception(); // Note: Throw expression is converted to throw statement var throwStatement = (TStatementSyntax)syntaxGenerator .ThrowStatement(_syntaxFacts.GetExpressionOfThrowExpression(inlineMethodContext.InlineExpression)); return (statementContainsInvocation, throwStatement.WithTriviaFrom(statementContainsInvocation)); } if (_syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent) && !calleeMethodSymbol.ReturnsVoid && !IsValidExpressionUnderExpressionStatement(inlineMethodContext.InlineExpression)) { // If the callee is invoked as ExpressionStatement, but the inlined expression in the callee can't be // placed under ExpressionStatement // Example: // void Caller() // { // Callee(); // } // int Callee() // { // return 1; // }; // After it should be: // void Caller() // { // int temp = 1; // } // int Callee() // { // return 1; // }; // One variable declaration needs to be generated. var unusedLocalName = _semanticFactsService.GenerateUniqueLocalName( semanticModel, calleeInvocationNode, containerOpt: null, TemporaryName, cancellationToken); var localDeclarationNode = (TStatementSyntax)syntaxGenerator .LocalDeclarationStatement(calleeMethodSymbol.ReturnType, unusedLocalName.Text, inlineMethodContext.InlineExpression); return (statementContainsInvocation, localDeclarationNode.WithTriviaFrom(statementContainsInvocation)); } } if (_syntaxFacts.IsThrowStatement(rawInlineExpression.Parent)) { // Example: // Before: // void Caller() => Callee(); // void Callee() { throw new Exception(); } // After: // void Caller() => throw new Exception(); // void Callee() { throw new Exception(); } // Note: Throw statement is converted to throw expression if (CanBeReplacedByThrowExpression(calleeInvocationNode)) { var throwExpression = (TExpressionSyntax)syntaxGenerator .ThrowExpression(inlineMethodContext.InlineExpression) .WithTriviaFrom(calleeInvocationNode); return (calleeInvocationNode, throwExpression.WithTriviaFrom(calleeInvocationNode)); } } var inlineExpression = inlineMethodContext.InlineExpression; if (!_syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent) && !calleeMethodSymbol.ReturnsVoid && !_syntaxFacts.IsThrowExpression(inlineMethodContext.InlineExpression)) { // Add type cast and parenthesis to the inline expression. // It is required to cover cases like: // Case 1 (parenthesis added): // Before: // void Caller() { var x = 3 * Callee(); } // int Callee() { return 1 + 2; } // // After // void Caller() { var x = 3 * (1 + 2); } // int Callee() { return 1 + 2; } // // Case 2 (type cast) // Before: // void Caller() { var x = Callee(); } // long Callee() { return 1 } // // After // void Caller() { var x = (long)1; } // int Callee() { return 1; } // // Case 3 (type cast & additional parenthesis) // Before: // void Caller() { var x = Callee()(); } // Func<int> Callee() { return () => 1; } // After: // void Caller() { var x = ((Func<int>)(() => 1))(); } // Func<int> Callee() { return () => 1; } inlineExpression = (TExpressionSyntax)syntaxGenerator.AddParentheses( syntaxGenerator.CastExpression( GenerateTypeSyntax(calleeMethodSymbol.ReturnType, allowVar: false), syntaxGenerator.AddParentheses(inlineMethodContext.InlineExpression))); } return (calleeInvocationNode, inlineExpression.WithTriviaFrom(calleeInvocationNode)); } private ISymbol? GetCallerSymbol( TInvocationSyntax calleeMethodInvocationNode, SemanticModel semanticModel, CancellationToken cancellationToken) { for (SyntaxNode? node = calleeMethodInvocationNode; node != null; node = node.Parent) { var declaredSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (declaredSymbol.IsKind(SymbolKind.Property) || declaredSymbol.IsKind(SymbolKind.Method) || declaredSymbol.IsKind(SymbolKind.Event)) { return declaredSymbol; } if (IsFieldDeclarationSyntax(node) && semanticModel.GetExistingSymbols(node, cancellationToken).SingleOrDefault() is IFieldSymbol fieldSymbol) { return fieldSymbol; } if (_syntaxFacts.IsAnonymousFunction(node)) { return semanticModel.GetSymbolInfo(node, cancellationToken).Symbol; } } return null; } private class MySolutionChangeAction : CodeAction.SolutionChangeAction { public MySolutionChangeAction( string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.InlineMethod { internal abstract partial class AbstractInlineMethodRefactoringProvider< TMethodDeclarationSyntax, TStatementSyntax, TExpressionSyntax, TInvocationSyntax> : CodeRefactoringProvider where TMethodDeclarationSyntax : SyntaxNode where TStatementSyntax : SyntaxNode where TExpressionSyntax : SyntaxNode where TInvocationSyntax : TExpressionSyntax { /// <summary> /// A preferred name used to generated a declaration when the /// inline method's body is not a valid expresion in ExpressionStatement /// Example: /// void Caller() /// { /// Callee(); /// } /// int Callee() /// { /// return 1; /// }; /// After it should be: /// void Caller() /// { /// int temp = 1; /// } /// int Callee() /// { /// return 1; /// }; /// '1' is not a valid expression in ExpressionStatement so a declaration is needed to be generated. /// </summary> private const string TemporaryName = "temp"; private readonly ISyntaxFacts _syntaxFacts; private readonly ISemanticFactsService _semanticFactsService; protected abstract TExpressionSyntax? GetRawInlineExpression(TMethodDeclarationSyntax calleeMethodDeclarationSyntaxNode); protected abstract SyntaxNode GenerateTypeSyntax(ITypeSymbol symbol, bool allowVar); protected abstract TExpressionSyntax GenerateLiteralExpression(ITypeSymbol typeSymbol, object? value); protected abstract bool IsFieldDeclarationSyntax(SyntaxNode node); /// <summary> /// Check if <paramref name="expressionNode"/> could be used as an Expression in ExpressionStatement /// </summary> protected abstract bool IsValidExpressionUnderExpressionStatement(TExpressionSyntax expressionNode); /// <summary> /// Check if <paramref name="syntaxNode"/> could be replaced by ThrowExpression. /// For VB it always return false because ThrowExpression doesn't exist. /// </summary> protected abstract bool CanBeReplacedByThrowExpression(SyntaxNode syntaxNode); protected AbstractInlineMethodRefactoringProvider( ISyntaxFacts syntaxFacts, ISemanticFactsService semanticFactsService) { _syntaxFacts = syntaxFacts; _semanticFactsService = semanticFactsService; } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, _, cancellationToken) = context; var calleeInvocationNode = await context.TryGetRelevantNodeAsync<TInvocationSyntax>().ConfigureAwait(false); if (calleeInvocationNode == null) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var calleeMethodSymbol = semanticModel.GetSymbolInfo(calleeInvocationNode, cancellationToken).GetAnySymbol() as IMethodSymbol; if (calleeMethodSymbol == null) { return; } if (calleeMethodSymbol.PartialImplementationPart != null) { calleeMethodSymbol = calleeMethodSymbol.PartialImplementationPart; } if (!calleeMethodSymbol.IsOrdinaryMethod() && !calleeMethodSymbol.IsExtensionMethod) { return; } if (calleeMethodSymbol.IsVararg) { return; } if (calleeMethodSymbol.DeclaredAccessibility != Accessibility.Private) { return; } var symbolDeclarationService = document.GetRequiredLanguageService<ISymbolDeclarationService>(); var calleeMethodDeclarationSyntaxReferences = symbolDeclarationService.GetDeclarations(calleeMethodSymbol); if (calleeMethodDeclarationSyntaxReferences.Length != 1) { return; } var calleeMethodDeclarationSyntaxReference = calleeMethodDeclarationSyntaxReferences[0]; var calleeMethodNode = await calleeMethodDeclarationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false) as TMethodDeclarationSyntax; if (calleeMethodNode == null) { return; } var inlineExpression = GetRawInlineExpression(calleeMethodNode); // Special case 1: AwaitExpression if (_syntaxFacts.IsAwaitExpression(inlineExpression)) { // 1. If Caller & callee both have 'await' make sure there is no duplicate 'await' // Example: // Before: // async Task Caller() => await Callee(); // async Task Callee() => await Task.CompletedTask; // After: // async Task Caller() => await Task.CompletedTask; // async Task Callee() => await Task.CompletedTask; // The original inline expression in callee will be 'await Task.CompletedTask' // The caller just need 'Task.CompletedTask' without the 'await' // // 2. If Caller doesn't have await but callee has. // Example: // Before: // void Caller() { Callee().Wait();} // async Task Callee() => await DoAsync(); // After: // void Caller() { DoAsync().Wait(); } // async Task Callee() => await DoAsync(); // What caller is expecting is an expression returns 'Task', which doesn't include the 'await' inlineExpression = _syntaxFacts.GetExpressionOfAwaitExpression(inlineExpression) as TExpressionSyntax; } if (inlineExpression == null) { return; } // Special case 2: ThrowStatement & ThrowExpresion if (_syntaxFacts.IsThrowStatement(inlineExpression.Parent) || _syntaxFacts.IsThrowExpression(inlineExpression)) { // If this is a throw statement, then it should be valid for // 1. If it is invoked as ExpressionStatement // Example: // Before: // void Caller() { Callee(); } // void Callee() { throw new Exception();} // After: // void Caller() { throw new Exception(); } // void Callee() { throw new Exception();} // 2. If it is invoked in a place allow throw expression // Example: // Before: // void Caller(bool flag) { var x = flag ? Callee() : 1; } // int Callee() { throw new Exception();} // After: // void Caller() { var x = flag ? throw new Exception() : 1; } // int Callee() { throw new Exception();} // Note here throw statement is changed to throw expression after inlining // If this is a throw expression, the check is the same // 1. If it is invoked as ExpressionStatement // Example: // Before: // void Caller() { Callee(); } // void Callee() => throw new Exception(); // After: // void Caller() { throw new Exception(); } // void Callee() => throw new Exception(); // Note here throw expression is converted to throw statement // 2. If it is invoked in a place allow throw expression // Example: // Before: // void Caller(bool flag) { var x = flag ? Callee() : 1; } // int Callee() => throw new Exception(); // After: // void Caller() { var x = flag ? throw new Exception() : 1; } // int Callee() => throw new Exception(); if (!CanBeReplacedByThrowExpression(calleeInvocationNode) && !_syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent)) { return; } } var callerSymbol = GetCallerSymbol(calleeInvocationNode, semanticModel, cancellationToken); if (callerSymbol == null) { return; } var callerReferences = symbolDeclarationService.GetDeclarations(callerSymbol); if (callerReferences.Length != 1) { return; } var callerDeclarationNode = await callerReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); var invocationOperation = semanticModel.GetOperation(calleeInvocationNode, cancellationToken) as IInvocationOperation; if (invocationOperation == null) { return; } var codeActions = GenerateCodeActions( document, calleeInvocationNode, calleeMethodSymbol, calleeMethodNode, callerSymbol, callerDeclarationNode, inlineExpression, invocationOperation); var nestedCodeAction = new CodeAction.CodeActionWithNestedActions( string.Format(FeaturesResources.Inline_0, calleeMethodSymbol.ToNameDisplayString()), codeActions, isInlinable: true); context.RegisterRefactoring(nestedCodeAction, calleeInvocationNode.Span); } private ImmutableArray<CodeAction> GenerateCodeActions(Document document, TInvocationSyntax calleeMethodInvocationNode, IMethodSymbol calleeMethodSymbol, TMethodDeclarationSyntax calleeMethodNode, ISymbol callerSymbol, SyntaxNode callerMethodNode, TExpressionSyntax inlineExpression, IInvocationOperation invocationOperation) { var calleeMethodName = calleeMethodSymbol.ToNameDisplayString(); var codeActionRemovesCallee = new MySolutionChangeAction( string.Format(FeaturesResources.Inline_0, calleeMethodName), cancellationToken => InlineMethodAsync( document, calleeMethodInvocationNode, calleeMethodSymbol, calleeMethodNode, callerSymbol, callerMethodNode, inlineExpression, invocationOperation, removeCalleeDeclarationNode: true, cancellationToken: cancellationToken)); var codeActionKeepsCallee = new MySolutionChangeAction( string.Format(FeaturesResources.Inline_and_keep_0, calleeMethodName), cancellationToken => InlineMethodAsync( document, calleeMethodInvocationNode, calleeMethodSymbol, calleeMethodNode, callerSymbol, callerMethodNode, inlineExpression, invocationOperation, removeCalleeDeclarationNode: false, cancellationToken: cancellationToken)); return ImmutableArray.Create<CodeAction>(codeActionRemovesCallee, codeActionKeepsCallee); } private async Task<Solution> InlineMethodAsync(Document document, TInvocationSyntax calleeInvocationNode, IMethodSymbol calleeMethodSymbol, TMethodDeclarationSyntax calleeMethodNode, ISymbol callerSymbol, SyntaxNode callerNode, TExpressionSyntax rawInlineExpression, IInvocationOperation invocationOperation, bool removeCalleeDeclarationNode, CancellationToken cancellationToken) { // Find the statement contains the invocation. This should happen when Callee is invoked in a block // example: // void Caller() // { // Action a = () => // { // var x = Callee(); // } // } (Local declaration x is the containing node) // Note: Stop the searching when it hits lambda or local function, because for this case below don't // treat the declaration of a is the containing node // void Caller() // { // Action a = () => Callee(); // } // it could be null if the caller is invoked as arrow function var statementContainsInvocation = calleeInvocationNode.GetAncestors() .TakeWhile(node => !_syntaxFacts.IsAnonymousFunction(node) && !_syntaxFacts.IsLocalFunction(node)) .FirstOrDefault(node => node is TStatementSyntax) as TStatementSyntax; var methodParametersInfo = await GetMethodParametersInfoAsync( document, calleeInvocationNode, calleeMethodNode, statementContainsInvocation, rawInlineExpression, invocationOperation, cancellationToken).ConfigureAwait(false); var inlineContext = await GetInlineMethodContextAsync( document, calleeMethodNode, calleeInvocationNode, calleeMethodSymbol, rawInlineExpression, methodParametersInfo, cancellationToken).ConfigureAwait(false); var solution = document.Project.Solution; var solutionEditor = new SolutionEditor(solution); if (removeCalleeDeclarationNode) { var calleeDocumentId = solution.GetDocumentId(calleeMethodNode.SyntaxTree); if (calleeDocumentId != null) { var calleeDocumentEditor = await solutionEditor.GetDocumentEditorAsync(calleeDocumentId, cancellationToken).ConfigureAwait(false); calleeDocumentEditor.RemoveNode(calleeMethodNode); } } var newCallerMethodNode = await GetChangedCallerAsync( document, calleeInvocationNode, calleeMethodSymbol, callerSymbol, callerNode, statementContainsInvocation, rawInlineExpression, methodParametersInfo, inlineContext, cancellationToken).ConfigureAwait(false); var callerDocumentEditor = await solutionEditor.GetDocumentEditorAsync(document.Id, cancellationToken).ConfigureAwait(false); callerDocumentEditor.ReplaceNode(callerNode, newCallerMethodNode); return solutionEditor.GetChangedSolution(); } private async Task<SyntaxNode> GetChangedCallerAsync(Document document, TInvocationSyntax calleeInvocationNode, IMethodSymbol calleeMethodSymbol, ISymbol callerSymbol, SyntaxNode callerDeclarationNode, TStatementSyntax? statementContainsInvocation, TExpressionSyntax rawInlineExpression, MethodParametersInfo methodParametersInfo, InlineMethodContext inlineMethodContext, CancellationToken cancellationToken) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); var callerNodeEditor = new SyntaxEditor(callerDeclarationNode, syntaxGenerator); if (inlineMethodContext.ContainsAwaitExpression) { // If the inline content has 'await' expression, then make sure the caller is changed to 'async' method // if its return type is awaitable. In all other cases, do nothing. if (callerSymbol is IMethodSymbol callerMethodSymbol && callerMethodSymbol.IsOrdinaryMethod() && !callerMethodSymbol.IsAsync && (callerMethodSymbol.ReturnsVoid || callerMethodSymbol.IsAwaitableNonDynamic(semanticModel, callerDeclarationNode.SpanStart))) { var declarationModifiers = DeclarationModifiers.From(callerSymbol).WithAsync(true); callerNodeEditor.SetModifiers(callerDeclarationNode, declarationModifiers); } } if (statementContainsInvocation != null) { foreach (var statement in inlineMethodContext.StatementsToInsertBeforeInvocationOfCallee) { // Add a CarriageReturn to make sure for VB the statement would be in different line. callerNodeEditor.InsertBefore(statementContainsInvocation, statement.WithAppendedTrailingTrivia(_syntaxFacts.ElasticCarriageReturnLineFeed)); } } var (nodeToReplace, inlineNode) = GetInlineNode( calleeInvocationNode, calleeMethodSymbol, statementContainsInvocation, rawInlineExpression, methodParametersInfo, inlineMethodContext, semanticModel, syntaxGenerator, cancellationToken); callerNodeEditor.ReplaceNode(nodeToReplace, (node, generator) => inlineNode); return callerNodeEditor.GetChangedRoot(); } private (SyntaxNode nodeToReplace, SyntaxNode inlineNode) GetInlineNode( TInvocationSyntax calleeInvocationNode, IMethodSymbol calleeMethodSymbol, TStatementSyntax? statementContainsInvocation, TExpressionSyntax rawInlineExpression, MethodParametersInfo methodParametersInfo, InlineMethodContext inlineMethodContext, SemanticModel semanticModel, SyntaxGenerator syntaxGenerator, CancellationToken cancellationToken) { if (statementContainsInvocation != null) { if (methodParametersInfo.MergeInlineContentAndVariableDeclarationArgument) { var rightHandSideValue = _syntaxFacts.GetRightHandSideOfAssignment(inlineMethodContext.InlineExpression); var (parameterSymbol, name) = methodParametersInfo.ParametersWithVariableDeclarationArgument.Single(); var declarationNode = (TStatementSyntax)syntaxGenerator .LocalDeclarationStatement(parameterSymbol.Type, name, rightHandSideValue); return (statementContainsInvocation, declarationNode.WithTriviaFrom(statementContainsInvocation)); } if (_syntaxFacts.IsThrowStatement(rawInlineExpression.Parent) && _syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent)) { var throwStatement = (TStatementSyntax)syntaxGenerator .ThrowStatement(inlineMethodContext.InlineExpression); return (statementContainsInvocation, throwStatement.WithTriviaFrom(statementContainsInvocation)); } if (_syntaxFacts.IsThrowExpression(rawInlineExpression) && _syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent)) { // Example: // Before: // void Caller() { Callee(); } // void Callee() => throw new Exception(); // After: // void Caller() { throw new Exception(); } // void Callee() => throw new Exception(); // Note: Throw expression is converted to throw statement var throwStatement = (TStatementSyntax)syntaxGenerator .ThrowStatement(_syntaxFacts.GetExpressionOfThrowExpression(inlineMethodContext.InlineExpression)); return (statementContainsInvocation, throwStatement.WithTriviaFrom(statementContainsInvocation)); } if (_syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent) && !calleeMethodSymbol.ReturnsVoid && !IsValidExpressionUnderExpressionStatement(inlineMethodContext.InlineExpression)) { // If the callee is invoked as ExpressionStatement, but the inlined expression in the callee can't be // placed under ExpressionStatement // Example: // void Caller() // { // Callee(); // } // int Callee() // { // return 1; // }; // After it should be: // void Caller() // { // int temp = 1; // } // int Callee() // { // return 1; // }; // One variable declaration needs to be generated. var unusedLocalName = _semanticFactsService.GenerateUniqueLocalName( semanticModel, calleeInvocationNode, containerOpt: null, TemporaryName, cancellationToken); var localDeclarationNode = (TStatementSyntax)syntaxGenerator .LocalDeclarationStatement(calleeMethodSymbol.ReturnType, unusedLocalName.Text, inlineMethodContext.InlineExpression); return (statementContainsInvocation, localDeclarationNode.WithTriviaFrom(statementContainsInvocation)); } } if (_syntaxFacts.IsThrowStatement(rawInlineExpression.Parent)) { // Example: // Before: // void Caller() => Callee(); // void Callee() { throw new Exception(); } // After: // void Caller() => throw new Exception(); // void Callee() { throw new Exception(); } // Note: Throw statement is converted to throw expression if (CanBeReplacedByThrowExpression(calleeInvocationNode)) { var throwExpression = (TExpressionSyntax)syntaxGenerator .ThrowExpression(inlineMethodContext.InlineExpression) .WithTriviaFrom(calleeInvocationNode); return (calleeInvocationNode, throwExpression.WithTriviaFrom(calleeInvocationNode)); } } var inlineExpression = inlineMethodContext.InlineExpression; if (!_syntaxFacts.IsExpressionStatement(calleeInvocationNode.Parent) && !calleeMethodSymbol.ReturnsVoid && !_syntaxFacts.IsThrowExpression(inlineMethodContext.InlineExpression)) { // Add type cast and parenthesis to the inline expression. // It is required to cover cases like: // Case 1 (parenthesis added): // Before: // void Caller() { var x = 3 * Callee(); } // int Callee() { return 1 + 2; } // // After // void Caller() { var x = 3 * (1 + 2); } // int Callee() { return 1 + 2; } // // Case 2 (type cast) // Before: // void Caller() { var x = Callee(); } // long Callee() { return 1 } // // After // void Caller() { var x = (long)1; } // int Callee() { return 1; } // // Case 3 (type cast & additional parenthesis) // Before: // void Caller() { var x = Callee()(); } // Func<int> Callee() { return () => 1; } // After: // void Caller() { var x = ((Func<int>)(() => 1))(); } // Func<int> Callee() { return () => 1; } inlineExpression = (TExpressionSyntax)syntaxGenerator.AddParentheses( syntaxGenerator.CastExpression( GenerateTypeSyntax(calleeMethodSymbol.ReturnType, allowVar: false), syntaxGenerator.AddParentheses(inlineMethodContext.InlineExpression))); } return (calleeInvocationNode, inlineExpression.WithTriviaFrom(calleeInvocationNode)); } private ISymbol? GetCallerSymbol( TInvocationSyntax calleeMethodInvocationNode, SemanticModel semanticModel, CancellationToken cancellationToken) { for (SyntaxNode? node = calleeMethodInvocationNode; node != null; node = node.Parent) { var declaredSymbol = semanticModel.GetDeclaredSymbol(node, cancellationToken); if (declaredSymbol.IsKind(SymbolKind.Property) || declaredSymbol.IsKind(SymbolKind.Method) || declaredSymbol.IsKind(SymbolKind.Event)) { return declaredSymbol; } if (IsFieldDeclarationSyntax(node) && semanticModel.GetExistingSymbols(node, cancellationToken).SingleOrDefault() is IFieldSymbol fieldSymbol) { return fieldSymbol; } if (_syntaxFacts.IsAnonymousFunction(node)) { return semanticModel.GetSymbolInfo(node, cancellationToken).Symbol; } } return null; } private class MySolutionChangeAction : CodeAction.SolutionChangeAction { public MySolutionChangeAction( string title, Func<CancellationToken, Task<Solution>> createChangedSolution) : base(title, createChangedSolution, title) { } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/DocumentationComments/DocumentationCommentSnippet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal class DocumentationCommentSnippet { /// <summary> /// The span in the original text that should be replaced with the documentation comment. /// </summary> public TextSpan SpanToReplace { get; } /// <summary> /// The documentation comment text to replace the span with /// </summary> public string SnippetText { get; } /// <summary> /// The offset within <see cref="SnippetText"/> where the caret should be positioned after replacement /// </summary> public int CaretOffset { get; } internal DocumentationCommentSnippet(TextSpan spanToReplace, string snippetText, int caretOffset) { SpanToReplace = spanToReplace; SnippetText = snippetText; CaretOffset = caretOffset; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.DocumentationComments { internal class DocumentationCommentSnippet { /// <summary> /// The span in the original text that should be replaced with the documentation comment. /// </summary> public TextSpan SpanToReplace { get; } /// <summary> /// The documentation comment text to replace the span with /// </summary> public string SnippetText { get; } /// <summary> /// The offset within <see cref="SnippetText"/> where the caret should be positioned after replacement /// </summary> public int CaretOffset { get; } internal DocumentationCommentSnippet(TextSpan spanToReplace, string snippetText, int caretOffset) { SpanToReplace = spanToReplace; SnippetText = snippetText; CaretOffset = caretOffset; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/VisualBasicUseObjectInitializerCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.UseObjectInitializer Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseObjectInitializer), [Shared]> Friend Class VisualBasicUseObjectInitializerCodeFixProvider Inherits AbstractUseObjectInitializerCodeFixProvider(Of SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax, VariableDeclaratorSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetNewStatement( statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As StatementSyntax Dim newStatement = statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)) Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance() totalTrivia.AddRange(statement.GetLeadingTrivia()) totalTrivia.Add(SyntaxFactory.ElasticMarker) For Each match In matches For Each trivia In match.Statement.GetLeadingTrivia() If trivia.Kind = SyntaxKind.CommentTrivia Then totalTrivia.Add(trivia) totalTrivia.Add(SyntaxFactory.ElasticMarker) End If Next Next Return newStatement.WithLeadingTrivia(totalTrivia) End Function Private Shared Function GetNewObjectCreation( objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As ObjectCreationExpressionSyntax Return UseInitializerHelpers.GetNewObjectCreation( objectCreation, SyntaxFactory.ObjectMemberInitializer( CreateFieldInitializers(matches))) End Function Private Shared Function CreateFieldInitializers( matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As SeparatedSyntaxList(Of FieldInitializerSyntax) Dim nodesAndTokens = New List(Of SyntaxNodeOrToken) For i = 0 To matches.Length - 1 Dim match = matches(i) Dim rightValue = match.Initializer If i < matches.Length - 1 Then rightValue = rightValue.WithoutTrailingTrivia() End If Dim initializer = SyntaxFactory.NamedFieldInitializer( keyKeyword:=Nothing, dotToken:=match.MemberAccessExpression.OperatorToken, name:=SyntaxFactory.IdentifierName(match.MemberName), equalsToken:=match.Statement.OperatorToken, expression:=rightValue).WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) nodesAndTokens.Add(initializer) If i < matches.Length - 1 Then Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken). WithTrailingTrivia(match.Initializer.GetTrailingTrivia()) nodesAndTokens.Add(comma) End If Next Return SyntaxFactory.SeparatedList(Of FieldInitializerSyntax)(nodesAndTokens) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.UseObjectInitializer Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseObjectInitializer), [Shared]> Friend Class VisualBasicUseObjectInitializerCodeFixProvider Inherits AbstractUseObjectInitializerCodeFixProvider(Of SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax, VariableDeclaratorSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetNewStatement( statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As StatementSyntax Dim newStatement = statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)) Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance() totalTrivia.AddRange(statement.GetLeadingTrivia()) totalTrivia.Add(SyntaxFactory.ElasticMarker) For Each match In matches For Each trivia In match.Statement.GetLeadingTrivia() If trivia.Kind = SyntaxKind.CommentTrivia Then totalTrivia.Add(trivia) totalTrivia.Add(SyntaxFactory.ElasticMarker) End If Next Next Return newStatement.WithLeadingTrivia(totalTrivia) End Function Private Shared Function GetNewObjectCreation( objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As ObjectCreationExpressionSyntax Return UseInitializerHelpers.GetNewObjectCreation( objectCreation, SyntaxFactory.ObjectMemberInitializer( CreateFieldInitializers(matches))) End Function Private Shared Function CreateFieldInitializers( matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As SeparatedSyntaxList(Of FieldInitializerSyntax) Dim nodesAndTokens = New List(Of SyntaxNodeOrToken) For i = 0 To matches.Length - 1 Dim match = matches(i) Dim rightValue = match.Initializer If i < matches.Length - 1 Then rightValue = rightValue.WithoutTrailingTrivia() End If Dim initializer = SyntaxFactory.NamedFieldInitializer( keyKeyword:=Nothing, dotToken:=match.MemberAccessExpression.OperatorToken, name:=SyntaxFactory.IdentifierName(match.MemberName), equalsToken:=match.Statement.OperatorToken, expression:=rightValue).WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) nodesAndTokens.Add(initializer) If i < matches.Length - 1 Then Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken). WithTrailingTrivia(match.Initializer.GetTrailingTrivia()) nodesAndTokens.Add(comma) End If Next Return SyntaxFactory.SeparatedList(Of FieldInitializerSyntax)(nodesAndTokens) End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Portable/Syntax/SyntaxNormalizer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Class SyntaxNormalizer Inherits VisualBasicSyntaxRewriter Private ReadOnly _consideredSpan As TextSpan Private ReadOnly _indentWhitespace As String Private ReadOnly _eolTrivia As SyntaxTrivia Private ReadOnly _useElasticTrivia As Boolean Private ReadOnly _useDefaultCasing As Boolean Private _isInStructuredTrivia As Boolean Private _previousToken As SyntaxToken Private _afterLineBreak As Boolean Private _afterIndentation As Boolean Private ReadOnly _lineBreaksAfterToken As Dictionary(Of SyntaxToken, Integer) = New Dictionary(Of SyntaxToken, Integer)() Private ReadOnly _lastStatementsInBlocks As HashSet(Of SyntaxNode) = New HashSet(Of SyntaxNode)() Private _indentationDepth As Integer Private _indentations As ArrayBuilder(Of SyntaxTrivia) ''' <summary> ''' Creates a syntax trivia normalizing visitor ''' </summary> ''' <param name="indentWhitespace">The whitespace to indent with</param> ''' <param name="eolWhitespace">The whitespace to use for end of line</param> ''' <param name="useElasticTrivia">Whether to use elastic trivia or not</param> ''' <param name="useDefaultCasing">Whether to rewrite keywords in default casing or not</param> ''' <remarks></remarks> Private Sub New(consideredSpan As TextSpan, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) MyBase.New(visitIntoStructuredTrivia:=True) Me._consideredSpan = consideredSpan Me._indentWhitespace = indentWhitespace Me._useElasticTrivia = useElasticTrivia Me._eolTrivia = If(useElasticTrivia, SyntaxFactory.ElasticEndOfLine(eolWhitespace), SyntaxFactory.EndOfLine(eolWhitespace)) Me._useDefaultCasing = useDefaultCasing Me._afterLineBreak = True End Sub Friend Shared Function Normalize(Of TNode As SyntaxNode)(node As TNode, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) As SyntaxNode Dim normalizer As New SyntaxNormalizer(node.FullSpan, indentWhitespace, eolWhitespace, useElasticTrivia, useDefaultCasing) Dim result As TNode = CType(normalizer.Visit(node), TNode) normalizer.Free() Return result End Function Friend Shared Function Normalize(token As SyntaxToken, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) As SyntaxToken Dim normalizer As New SyntaxNormalizer(token.FullSpan, indentWhitespace, eolWhitespace, useElasticTrivia, useDefaultCasing) Dim result As SyntaxToken = normalizer.VisitToken(token) normalizer.Free() Return result End Function Friend Shared Function Normalize(trivia As SyntaxTriviaList, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) As SyntaxTriviaList Dim normalizer = New SyntaxNormalizer(trivia.FullSpan, indentWhitespace, eolWhitespace, useElasticTrivia, useDefaultCasing) Dim result As SyntaxTriviaList = normalizer.RewriteTrivia(trivia, normalizer.GetIndentationDepth(), isTrailing:=False, mustBeIndented:=False, mustHaveSeparator:=False, lineBreaksAfter:=0, lineBreaksBefore:=0) normalizer.Free() Return result End Function Private Sub Free() If _indentations IsNot Nothing Then _indentations.Free() End If End Sub Private Function GetIndentation(count As Integer) As SyntaxTrivia Dim capacity = count + 1 If _indentations Is Nothing Then _indentations = ArrayBuilder(Of SyntaxTrivia).GetInstance(capacity) Else _indentations.EnsureCapacity(capacity) End If For i As Integer = _indentations.Count To count Dim text As String = If(i = 0, "", _indentations(i - 1).ToString() + Me._indentWhitespace) _indentations.Add(If(Me._useElasticTrivia, SyntaxFactory.ElasticWhitespace(text), SyntaxFactory.Whitespace(text))) Next Return _indentations(count) End Function ' use leadingTrivia as indentation ' use trailingTrivia as separation & newlines if needed Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken ' ignore tokens with no content If token.Kind = SyntaxKind.None Then Return token End If Try Dim newToken As SyntaxToken If _useDefaultCasing AndAlso token.IsKeyword() Then newToken = SyntaxFactory.Token(token.Kind) Else newToken = token End If Dim indentationDepth = GetIndentationDepth() ' check if this token is first on this line Dim numLineBreaksBefore As Integer = LineBreaksBetween(_previousToken, token) Dim needsIndentation As Boolean = (numLineBreaksBefore > 0) ' all line breaks except the first will be leading trivia of this token. The first line break ' is trailing trivia of the previous token. If numLineBreaksBefore > 0 AndAlso IsLastTokenOnLine(_previousToken) Then numLineBreaksBefore -= 1 End If newToken = newToken.WithLeadingTrivia( RewriteTrivia( token.LeadingTrivia, indentationDepth, isTrailing:=False, mustBeIndented:=needsIndentation, mustHaveSeparator:=False, lineBreaksAfter:=0, lineBreaksBefore:=numLineBreaksBefore)) Dim nextToken As SyntaxToken = GetNextRelevantToken(token) Me._afterIndentation = False ' we only add one of the line breaks to trivia of this token. The remaining ones will be leading trivia ' for the next token Dim numLineBreaksAfter As Integer = If(LineBreaksBetween(token, nextToken) > 0, 1, 0) Dim needsSeparatorAfter = If(numLineBreaksAfter > 0, False, NeedsSeparator(token, nextToken)) newToken = newToken.WithTrailingTrivia( RewriteTrivia( token.TrailingTrivia, depth:=0, isTrailing:=True, mustBeIndented:=False, mustHaveSeparator:=needsSeparatorAfter, lineBreaksAfter:=numLineBreaksAfter, lineBreaksBefore:=0)) If newToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken Then _afterLineBreak = True ElseIf newToken.Kind = SyntaxKind.XmlTextLiteralToken Then If newToken.TrailingTrivia.Count = 0 AndAlso IsNewLineChar(newToken.ValueText.Last) Then _afterLineBreak = True End If End If Return newToken Finally Me._previousToken = token End Try Return token End Function Private Function RewriteTrivia( triviaList As SyntaxTriviaList, depth As Integer, isTrailing As Boolean, mustBeIndented As Boolean, mustHaveSeparator As Boolean, lineBreaksAfter As Integer, lineBreaksBefore As Integer) As SyntaxTriviaList Dim currentTriviaList As ArrayBuilder(Of SyntaxTrivia) = ArrayBuilder(Of SyntaxTrivia).GetInstance() Try For i = 1 To lineBreaksBefore currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False Next For Each trivia In triviaList ' just keep non whitespace trivia If trivia.Kind = SyntaxKind.WhitespaceTrivia OrElse trivia.Kind = SyntaxKind.EndOfLineTrivia OrElse trivia.Kind = SyntaxKind.LineContinuationTrivia OrElse trivia.FullWidth = 0 Then Continue For End If ' check if there's a separator or a line break needed between the trivia itself Dim tokenParent = trivia.Token.Parent Dim needsSeparator As Boolean = Not (trivia.Kind = SyntaxKind.ColonTrivia AndAlso tokenParent IsNot Nothing AndAlso tokenParent.Kind = SyntaxKind.LabelStatement) AndAlso Not (tokenParent IsNot Nothing AndAlso tokenParent.Parent IsNot Nothing AndAlso tokenParent.Parent.Kind = SyntaxKind.CrefReference) AndAlso ( (currentTriviaList.Count > 0 AndAlso NeedsSeparatorBetween(currentTriviaList.Last()) AndAlso Not EndsInLineBreak(currentTriviaList.Last())) OrElse (currentTriviaList.Count = 0 AndAlso isTrailing) ) Dim needsLineBreak As Boolean = NeedsLineBreakBefore(trivia) OrElse (currentTriviaList.Count > 0 AndAlso NeedsLineBreakBetween(currentTriviaList.Last(), trivia, isTrailing)) If needsLineBreak AndAlso Not _afterLineBreak Then currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False End If If _afterLineBreak And Not isTrailing Then If Not _afterIndentation AndAlso Me.NeedsIndentAfterLineBreak(trivia) Then currentTriviaList.Add(Me.GetIndentation(GetIndentationDepth(trivia))) _afterIndentation = True End If ElseIf needsSeparator Then currentTriviaList.Add(GetSpace()) _afterLineBreak = False _afterIndentation = False End If If trivia.HasStructure Then Dim structuredTrivia As SyntaxTrivia = Me.VisitStructuredTrivia(trivia) currentTriviaList.Add(structuredTrivia) Else ' in structured trivia, the xml doc ''' token contains leading whitespace as text If trivia.Kind = SyntaxKind.DocumentationCommentExteriorTrivia Then trivia = SyntaxFactory.DocumentationCommentExteriorTrivia(SyntaxFacts.GetText(SyntaxKind.DocumentationCommentExteriorTrivia)) End If currentTriviaList.Add(trivia) End If If NeedsLineBreakAfter(trivia) Then If Not isTrailing Then currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False End If Else _afterLineBreak = EndsInLineBreak(trivia) End If Next If lineBreaksAfter > 0 Then If currentTriviaList.Count > 0 AndAlso EndsInLineBreak(currentTriviaList.Last()) Then lineBreaksAfter = lineBreaksAfter - 1 End If For i = 0 To lineBreaksAfter - 1 currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False Next i ElseIf mustHaveSeparator Then currentTriviaList.Add(GetSpace()) _afterLineBreak = False _afterIndentation = False End If If mustBeIndented Then currentTriviaList.Add(Me.GetIndentation(depth)) _afterIndentation = True _afterLineBreak = False End If If currentTriviaList.Count = 0 Then If _useElasticTrivia Then Return SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker) Else Return Nothing End If ElseIf currentTriviaList.Count = 1 Then Return SyntaxFactory.TriviaList(currentTriviaList.First()) Else Return SyntaxFactory.TriviaList(currentTriviaList) End If Finally currentTriviaList.Free() End Try End Function Private Function IsLastTokenOnLine(token As SyntaxToken) As Boolean Return (token.HasTrailingTrivia AndAlso token.TrailingTrivia.Last.Kind = SyntaxKind.ColonTrivia) OrElse (token.Parent IsNot Nothing AndAlso token.Parent.GetLastToken() = token) End Function Private Function LineBreaksBetween(currentToken As SyntaxToken, nextToken As SyntaxToken) As Integer ' First and last token may be of kind none If currentToken.Kind = SyntaxKind.None OrElse nextToken.Kind = SyntaxKind.None Then Return 0 End If Dim numLineBreaks As Integer = 0 If _lineBreaksAfterToken.TryGetValue(currentToken, numLineBreaks) Then Return numLineBreaks End If Return 0 End Function ''' <summary> ''' indentation depth is the declaration depth for statements within the block. for start/end statements ''' of these blocks (e.g. the if statement), it is a level less ''' </summary> Private Function GetIndentationDepth() As Integer Debug.Assert(Me._indentationDepth >= 0) Return Me._indentationDepth End Function Private Function GetIndentationDepth(trivia As SyntaxTrivia) As Integer If SyntaxFacts.IsPreprocessorDirective(trivia.Kind) Then Return 0 End If Return GetIndentationDepth() End Function Private Function GetSpace() As SyntaxTrivia Return If(Me._useElasticTrivia, SyntaxFactory.ElasticSpace, SyntaxFactory.Space) End Function Private Function GetEndOfLine() As SyntaxTrivia Return _eolTrivia End Function Private Function NeedsSeparatorBetween(trivia As SyntaxTrivia) As Boolean Select Case trivia.Kind Case SyntaxKind.None, SyntaxKind.WhitespaceTrivia, SyntaxKind.DocumentationCommentExteriorTrivia, SyntaxKind.LineContinuationTrivia Return False Case Else Return Not SyntaxFacts.IsPreprocessorDirective(trivia.Kind) End Select End Function Private Function NeedsLineBreakBetween(trivia As SyntaxTrivia, nextTrivia As SyntaxTrivia, isTrailingTrivia As Boolean) As Boolean If EndsInLineBreak(trivia) Then Return False End If Select Case nextTrivia.Kind Case SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentExteriorTrivia, SyntaxKind.EmptyStatement, SyntaxKind.IfDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia, SyntaxKind.ElseDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia, SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.ConstDirectiveTrivia, SyntaxKind.ExternalSourceDirectiveTrivia, SyntaxKind.EndExternalSourceDirectiveTrivia, SyntaxKind.ExternalChecksumDirectiveTrivia, SyntaxKind.EnableWarningDirectiveTrivia, SyntaxKind.DisableWarningDirectiveTrivia, SyntaxKind.ReferenceDirectiveTrivia, SyntaxKind.BadDirectiveTrivia Return Not isTrailingTrivia Case Else Return False End Select End Function Private Function NeedsLineBreakAfter(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Private Function NeedsLineBreakBefore(trivia As SyntaxTrivia) As Boolean Select Case trivia.Kind Case SyntaxKind.DocumentationCommentExteriorTrivia Return True Case Else Return False End Select End Function Private Function NeedsIndentAfterLineBreak(trivia As SyntaxTrivia) As Boolean Select Case trivia.Kind Case SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentExteriorTrivia, SyntaxKind.DocumentationCommentTrivia Return True Case Else Return False End Select End Function Private Function NeedsSeparator(token As SyntaxToken, nextToken As SyntaxToken) As Boolean If token.Kind = SyntaxKind.EndOfFileToken Then Return False End If If token.Parent Is Nothing OrElse nextToken.Kind = SyntaxKind.None Then Return False End If If nextToken.Parent.Kind = SyntaxKind.SingleLineFunctionLambdaExpression Then Return True End If If nextToken.Kind = SyntaxKind.EndOfFileToken Then Return False End If ' +1 instead of + 1 ' but not a instead of nota ... If TypeOf (token.Parent) Is UnaryExpressionSyntax AndAlso token.Kind <> SyntaxKind.NotKeyword AndAlso token.Kind <> SyntaxKind.AddressOfKeyword Then Return False End If ' generally a + b, needs to go here to make it b + (a + b) instead of b +(a + b If TypeOf (token.Parent) Is BinaryExpressionSyntax OrElse TypeOf (nextToken.Parent) Is BinaryExpressionSyntax Then Return True End If ' (a instead of ( a If token.Kind = SyntaxKind.OpenParenToken Then Return False End If ' a) instead of a ) If nextToken.Kind = SyntaxKind.CloseParenToken Then Return False End If ' m( instead of m ( If token.Kind <> SyntaxKind.CommaToken AndAlso nextToken.Kind = SyntaxKind.OpenParenToken Then Return False End If ' (,,,) instead of ( , , ,) or (a As Char, b as Char) instead of (a As Char , b as Char) ' $"{e,1:C}" instead of $"{e,1:C}" If (token.Kind = SyntaxKind.CommaToken AndAlso (nextToken.Kind = SyntaxKind.EmptyToken OrElse token.Parent.Kind = SyntaxKind.InterpolationAlignmentClause)) OrElse nextToken.Kind = SyntaxKind.CommaToken Then Return False End If ' a.b and .b instead of a . b, but keep with {key .field} If token.Kind = SyntaxKind.DotToken Then Return False ElseIf nextToken.Kind = SyntaxKind.DotToken AndAlso nextToken.Parent.Kind <> SyntaxKind.NamedFieldInitializer Then Return False End If If nextToken.Kind = SyntaxKind.ColonToken Then If token.Parent.Kind = SyntaxKind.LabelStatement Then ' label: instead of label : Return False ElseIf nextToken.Parent.Kind = SyntaxKind.InterpolationFormatClause Then ' $"{e,1:C}" instead of $"{e,1 :C}" Return False End If End If ' {1 instead of { 1 and 1} instead of 1 } If token.Kind = SyntaxKind.OpenBraceToken OrElse nextToken.Kind = SyntaxKind.CloseBraceToken Then Return False End If ' s1(p1:=23, p2:=12) instead of s1(p1 := 23, p2 := 12) If token.Kind = SyntaxKind.ColonEqualsToken OrElse nextToken.Kind = SyntaxKind.ColonEqualsToken Then Return False End If ' case > 100 should keep separator ' need to test before xml analysis below If SyntaxFacts.IsRelationalCaseClause(token.Parent.Kind()) OrElse SyntaxFacts.IsRelationalCaseClause(nextToken.Parent.Kind()) Then Return True End If ' handle closing attribute before XML tokens ' sub goo(<obsolete()> ByRef i as Integer) instead of sub goo(<obsolete()>ByRef i as Integer) If (token.Kind = SyntaxKind.GreaterThanToken AndAlso token.Parent.Kind = SyntaxKind.AttributeList) Then Return True End If ' needs to be checked after binary operators ' Imports <goo instead of Imports < goo If (token.Kind = SyntaxKind.LessThanToken OrElse nextToken.Kind = SyntaxKind.GreaterThanToken OrElse token.Kind = SyntaxKind.LessThanSlashToken OrElse token.Kind = SyntaxKind.GreaterThanToken OrElse nextToken.Kind = SyntaxKind.LessThanSlashToken) Then Return False End If ' <xmlns:goo instead of <xmlns : goo If token.Kind = SyntaxKind.ColonToken AndAlso token.Parent.Kind = SyntaxKind.XmlPrefix OrElse nextToken.Kind = SyntaxKind.ColonToken AndAlso nextToken.Parent.Kind = SyntaxKind.XmlPrefix Then Return False End If ' <e/> instead of <e /> If nextToken.Kind = SyntaxKind.SlashGreaterThanToken Then Return False End If ' <!--a--> instead of <!-- a --> If token.Kind = SyntaxKind.LessThanExclamationMinusMinusToken OrElse nextToken.Kind = SyntaxKind.MinusMinusGreaterThanToken Then Return False End If ' <?xml ?> instead of <? xml ?> If token.Kind = SyntaxKind.LessThanQuestionToken Then Return False End If ' <![CDATA[goo]]> instead of <![CDATA[ goo ]]> If token.Kind = SyntaxKind.BeginCDataToken OrElse nextToken.Kind = SyntaxKind.EndCDataToken Then Return False End If ' <Assembly:System.Copyright("(C) 2009")> instead of <Assembly : System.Copyright("(C) 2009")> If token.Kind = SyntaxKind.ColonToken AndAlso token.Parent.Kind = SyntaxKind.AttributeTarget OrElse nextToken.Kind = SyntaxKind.ColonToken AndAlso nextToken.Parent.Kind = SyntaxKind.AttributeTarget Then Return False End If ' <goo="bar" instead of <goo = "bar" If (token.Kind = SyntaxKind.EqualsToken AndAlso (token.Parent.Kind = SyntaxKind.XmlAttribute OrElse token.Parent.Kind = SyntaxKind.XmlCrefAttribute OrElse token.Parent.Kind = SyntaxKind.XmlNameAttribute OrElse token.Parent.Kind = SyntaxKind.XmlDeclaration)) OrElse (nextToken.Kind = SyntaxKind.EqualsToken AndAlso (nextToken.Parent.Kind = SyntaxKind.XmlAttribute OrElse nextToken.Parent.Kind = SyntaxKind.XmlCrefAttribute OrElse nextToken.Parent.Kind = SyntaxKind.XmlNameAttribute OrElse nextToken.Parent.Kind = SyntaxKind.XmlDeclaration)) Then Return False End If ' needs to be below binary expression checks ' <attrib="goo" instead of <attrib=" goo " If token.Kind = SyntaxKind.DoubleQuoteToken OrElse nextToken.Kind = SyntaxKind.DoubleQuoteToken Then Return False End If ' <x/>@a instead of <x/>@ a If token.Kind = SyntaxKind.AtToken AndAlso token.Parent.Kind = SyntaxKind.XmlAttributeAccessExpression Then Return False End If ' 'e' instead of ' e ' If token.Kind = SyntaxKind.SingleQuoteToken OrElse nextToken.Kind = SyntaxKind.SingleQuoteToken Then Return False End If ' Integer? instead of Integer ? If nextToken.Kind = SyntaxKind.QuestionToken Then Return False End If ' #if instead of # if If token.Kind = SyntaxKind.HashToken AndAlso TypeOf token.Parent Is DirectiveTriviaSyntax Then Return False End If ' "#region" instead of "#region " If token.Parent.Kind = SyntaxKind.RegionDirectiveTrivia AndAlso nextToken.Kind = SyntaxKind.StringLiteralToken AndAlso String.IsNullOrEmpty(nextToken.ValueText) Then Return False End If If token.Kind = SyntaxKind.XmlTextLiteralToken OrElse token.Kind = SyntaxKind.DocumentationCommentLineBreakToken Then Return False End If If token.Kind = SyntaxKind.DollarSignDoubleQuoteToken Then Return False End If If token.Kind = SyntaxKind.InterpolatedStringTextToken OrElse nextToken.Kind = SyntaxKind.InterpolatedStringTextToken Then Return False End If Return True End Function Private Function EndsInLineBreak(trivia As SyntaxTrivia) As Boolean If trivia.Kind = SyntaxKind.EndOfLineTrivia Then Return True End If If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Dim text As String = trivia.ToFullString() Return text.Length > 0 AndAlso IsNewLineChar(text.Last()) End If If trivia.HasStructure Then If trivia.GetStructure.GetLastToken.HasTrailingTrivia AndAlso trivia.GetStructure.GetLastToken.TrailingTrivia.Last.Kind = SyntaxKind.EndOfLineTrivia Then Return True End If End If Return False End Function Private Shared Function IsNewLineChar(ch As Char) As Boolean ' new-line-character: ' Carriage return character (U+000D) ' Line feed character (U+000A) ' Next line character (U+0085) ' Line separator character (U+2028) ' Paragraph separator character (U+2029) Return ch = vbLf _ OrElse ch = vbCr _ OrElse ch = "\u0085" _ OrElse ch = "\u2028" _ OrElse ch = "\u2029" End Function Private Overloads Function VisitStructuredTrivia(trivia As SyntaxTrivia) As SyntaxTrivia Dim oldIsInStructuredTrivia As Boolean = Me._isInStructuredTrivia Me._isInStructuredTrivia = True Dim oldPreviousToken = Me._previousToken Me._previousToken = Nothing Dim result As SyntaxTrivia = VisitTrivia(trivia) Me._isInStructuredTrivia = oldIsInStructuredTrivia Me._previousToken = oldPreviousToken Return result End Function Private Function GetNextRelevantToken(token As SyntaxToken) As SyntaxToken Dim nextToken = token.GetNextToken(Function(t As SyntaxToken) Return t.Kind <> SyntaxKind.None End Function, Function(t As SyntaxTrivia) False) If _consideredSpan.Contains(nextToken.FullSpan) Then Return nextToken Else Return Nothing End If End Function Private Sub AddLinebreaksAfterElementsIfNeeded(Of TNode As SyntaxNode)( list As SyntaxList(Of TNode), linebreaksBetweenElements As Integer, linebreaksAfterLastElement As Integer ) Dim lastElementIndex = list.Count - 1 For elementIndex = 0 To lastElementIndex Dim listElement = list(elementIndex) If listElement.Kind = SyntaxKind.LabelStatement Then ' always add linebreaks after label _lineBreaksAfterToken(listElement.GetLastToken()) = 1 Else AddLinebreaksAfterTokenIfNeeded(listElement.GetLastToken(), If(elementIndex = lastElementIndex, linebreaksAfterLastElement, linebreaksBetweenElements)) End If Next End Sub Private Sub AddLinebreaksAfterTokenIfNeeded(node As SyntaxToken, linebreaksAfterToken As Integer) If Not EndsWithColonSeparator(node) Then Me._lineBreaksAfterToken(node) = linebreaksAfterToken End If End Sub Private Function EndsWithColonSeparator(node As SyntaxToken) As Boolean Return node.HasTrailingTrivia AndAlso node.TrailingTrivia.Last.Kind = SyntaxKind.ColonTrivia End Function Private Sub MarkLastStatementIfNeeded(Of TNode As SyntaxNode)(list As SyntaxList(Of TNode)) If list.Any Then _lastStatementsInBlocks.Add(list.Last) End If End Sub ''' <summary> ''' We each element of option, imports and attributes on a separate line, where the last element of this the list if ''' followed by an empty line: ''' Option Strict On ''' ''' Imports System ''' Imports Goo ''' ''' [...] ''' ''' Namespace ''' [...] ''' </summary> Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode Dim hasImports = node.Imports.Any Dim hasMembers = node.Members.Any Dim hasAttributes = node.Attributes.Any If hasImports OrElse hasAttributes OrElse hasMembers Then AddLinebreaksAfterElementsIfNeeded(node.Options, 1, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Options, 1, 1) End If If hasAttributes OrElse hasMembers Then AddLinebreaksAfterElementsIfNeeded(node.Imports, 1, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Imports, 1, 1) End If If hasMembers Then AddLinebreaksAfterElementsIfNeeded(node.Attributes, 1, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Attributes, 1, 1) End If AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 1) Return MyBase.VisitCompilationUnit(node) End Function ''' <summary> ''' Add an empty line after the begin, except the first member is a nested namespace. ''' Separate each member of a namespace with an empty line. ''' </summary> Public Overrides Function VisitNamespaceBlock(node As NamespaceBlockSyntax) As SyntaxNode If node.Members.Count > 0 Then ' Add an empty line after the namespace begin if there ' is not a namespace declaration as first member If node.Members(0).Kind <> SyntaxKind.NamespaceBlock Then AddLinebreaksAfterTokenIfNeeded(node.NamespaceStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.NamespaceStatement.GetLastToken(), 1) End If AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 1) Else AddLinebreaksAfterTokenIfNeeded(node.NamespaceStatement.GetLastToken(), 1) End If Return MyBase.VisitNamespaceBlock(node) End Function Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitModuleBlock(node) End Function Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitClassBlock(node) End Function Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitStructureBlock(node) End Function Public Overrides Function VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitInterfaceBlock(node) End Function ''' <summary> ''' We want to display type blocks (Modules, Classes, Structures and Interfaces) like follows ''' Class Goo ''' implements IBar1, IBar2 ''' implements IBar3 ''' inherits Bar1 ''' ''' Public Sub Boo() ''' End Sub ''' End Class ''' ''' or ''' ''' Class Goo ''' ''' Public Sub Boo() ''' End Sub ''' End Class ''' ''' Basically it's an empty line between implements and inherits and between each member. If there are no ''' inherits or implements, add an empty line before the first member. ''' </summary> Private Sub VisitTypeBlockSyntax(ByVal node As TypeBlockSyntax) Dim hasImplements As Boolean = node.Implements.Count > 0 Dim hasInherits As Boolean = node.Inherits.Count > 0 ' add a line break between begin statement and the ones from the statement list If Not hasInherits AndAlso Not hasImplements AndAlso node.Members.Count > 0 Then AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) End If If hasImplements Then AddLinebreaksAfterElementsIfNeeded(node.Inherits, 1, 1) Else AddLinebreaksAfterElementsIfNeeded(node.Inherits, 1, 2) End If AddLinebreaksAfterElementsIfNeeded(node.Implements, 1, 2) If node.Kind = SyntaxKind.InterfaceBlock Then AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 1) End If End Sub Public Overrides Function VisitMultiLineIfBlock(node As MultiLineIfBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.IfStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Dim previousNode As VisualBasicSyntaxNode If node.Statements.Any() Then previousNode = node.Statements.Last() Else previousNode = node.IfStatement End If For Each elseIfBlock In node.ElseIfBlocks AddLinebreaksAfterTokenIfNeeded(previousNode.GetLastToken(), 1) previousNode = elseIfBlock Next If node.ElseBlock IsNot Nothing Then AddLinebreaksAfterTokenIfNeeded(previousNode.GetLastToken(), 1) End If If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndIfStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndIfStatement.GetLastToken(), 1) End If Return MyBase.VisitMultiLineIfBlock(node) End Function Public Overrides Function VisitEventBlock(node As EventBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.EventStatement.GetLastToken, 1) AddLinebreaksAfterElementsIfNeeded(node.Accessors, 2, 1) Return MyBase.VisitEventBlock(node) End Function Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.DoStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.LoopStatement.GetLastToken(), 1) Else AddLinebreaksAfterTokenIfNeeded(node.LoopStatement.GetLastToken(), 2) End If Return MyBase.VisitDoLoopBlock(node) End Function Public Overrides Function VisitSyncLockBlock(node As SyncLockBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.SyncLockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) If _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndSyncLockStatement.GetLastToken(), 1) Else AddLinebreaksAfterTokenIfNeeded(node.EndSyncLockStatement.GetLastToken(), 2) End If Return MyBase.VisitSyncLockBlock(node) End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitMethodBlock(node) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitConstructorBlock(node) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitOperatorBlock(node) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitAccessorBlock(node) End Function ''' <summary> ''' Each statement and the begin will be displayed on a separate line. No empty lines. ''' </summary> Public Overrides Function VisitEnumBlock(node As EnumBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.EnumStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Members, 1, 1) Return MyBase.VisitEnumBlock(node) End Function Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.WhileStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndWhileStatement.GetLastToken(), 2) End If Return MyBase.VisitWhileBlock(node) End Function Public Overrides Function VisitForBlock(node As ForBlockSyntax) As SyntaxNode VisitForOrForEachBlock(node) Return MyBase.VisitForBlock(node) End Function Public Overrides Function VisitForEachBlock(node As ForEachBlockSyntax) As SyntaxNode VisitForOrForEachBlock(node) Return MyBase.VisitForEachBlock(node) End Function Private Sub VisitForOrForEachBlock(node As ForOrForEachBlockSyntax) AddLinebreaksAfterTokenIfNeeded(node.ForOrForEachStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If node.NextStatement IsNot Nothing Then If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.NextStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.NextStatement.GetLastToken(), 1) End If End If End Sub Public Overrides Function VisitUsingBlock(node As UsingBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.UsingStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndUsingStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndUsingStatement.GetLastToken(), 1) End If Return MyBase.VisitUsingBlock(node) End Function Public Overrides Function VisitWithBlock(node As WithBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.WithStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitWithBlock(node) End Function Public Overrides Function VisitSelectBlock(node As SelectBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.SelectStatement.GetLastToken(), 1) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndSelectStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndSelectStatement.GetLastToken(), 1) End If Return MyBase.VisitSelectBlock(node) End Function Public Overrides Function VisitCaseBlock(node As CaseBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.CaseStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) Dim result = MyBase.VisitCaseBlock(node) _indentationDepth -= 1 Return result End Function Public Overrides Function VisitTryBlock(node As TryBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.TryStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndTryStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndTryStatement.GetLastToken(), 1) End If Return MyBase.VisitTryBlock(node) End Function Public Overrides Function VisitCatchBlock(node As CatchBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.CatchStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) Return MyBase.VisitCatchBlock(node) End Function Public Overrides Function VisitFinallyBlock(node As FinallyBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.FinallyStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitFinallyBlock(node) End Function Public Overrides Function VisitPropertyBlock(node As PropertyBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.PropertyStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Accessors, 2, 1) Return MyBase.VisitPropertyBlock(node) End Function Public Overrides Function VisitElseBlock(node As ElseBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.ElseStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitElseBlock(node) End Function Public Overrides Function VisitElseIfBlock(node As ElseIfBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.ElseIfStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitElseIfBlock(node) End Function Public Overrides Function VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.SubOrFunctionHeader.GetLastToken(), 1) ' one statement per line AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) _indentationDepth += 1 Dim result = MyBase.VisitMultiLineLambdaExpression(node) Return result End Function Public Overrides Function VisitConstDirectiveTrivia(node As ConstDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitConstDirectiveTrivia(node) End Function Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitIfDirectiveTrivia(node) End Function Public Overrides Function VisitElseDirectiveTrivia(node As ElseDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitElseDirectiveTrivia(node) End Function Public Overrides Function VisitEndIfDirectiveTrivia(node As EndIfDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEndIfDirectiveTrivia(node) End Function Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitRegionDirectiveTrivia(node) End Function Public Overrides Function VisitEndRegionDirectiveTrivia(node As EndRegionDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEndRegionDirectiveTrivia(node) End Function Public Overrides Function VisitExternalSourceDirectiveTrivia(node As ExternalSourceDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitExternalSourceDirectiveTrivia(node) End Function Public Overrides Function VisitEndExternalSourceDirectiveTrivia(node As EndExternalSourceDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEndExternalSourceDirectiveTrivia(node) End Function Public Overrides Function VisitExternalChecksumDirectiveTrivia(node As ExternalChecksumDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitExternalChecksumDirectiveTrivia(node) End Function Public Overrides Function VisitEnableWarningDirectiveTrivia(node As EnableWarningDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEnableWarningDirectiveTrivia(node) End Function Public Overrides Function VisitDisableWarningDirectiveTrivia(node As DisableWarningDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitDisableWarningDirectiveTrivia(node) End Function Public Overrides Function VisitReferenceDirectiveTrivia(node As ReferenceDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitReferenceDirectiveTrivia(node) End Function Public Overrides Function VisitBadDirectiveTrivia(node As BadDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitBadDirectiveTrivia(node) End Function Public Overrides Function VisitAttributeList(node As AttributeListSyntax) As SyntaxNode ' do not add linebreaks for attributes of parameters or return types If node.Parent Is Nothing OrElse (node.Parent.Kind <> SyntaxKind.Parameter AndAlso node.Parent.Kind <> SyntaxKind.SimpleAsClause) Then AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) End If Return MyBase.VisitAttributeList(node) End Function Public Overrides Function VisitEndBlockStatement(node As EndBlockStatementSyntax) As SyntaxNode _indentationDepth -= 1 Return MyBase.VisitEndBlockStatement(node) End Function Public Overrides Function VisitElseStatement(node As ElseStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitElseStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitElseIfStatement(node As ElseIfStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitElseIfStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As SyntaxNode Dim result = MyBase.VisitIfStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitWithStatement(node As WithStatementSyntax) As SyntaxNode Dim result = MyBase.VisitWithStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitSyncLockStatement(node As SyncLockStatementSyntax) As SyntaxNode Dim result = MyBase.VisitSyncLockStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitModuleStatement(node As ModuleStatementSyntax) As SyntaxNode Dim result = MyBase.VisitModuleStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitNamespaceStatement(node As NamespaceStatementSyntax) As SyntaxNode Dim result = MyBase.VisitNamespaceStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitInterfaceStatement(node As InterfaceStatementSyntax) As SyntaxNode Dim result = MyBase.VisitInterfaceStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitStructureStatement(node As StructureStatementSyntax) As SyntaxNode Dim result = MyBase.VisitStructureStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitEnumStatement(node As EnumStatementSyntax) As SyntaxNode Dim result = MyBase.VisitEnumStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitClassStatement(node As ClassStatementSyntax) As SyntaxNode Dim result = MyBase.VisitClassStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitWhileStatement(node As WhileStatementSyntax) As SyntaxNode Dim result = MyBase.VisitWhileStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitDoStatement(node As DoStatementSyntax) As SyntaxNode Dim result = MyBase.VisitDoStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitSelectStatement(node As SelectStatementSyntax) As SyntaxNode Dim result = MyBase.VisitSelectStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitCaseStatement(node As CaseStatementSyntax) As SyntaxNode Dim result = MyBase.VisitCaseStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitLoopStatement(node As LoopStatementSyntax) As SyntaxNode _indentationDepth -= 1 Return MyBase.VisitLoopStatement(node) End Function Public Overrides Function VisitForStatement(node As ForStatementSyntax) As SyntaxNode Dim result = MyBase.VisitForStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitForEachStatement(node As ForEachStatementSyntax) As SyntaxNode Dim result = MyBase.VisitForEachStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitTryStatement(node As TryStatementSyntax) As SyntaxNode Dim result = MyBase.VisitTryStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitCatchStatement(node As CatchStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitCatchStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitFinallyStatement(node As FinallyStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitFinallyStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitUsingStatement(node As UsingStatementSyntax) As SyntaxNode Dim result = MyBase.VisitUsingStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitMethodStatement(node As MethodStatementSyntax) As SyntaxNode Dim result = MyBase.VisitMethodStatement(node) ' only indent if this is a block If node.Parent IsNot Nothing AndAlso (node.Parent.Kind = SyntaxKind.SubBlock OrElse node.Parent.Kind = SyntaxKind.FunctionBlock) Then _indentationDepth += 1 End If Return result End Function Public Overrides Function VisitSubNewStatement(node As SubNewStatementSyntax) As SyntaxNode Dim result = MyBase.VisitSubNewStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitAccessorStatement(node As AccessorStatementSyntax) As SyntaxNode Dim result = MyBase.VisitAccessorStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitOperatorStatement(node As OperatorStatementSyntax) As SyntaxNode Dim result = MyBase.VisitOperatorStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SyntaxNode Dim result = MyBase.VisitEventStatement(node) ' only indent if this is a block If node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.EventBlock Then _indentationDepth += 1 End If Return result End Function Public Overrides Function VisitPropertyStatement(node As PropertyStatementSyntax) As SyntaxNode Dim result = MyBase.VisitPropertyStatement(node) ' only indent if this is a block If node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.PropertyBlock Then _indentationDepth += 1 End If Return result End Function Public Overrides Function VisitLabelStatement(node As LabelStatementSyntax) As SyntaxNode ' labels are never indented. Dim previousIndentationDepth = _indentationDepth _indentationDepth = 0 Dim result = MyBase.VisitLabelStatement(node) _indentationDepth = previousIndentationDepth Return result End Function Public Overrides Function VisitNextStatement(node As NextStatementSyntax) As SyntaxNode ' next statements with multiple control variables are attached to the inner most for statement, ' but it should be indented as it is attached to the outer most one. Dim variableCount = node.ControlVariables.Count If variableCount = 0 Then variableCount = 1 End If _indentationDepth -= variableCount Return MyBase.VisitNextStatement(node) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax Friend Class SyntaxNormalizer Inherits VisualBasicSyntaxRewriter Private ReadOnly _consideredSpan As TextSpan Private ReadOnly _indentWhitespace As String Private ReadOnly _eolTrivia As SyntaxTrivia Private ReadOnly _useElasticTrivia As Boolean Private ReadOnly _useDefaultCasing As Boolean Private _isInStructuredTrivia As Boolean Private _previousToken As SyntaxToken Private _afterLineBreak As Boolean Private _afterIndentation As Boolean Private ReadOnly _lineBreaksAfterToken As Dictionary(Of SyntaxToken, Integer) = New Dictionary(Of SyntaxToken, Integer)() Private ReadOnly _lastStatementsInBlocks As HashSet(Of SyntaxNode) = New HashSet(Of SyntaxNode)() Private _indentationDepth As Integer Private _indentations As ArrayBuilder(Of SyntaxTrivia) ''' <summary> ''' Creates a syntax trivia normalizing visitor ''' </summary> ''' <param name="indentWhitespace">The whitespace to indent with</param> ''' <param name="eolWhitespace">The whitespace to use for end of line</param> ''' <param name="useElasticTrivia">Whether to use elastic trivia or not</param> ''' <param name="useDefaultCasing">Whether to rewrite keywords in default casing or not</param> ''' <remarks></remarks> Private Sub New(consideredSpan As TextSpan, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) MyBase.New(visitIntoStructuredTrivia:=True) Me._consideredSpan = consideredSpan Me._indentWhitespace = indentWhitespace Me._useElasticTrivia = useElasticTrivia Me._eolTrivia = If(useElasticTrivia, SyntaxFactory.ElasticEndOfLine(eolWhitespace), SyntaxFactory.EndOfLine(eolWhitespace)) Me._useDefaultCasing = useDefaultCasing Me._afterLineBreak = True End Sub Friend Shared Function Normalize(Of TNode As SyntaxNode)(node As TNode, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) As SyntaxNode Dim normalizer As New SyntaxNormalizer(node.FullSpan, indentWhitespace, eolWhitespace, useElasticTrivia, useDefaultCasing) Dim result As TNode = CType(normalizer.Visit(node), TNode) normalizer.Free() Return result End Function Friend Shared Function Normalize(token As SyntaxToken, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) As SyntaxToken Dim normalizer As New SyntaxNormalizer(token.FullSpan, indentWhitespace, eolWhitespace, useElasticTrivia, useDefaultCasing) Dim result As SyntaxToken = normalizer.VisitToken(token) normalizer.Free() Return result End Function Friend Shared Function Normalize(trivia As SyntaxTriviaList, indentWhitespace As String, eolWhitespace As String, useElasticTrivia As Boolean, useDefaultCasing As Boolean) As SyntaxTriviaList Dim normalizer = New SyntaxNormalizer(trivia.FullSpan, indentWhitespace, eolWhitespace, useElasticTrivia, useDefaultCasing) Dim result As SyntaxTriviaList = normalizer.RewriteTrivia(trivia, normalizer.GetIndentationDepth(), isTrailing:=False, mustBeIndented:=False, mustHaveSeparator:=False, lineBreaksAfter:=0, lineBreaksBefore:=0) normalizer.Free() Return result End Function Private Sub Free() If _indentations IsNot Nothing Then _indentations.Free() End If End Sub Private Function GetIndentation(count As Integer) As SyntaxTrivia Dim capacity = count + 1 If _indentations Is Nothing Then _indentations = ArrayBuilder(Of SyntaxTrivia).GetInstance(capacity) Else _indentations.EnsureCapacity(capacity) End If For i As Integer = _indentations.Count To count Dim text As String = If(i = 0, "", _indentations(i - 1).ToString() + Me._indentWhitespace) _indentations.Add(If(Me._useElasticTrivia, SyntaxFactory.ElasticWhitespace(text), SyntaxFactory.Whitespace(text))) Next Return _indentations(count) End Function ' use leadingTrivia as indentation ' use trailingTrivia as separation & newlines if needed Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken ' ignore tokens with no content If token.Kind = SyntaxKind.None Then Return token End If Try Dim newToken As SyntaxToken If _useDefaultCasing AndAlso token.IsKeyword() Then newToken = SyntaxFactory.Token(token.Kind) Else newToken = token End If Dim indentationDepth = GetIndentationDepth() ' check if this token is first on this line Dim numLineBreaksBefore As Integer = LineBreaksBetween(_previousToken, token) Dim needsIndentation As Boolean = (numLineBreaksBefore > 0) ' all line breaks except the first will be leading trivia of this token. The first line break ' is trailing trivia of the previous token. If numLineBreaksBefore > 0 AndAlso IsLastTokenOnLine(_previousToken) Then numLineBreaksBefore -= 1 End If newToken = newToken.WithLeadingTrivia( RewriteTrivia( token.LeadingTrivia, indentationDepth, isTrailing:=False, mustBeIndented:=needsIndentation, mustHaveSeparator:=False, lineBreaksAfter:=0, lineBreaksBefore:=numLineBreaksBefore)) Dim nextToken As SyntaxToken = GetNextRelevantToken(token) Me._afterIndentation = False ' we only add one of the line breaks to trivia of this token. The remaining ones will be leading trivia ' for the next token Dim numLineBreaksAfter As Integer = If(LineBreaksBetween(token, nextToken) > 0, 1, 0) Dim needsSeparatorAfter = If(numLineBreaksAfter > 0, False, NeedsSeparator(token, nextToken)) newToken = newToken.WithTrailingTrivia( RewriteTrivia( token.TrailingTrivia, depth:=0, isTrailing:=True, mustBeIndented:=False, mustHaveSeparator:=needsSeparatorAfter, lineBreaksAfter:=numLineBreaksAfter, lineBreaksBefore:=0)) If newToken.Kind = SyntaxKind.DocumentationCommentLineBreakToken Then _afterLineBreak = True ElseIf newToken.Kind = SyntaxKind.XmlTextLiteralToken Then If newToken.TrailingTrivia.Count = 0 AndAlso IsNewLineChar(newToken.ValueText.Last) Then _afterLineBreak = True End If End If Return newToken Finally Me._previousToken = token End Try Return token End Function Private Function RewriteTrivia( triviaList As SyntaxTriviaList, depth As Integer, isTrailing As Boolean, mustBeIndented As Boolean, mustHaveSeparator As Boolean, lineBreaksAfter As Integer, lineBreaksBefore As Integer) As SyntaxTriviaList Dim currentTriviaList As ArrayBuilder(Of SyntaxTrivia) = ArrayBuilder(Of SyntaxTrivia).GetInstance() Try For i = 1 To lineBreaksBefore currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False Next For Each trivia In triviaList ' just keep non whitespace trivia If trivia.Kind = SyntaxKind.WhitespaceTrivia OrElse trivia.Kind = SyntaxKind.EndOfLineTrivia OrElse trivia.Kind = SyntaxKind.LineContinuationTrivia OrElse trivia.FullWidth = 0 Then Continue For End If ' check if there's a separator or a line break needed between the trivia itself Dim tokenParent = trivia.Token.Parent Dim needsSeparator As Boolean = Not (trivia.Kind = SyntaxKind.ColonTrivia AndAlso tokenParent IsNot Nothing AndAlso tokenParent.Kind = SyntaxKind.LabelStatement) AndAlso Not (tokenParent IsNot Nothing AndAlso tokenParent.Parent IsNot Nothing AndAlso tokenParent.Parent.Kind = SyntaxKind.CrefReference) AndAlso ( (currentTriviaList.Count > 0 AndAlso NeedsSeparatorBetween(currentTriviaList.Last()) AndAlso Not EndsInLineBreak(currentTriviaList.Last())) OrElse (currentTriviaList.Count = 0 AndAlso isTrailing) ) Dim needsLineBreak As Boolean = NeedsLineBreakBefore(trivia) OrElse (currentTriviaList.Count > 0 AndAlso NeedsLineBreakBetween(currentTriviaList.Last(), trivia, isTrailing)) If needsLineBreak AndAlso Not _afterLineBreak Then currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False End If If _afterLineBreak And Not isTrailing Then If Not _afterIndentation AndAlso Me.NeedsIndentAfterLineBreak(trivia) Then currentTriviaList.Add(Me.GetIndentation(GetIndentationDepth(trivia))) _afterIndentation = True End If ElseIf needsSeparator Then currentTriviaList.Add(GetSpace()) _afterLineBreak = False _afterIndentation = False End If If trivia.HasStructure Then Dim structuredTrivia As SyntaxTrivia = Me.VisitStructuredTrivia(trivia) currentTriviaList.Add(structuredTrivia) Else ' in structured trivia, the xml doc ''' token contains leading whitespace as text If trivia.Kind = SyntaxKind.DocumentationCommentExteriorTrivia Then trivia = SyntaxFactory.DocumentationCommentExteriorTrivia(SyntaxFacts.GetText(SyntaxKind.DocumentationCommentExteriorTrivia)) End If currentTriviaList.Add(trivia) End If If NeedsLineBreakAfter(trivia) Then If Not isTrailing Then currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False End If Else _afterLineBreak = EndsInLineBreak(trivia) End If Next If lineBreaksAfter > 0 Then If currentTriviaList.Count > 0 AndAlso EndsInLineBreak(currentTriviaList.Last()) Then lineBreaksAfter = lineBreaksAfter - 1 End If For i = 0 To lineBreaksAfter - 1 currentTriviaList.Add(GetEndOfLine()) _afterLineBreak = True _afterIndentation = False Next i ElseIf mustHaveSeparator Then currentTriviaList.Add(GetSpace()) _afterLineBreak = False _afterIndentation = False End If If mustBeIndented Then currentTriviaList.Add(Me.GetIndentation(depth)) _afterIndentation = True _afterLineBreak = False End If If currentTriviaList.Count = 0 Then If _useElasticTrivia Then Return SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker) Else Return Nothing End If ElseIf currentTriviaList.Count = 1 Then Return SyntaxFactory.TriviaList(currentTriviaList.First()) Else Return SyntaxFactory.TriviaList(currentTriviaList) End If Finally currentTriviaList.Free() End Try End Function Private Function IsLastTokenOnLine(token As SyntaxToken) As Boolean Return (token.HasTrailingTrivia AndAlso token.TrailingTrivia.Last.Kind = SyntaxKind.ColonTrivia) OrElse (token.Parent IsNot Nothing AndAlso token.Parent.GetLastToken() = token) End Function Private Function LineBreaksBetween(currentToken As SyntaxToken, nextToken As SyntaxToken) As Integer ' First and last token may be of kind none If currentToken.Kind = SyntaxKind.None OrElse nextToken.Kind = SyntaxKind.None Then Return 0 End If Dim numLineBreaks As Integer = 0 If _lineBreaksAfterToken.TryGetValue(currentToken, numLineBreaks) Then Return numLineBreaks End If Return 0 End Function ''' <summary> ''' indentation depth is the declaration depth for statements within the block. for start/end statements ''' of these blocks (e.g. the if statement), it is a level less ''' </summary> Private Function GetIndentationDepth() As Integer Debug.Assert(Me._indentationDepth >= 0) Return Me._indentationDepth End Function Private Function GetIndentationDepth(trivia As SyntaxTrivia) As Integer If SyntaxFacts.IsPreprocessorDirective(trivia.Kind) Then Return 0 End If Return GetIndentationDepth() End Function Private Function GetSpace() As SyntaxTrivia Return If(Me._useElasticTrivia, SyntaxFactory.ElasticSpace, SyntaxFactory.Space) End Function Private Function GetEndOfLine() As SyntaxTrivia Return _eolTrivia End Function Private Function NeedsSeparatorBetween(trivia As SyntaxTrivia) As Boolean Select Case trivia.Kind Case SyntaxKind.None, SyntaxKind.WhitespaceTrivia, SyntaxKind.DocumentationCommentExteriorTrivia, SyntaxKind.LineContinuationTrivia Return False Case Else Return Not SyntaxFacts.IsPreprocessorDirective(trivia.Kind) End Select End Function Private Function NeedsLineBreakBetween(trivia As SyntaxTrivia, nextTrivia As SyntaxTrivia, isTrailingTrivia As Boolean) As Boolean If EndsInLineBreak(trivia) Then Return False End If Select Case nextTrivia.Kind Case SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentExteriorTrivia, SyntaxKind.EmptyStatement, SyntaxKind.IfDirectiveTrivia, SyntaxKind.ElseIfDirectiveTrivia, SyntaxKind.ElseDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia, SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.ConstDirectiveTrivia, SyntaxKind.ExternalSourceDirectiveTrivia, SyntaxKind.EndExternalSourceDirectiveTrivia, SyntaxKind.ExternalChecksumDirectiveTrivia, SyntaxKind.EnableWarningDirectiveTrivia, SyntaxKind.DisableWarningDirectiveTrivia, SyntaxKind.ReferenceDirectiveTrivia, SyntaxKind.BadDirectiveTrivia Return Not isTrailingTrivia Case Else Return False End Select End Function Private Function NeedsLineBreakAfter(trivia As SyntaxTrivia) As Boolean Return trivia.Kind = SyntaxKind.CommentTrivia End Function Private Function NeedsLineBreakBefore(trivia As SyntaxTrivia) As Boolean Select Case trivia.Kind Case SyntaxKind.DocumentationCommentExteriorTrivia Return True Case Else Return False End Select End Function Private Function NeedsIndentAfterLineBreak(trivia As SyntaxTrivia) As Boolean Select Case trivia.Kind Case SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentExteriorTrivia, SyntaxKind.DocumentationCommentTrivia Return True Case Else Return False End Select End Function Private Function NeedsSeparator(token As SyntaxToken, nextToken As SyntaxToken) As Boolean If token.Kind = SyntaxKind.EndOfFileToken Then Return False End If If token.Parent Is Nothing OrElse nextToken.Kind = SyntaxKind.None Then Return False End If If nextToken.Parent.Kind = SyntaxKind.SingleLineFunctionLambdaExpression Then Return True End If If nextToken.Kind = SyntaxKind.EndOfFileToken Then Return False End If ' +1 instead of + 1 ' but not a instead of nota ... If TypeOf (token.Parent) Is UnaryExpressionSyntax AndAlso token.Kind <> SyntaxKind.NotKeyword AndAlso token.Kind <> SyntaxKind.AddressOfKeyword Then Return False End If ' generally a + b, needs to go here to make it b + (a + b) instead of b +(a + b If TypeOf (token.Parent) Is BinaryExpressionSyntax OrElse TypeOf (nextToken.Parent) Is BinaryExpressionSyntax Then Return True End If ' (a instead of ( a If token.Kind = SyntaxKind.OpenParenToken Then Return False End If ' a) instead of a ) If nextToken.Kind = SyntaxKind.CloseParenToken Then Return False End If ' m( instead of m ( If token.Kind <> SyntaxKind.CommaToken AndAlso nextToken.Kind = SyntaxKind.OpenParenToken Then Return False End If ' (,,,) instead of ( , , ,) or (a As Char, b as Char) instead of (a As Char , b as Char) ' $"{e,1:C}" instead of $"{e,1:C}" If (token.Kind = SyntaxKind.CommaToken AndAlso (nextToken.Kind = SyntaxKind.EmptyToken OrElse token.Parent.Kind = SyntaxKind.InterpolationAlignmentClause)) OrElse nextToken.Kind = SyntaxKind.CommaToken Then Return False End If ' a.b and .b instead of a . b, but keep with {key .field} If token.Kind = SyntaxKind.DotToken Then Return False ElseIf nextToken.Kind = SyntaxKind.DotToken AndAlso nextToken.Parent.Kind <> SyntaxKind.NamedFieldInitializer Then Return False End If If nextToken.Kind = SyntaxKind.ColonToken Then If token.Parent.Kind = SyntaxKind.LabelStatement Then ' label: instead of label : Return False ElseIf nextToken.Parent.Kind = SyntaxKind.InterpolationFormatClause Then ' $"{e,1:C}" instead of $"{e,1 :C}" Return False End If End If ' {1 instead of { 1 and 1} instead of 1 } If token.Kind = SyntaxKind.OpenBraceToken OrElse nextToken.Kind = SyntaxKind.CloseBraceToken Then Return False End If ' s1(p1:=23, p2:=12) instead of s1(p1 := 23, p2 := 12) If token.Kind = SyntaxKind.ColonEqualsToken OrElse nextToken.Kind = SyntaxKind.ColonEqualsToken Then Return False End If ' case > 100 should keep separator ' need to test before xml analysis below If SyntaxFacts.IsRelationalCaseClause(token.Parent.Kind()) OrElse SyntaxFacts.IsRelationalCaseClause(nextToken.Parent.Kind()) Then Return True End If ' handle closing attribute before XML tokens ' sub goo(<obsolete()> ByRef i as Integer) instead of sub goo(<obsolete()>ByRef i as Integer) If (token.Kind = SyntaxKind.GreaterThanToken AndAlso token.Parent.Kind = SyntaxKind.AttributeList) Then Return True End If ' needs to be checked after binary operators ' Imports <goo instead of Imports < goo If (token.Kind = SyntaxKind.LessThanToken OrElse nextToken.Kind = SyntaxKind.GreaterThanToken OrElse token.Kind = SyntaxKind.LessThanSlashToken OrElse token.Kind = SyntaxKind.GreaterThanToken OrElse nextToken.Kind = SyntaxKind.LessThanSlashToken) Then Return False End If ' <xmlns:goo instead of <xmlns : goo If token.Kind = SyntaxKind.ColonToken AndAlso token.Parent.Kind = SyntaxKind.XmlPrefix OrElse nextToken.Kind = SyntaxKind.ColonToken AndAlso nextToken.Parent.Kind = SyntaxKind.XmlPrefix Then Return False End If ' <e/> instead of <e /> If nextToken.Kind = SyntaxKind.SlashGreaterThanToken Then Return False End If ' <!--a--> instead of <!-- a --> If token.Kind = SyntaxKind.LessThanExclamationMinusMinusToken OrElse nextToken.Kind = SyntaxKind.MinusMinusGreaterThanToken Then Return False End If ' <?xml ?> instead of <? xml ?> If token.Kind = SyntaxKind.LessThanQuestionToken Then Return False End If ' <![CDATA[goo]]> instead of <![CDATA[ goo ]]> If token.Kind = SyntaxKind.BeginCDataToken OrElse nextToken.Kind = SyntaxKind.EndCDataToken Then Return False End If ' <Assembly:System.Copyright("(C) 2009")> instead of <Assembly : System.Copyright("(C) 2009")> If token.Kind = SyntaxKind.ColonToken AndAlso token.Parent.Kind = SyntaxKind.AttributeTarget OrElse nextToken.Kind = SyntaxKind.ColonToken AndAlso nextToken.Parent.Kind = SyntaxKind.AttributeTarget Then Return False End If ' <goo="bar" instead of <goo = "bar" If (token.Kind = SyntaxKind.EqualsToken AndAlso (token.Parent.Kind = SyntaxKind.XmlAttribute OrElse token.Parent.Kind = SyntaxKind.XmlCrefAttribute OrElse token.Parent.Kind = SyntaxKind.XmlNameAttribute OrElse token.Parent.Kind = SyntaxKind.XmlDeclaration)) OrElse (nextToken.Kind = SyntaxKind.EqualsToken AndAlso (nextToken.Parent.Kind = SyntaxKind.XmlAttribute OrElse nextToken.Parent.Kind = SyntaxKind.XmlCrefAttribute OrElse nextToken.Parent.Kind = SyntaxKind.XmlNameAttribute OrElse nextToken.Parent.Kind = SyntaxKind.XmlDeclaration)) Then Return False End If ' needs to be below binary expression checks ' <attrib="goo" instead of <attrib=" goo " If token.Kind = SyntaxKind.DoubleQuoteToken OrElse nextToken.Kind = SyntaxKind.DoubleQuoteToken Then Return False End If ' <x/>@a instead of <x/>@ a If token.Kind = SyntaxKind.AtToken AndAlso token.Parent.Kind = SyntaxKind.XmlAttributeAccessExpression Then Return False End If ' 'e' instead of ' e ' If token.Kind = SyntaxKind.SingleQuoteToken OrElse nextToken.Kind = SyntaxKind.SingleQuoteToken Then Return False End If ' Integer? instead of Integer ? If nextToken.Kind = SyntaxKind.QuestionToken Then Return False End If ' #if instead of # if If token.Kind = SyntaxKind.HashToken AndAlso TypeOf token.Parent Is DirectiveTriviaSyntax Then Return False End If ' "#region" instead of "#region " If token.Parent.Kind = SyntaxKind.RegionDirectiveTrivia AndAlso nextToken.Kind = SyntaxKind.StringLiteralToken AndAlso String.IsNullOrEmpty(nextToken.ValueText) Then Return False End If If token.Kind = SyntaxKind.XmlTextLiteralToken OrElse token.Kind = SyntaxKind.DocumentationCommentLineBreakToken Then Return False End If If token.Kind = SyntaxKind.DollarSignDoubleQuoteToken Then Return False End If If token.Kind = SyntaxKind.InterpolatedStringTextToken OrElse nextToken.Kind = SyntaxKind.InterpolatedStringTextToken Then Return False End If Return True End Function Private Function EndsInLineBreak(trivia As SyntaxTrivia) As Boolean If trivia.Kind = SyntaxKind.EndOfLineTrivia Then Return True End If If trivia.Kind = SyntaxKind.DisabledTextTrivia Then Dim text As String = trivia.ToFullString() Return text.Length > 0 AndAlso IsNewLineChar(text.Last()) End If If trivia.HasStructure Then If trivia.GetStructure.GetLastToken.HasTrailingTrivia AndAlso trivia.GetStructure.GetLastToken.TrailingTrivia.Last.Kind = SyntaxKind.EndOfLineTrivia Then Return True End If End If Return False End Function Private Shared Function IsNewLineChar(ch As Char) As Boolean ' new-line-character: ' Carriage return character (U+000D) ' Line feed character (U+000A) ' Next line character (U+0085) ' Line separator character (U+2028) ' Paragraph separator character (U+2029) Return ch = vbLf _ OrElse ch = vbCr _ OrElse ch = "\u0085" _ OrElse ch = "\u2028" _ OrElse ch = "\u2029" End Function Private Overloads Function VisitStructuredTrivia(trivia As SyntaxTrivia) As SyntaxTrivia Dim oldIsInStructuredTrivia As Boolean = Me._isInStructuredTrivia Me._isInStructuredTrivia = True Dim oldPreviousToken = Me._previousToken Me._previousToken = Nothing Dim result As SyntaxTrivia = VisitTrivia(trivia) Me._isInStructuredTrivia = oldIsInStructuredTrivia Me._previousToken = oldPreviousToken Return result End Function Private Function GetNextRelevantToken(token As SyntaxToken) As SyntaxToken Dim nextToken = token.GetNextToken(Function(t As SyntaxToken) Return t.Kind <> SyntaxKind.None End Function, Function(t As SyntaxTrivia) False) If _consideredSpan.Contains(nextToken.FullSpan) Then Return nextToken Else Return Nothing End If End Function Private Sub AddLinebreaksAfterElementsIfNeeded(Of TNode As SyntaxNode)( list As SyntaxList(Of TNode), linebreaksBetweenElements As Integer, linebreaksAfterLastElement As Integer ) Dim lastElementIndex = list.Count - 1 For elementIndex = 0 To lastElementIndex Dim listElement = list(elementIndex) If listElement.Kind = SyntaxKind.LabelStatement Then ' always add linebreaks after label _lineBreaksAfterToken(listElement.GetLastToken()) = 1 Else AddLinebreaksAfterTokenIfNeeded(listElement.GetLastToken(), If(elementIndex = lastElementIndex, linebreaksAfterLastElement, linebreaksBetweenElements)) End If Next End Sub Private Sub AddLinebreaksAfterTokenIfNeeded(node As SyntaxToken, linebreaksAfterToken As Integer) If Not EndsWithColonSeparator(node) Then Me._lineBreaksAfterToken(node) = linebreaksAfterToken End If End Sub Private Function EndsWithColonSeparator(node As SyntaxToken) As Boolean Return node.HasTrailingTrivia AndAlso node.TrailingTrivia.Last.Kind = SyntaxKind.ColonTrivia End Function Private Sub MarkLastStatementIfNeeded(Of TNode As SyntaxNode)(list As SyntaxList(Of TNode)) If list.Any Then _lastStatementsInBlocks.Add(list.Last) End If End Sub ''' <summary> ''' We each element of option, imports and attributes on a separate line, where the last element of this the list if ''' followed by an empty line: ''' Option Strict On ''' ''' Imports System ''' Imports Goo ''' ''' [...] ''' ''' Namespace ''' [...] ''' </summary> Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode Dim hasImports = node.Imports.Any Dim hasMembers = node.Members.Any Dim hasAttributes = node.Attributes.Any If hasImports OrElse hasAttributes OrElse hasMembers Then AddLinebreaksAfterElementsIfNeeded(node.Options, 1, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Options, 1, 1) End If If hasAttributes OrElse hasMembers Then AddLinebreaksAfterElementsIfNeeded(node.Imports, 1, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Imports, 1, 1) End If If hasMembers Then AddLinebreaksAfterElementsIfNeeded(node.Attributes, 1, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Attributes, 1, 1) End If AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 1) Return MyBase.VisitCompilationUnit(node) End Function ''' <summary> ''' Add an empty line after the begin, except the first member is a nested namespace. ''' Separate each member of a namespace with an empty line. ''' </summary> Public Overrides Function VisitNamespaceBlock(node As NamespaceBlockSyntax) As SyntaxNode If node.Members.Count > 0 Then ' Add an empty line after the namespace begin if there ' is not a namespace declaration as first member If node.Members(0).Kind <> SyntaxKind.NamespaceBlock Then AddLinebreaksAfterTokenIfNeeded(node.NamespaceStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.NamespaceStatement.GetLastToken(), 1) End If AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 1) Else AddLinebreaksAfterTokenIfNeeded(node.NamespaceStatement.GetLastToken(), 1) End If Return MyBase.VisitNamespaceBlock(node) End Function Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitModuleBlock(node) End Function Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitClassBlock(node) End Function Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitStructureBlock(node) End Function Public Overrides Function VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax) As SyntaxNode VisitTypeBlockSyntax(node) Return MyBase.VisitInterfaceBlock(node) End Function ''' <summary> ''' We want to display type blocks (Modules, Classes, Structures and Interfaces) like follows ''' Class Goo ''' implements IBar1, IBar2 ''' implements IBar3 ''' inherits Bar1 ''' ''' Public Sub Boo() ''' End Sub ''' End Class ''' ''' or ''' ''' Class Goo ''' ''' Public Sub Boo() ''' End Sub ''' End Class ''' ''' Basically it's an empty line between implements and inherits and between each member. If there are no ''' inherits or implements, add an empty line before the first member. ''' </summary> Private Sub VisitTypeBlockSyntax(ByVal node As TypeBlockSyntax) Dim hasImplements As Boolean = node.Implements.Count > 0 Dim hasInherits As Boolean = node.Inherits.Count > 0 ' add a line break between begin statement and the ones from the statement list If Not hasInherits AndAlso Not hasImplements AndAlso node.Members.Count > 0 Then AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) End If If hasImplements Then AddLinebreaksAfterElementsIfNeeded(node.Inherits, 1, 1) Else AddLinebreaksAfterElementsIfNeeded(node.Inherits, 1, 2) End If AddLinebreaksAfterElementsIfNeeded(node.Implements, 1, 2) If node.Kind = SyntaxKind.InterfaceBlock Then AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 2) Else AddLinebreaksAfterElementsIfNeeded(node.Members, 2, 1) End If End Sub Public Overrides Function VisitMultiLineIfBlock(node As MultiLineIfBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.IfStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Dim previousNode As VisualBasicSyntaxNode If node.Statements.Any() Then previousNode = node.Statements.Last() Else previousNode = node.IfStatement End If For Each elseIfBlock In node.ElseIfBlocks AddLinebreaksAfterTokenIfNeeded(previousNode.GetLastToken(), 1) previousNode = elseIfBlock Next If node.ElseBlock IsNot Nothing Then AddLinebreaksAfterTokenIfNeeded(previousNode.GetLastToken(), 1) End If If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndIfStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndIfStatement.GetLastToken(), 1) End If Return MyBase.VisitMultiLineIfBlock(node) End Function Public Overrides Function VisitEventBlock(node As EventBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.EventStatement.GetLastToken, 1) AddLinebreaksAfterElementsIfNeeded(node.Accessors, 2, 1) Return MyBase.VisitEventBlock(node) End Function Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.DoStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.LoopStatement.GetLastToken(), 1) Else AddLinebreaksAfterTokenIfNeeded(node.LoopStatement.GetLastToken(), 2) End If Return MyBase.VisitDoLoopBlock(node) End Function Public Overrides Function VisitSyncLockBlock(node As SyncLockBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.SyncLockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) If _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndSyncLockStatement.GetLastToken(), 1) Else AddLinebreaksAfterTokenIfNeeded(node.EndSyncLockStatement.GetLastToken(), 2) End If Return MyBase.VisitSyncLockBlock(node) End Function Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitMethodBlock(node) End Function Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitConstructorBlock(node) End Function Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitOperatorBlock(node) End Function Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.BlockStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitAccessorBlock(node) End Function ''' <summary> ''' Each statement and the begin will be displayed on a separate line. No empty lines. ''' </summary> Public Overrides Function VisitEnumBlock(node As EnumBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.EnumStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Members, 1, 1) Return MyBase.VisitEnumBlock(node) End Function Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.WhileStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndWhileStatement.GetLastToken(), 2) End If Return MyBase.VisitWhileBlock(node) End Function Public Overrides Function VisitForBlock(node As ForBlockSyntax) As SyntaxNode VisitForOrForEachBlock(node) Return MyBase.VisitForBlock(node) End Function Public Overrides Function VisitForEachBlock(node As ForEachBlockSyntax) As SyntaxNode VisitForOrForEachBlock(node) Return MyBase.VisitForEachBlock(node) End Function Private Sub VisitForOrForEachBlock(node As ForOrForEachBlockSyntax) AddLinebreaksAfterTokenIfNeeded(node.ForOrForEachStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If node.NextStatement IsNot Nothing Then If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.NextStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.NextStatement.GetLastToken(), 1) End If End If End Sub Public Overrides Function VisitUsingBlock(node As UsingBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.UsingStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndUsingStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndUsingStatement.GetLastToken(), 1) End If Return MyBase.VisitUsingBlock(node) End Function Public Overrides Function VisitWithBlock(node As WithBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.WithStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitWithBlock(node) End Function Public Overrides Function VisitSelectBlock(node As SelectBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.SelectStatement.GetLastToken(), 1) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndSelectStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndSelectStatement.GetLastToken(), 1) End If Return MyBase.VisitSelectBlock(node) End Function Public Overrides Function VisitCaseBlock(node As CaseBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.CaseStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) Dim result = MyBase.VisitCaseBlock(node) _indentationDepth -= 1 Return result End Function Public Overrides Function VisitTryBlock(node As TryBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.TryStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) If Not _lastStatementsInBlocks.Contains(node) Then AddLinebreaksAfterTokenIfNeeded(node.EndTryStatement.GetLastToken(), 2) Else AddLinebreaksAfterTokenIfNeeded(node.EndTryStatement.GetLastToken(), 1) End If Return MyBase.VisitTryBlock(node) End Function Public Overrides Function VisitCatchBlock(node As CatchBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.CatchStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) Return MyBase.VisitCatchBlock(node) End Function Public Overrides Function VisitFinallyBlock(node As FinallyBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.FinallyStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitFinallyBlock(node) End Function Public Overrides Function VisitPropertyBlock(node As PropertyBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.PropertyStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Accessors, 2, 1) Return MyBase.VisitPropertyBlock(node) End Function Public Overrides Function VisitElseBlock(node As ElseBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.ElseStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitElseBlock(node) End Function Public Overrides Function VisitElseIfBlock(node As ElseIfBlockSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.ElseIfStatement.GetLastToken(), 1) AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) Return MyBase.VisitElseIfBlock(node) End Function Public Overrides Function VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.SubOrFunctionHeader.GetLastToken(), 1) ' one statement per line AddLinebreaksAfterElementsIfNeeded(node.Statements, 1, 1) MarkLastStatementIfNeeded(node.Statements) _indentationDepth += 1 Dim result = MyBase.VisitMultiLineLambdaExpression(node) Return result End Function Public Overrides Function VisitConstDirectiveTrivia(node As ConstDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitConstDirectiveTrivia(node) End Function Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitIfDirectiveTrivia(node) End Function Public Overrides Function VisitElseDirectiveTrivia(node As ElseDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitElseDirectiveTrivia(node) End Function Public Overrides Function VisitEndIfDirectiveTrivia(node As EndIfDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEndIfDirectiveTrivia(node) End Function Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitRegionDirectiveTrivia(node) End Function Public Overrides Function VisitEndRegionDirectiveTrivia(node As EndRegionDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEndRegionDirectiveTrivia(node) End Function Public Overrides Function VisitExternalSourceDirectiveTrivia(node As ExternalSourceDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitExternalSourceDirectiveTrivia(node) End Function Public Overrides Function VisitEndExternalSourceDirectiveTrivia(node As EndExternalSourceDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEndExternalSourceDirectiveTrivia(node) End Function Public Overrides Function VisitExternalChecksumDirectiveTrivia(node As ExternalChecksumDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitExternalChecksumDirectiveTrivia(node) End Function Public Overrides Function VisitEnableWarningDirectiveTrivia(node As EnableWarningDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitEnableWarningDirectiveTrivia(node) End Function Public Overrides Function VisitDisableWarningDirectiveTrivia(node As DisableWarningDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitDisableWarningDirectiveTrivia(node) End Function Public Overrides Function VisitReferenceDirectiveTrivia(node As ReferenceDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitReferenceDirectiveTrivia(node) End Function Public Overrides Function VisitBadDirectiveTrivia(node As BadDirectiveTriviaSyntax) As SyntaxNode AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) Return MyBase.VisitBadDirectiveTrivia(node) End Function Public Overrides Function VisitAttributeList(node As AttributeListSyntax) As SyntaxNode ' do not add linebreaks for attributes of parameters or return types If node.Parent Is Nothing OrElse (node.Parent.Kind <> SyntaxKind.Parameter AndAlso node.Parent.Kind <> SyntaxKind.SimpleAsClause) Then AddLinebreaksAfterTokenIfNeeded(node.GetLastToken(), 1) End If Return MyBase.VisitAttributeList(node) End Function Public Overrides Function VisitEndBlockStatement(node As EndBlockStatementSyntax) As SyntaxNode _indentationDepth -= 1 Return MyBase.VisitEndBlockStatement(node) End Function Public Overrides Function VisitElseStatement(node As ElseStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitElseStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitElseIfStatement(node As ElseIfStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitElseIfStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As SyntaxNode Dim result = MyBase.VisitIfStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitWithStatement(node As WithStatementSyntax) As SyntaxNode Dim result = MyBase.VisitWithStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitSyncLockStatement(node As SyncLockStatementSyntax) As SyntaxNode Dim result = MyBase.VisitSyncLockStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitModuleStatement(node As ModuleStatementSyntax) As SyntaxNode Dim result = MyBase.VisitModuleStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitNamespaceStatement(node As NamespaceStatementSyntax) As SyntaxNode Dim result = MyBase.VisitNamespaceStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitInterfaceStatement(node As InterfaceStatementSyntax) As SyntaxNode Dim result = MyBase.VisitInterfaceStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitStructureStatement(node As StructureStatementSyntax) As SyntaxNode Dim result = MyBase.VisitStructureStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitEnumStatement(node As EnumStatementSyntax) As SyntaxNode Dim result = MyBase.VisitEnumStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitClassStatement(node As ClassStatementSyntax) As SyntaxNode Dim result = MyBase.VisitClassStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitWhileStatement(node As WhileStatementSyntax) As SyntaxNode Dim result = MyBase.VisitWhileStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitDoStatement(node As DoStatementSyntax) As SyntaxNode Dim result = MyBase.VisitDoStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitSelectStatement(node As SelectStatementSyntax) As SyntaxNode Dim result = MyBase.VisitSelectStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitCaseStatement(node As CaseStatementSyntax) As SyntaxNode Dim result = MyBase.VisitCaseStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitLoopStatement(node As LoopStatementSyntax) As SyntaxNode _indentationDepth -= 1 Return MyBase.VisitLoopStatement(node) End Function Public Overrides Function VisitForStatement(node As ForStatementSyntax) As SyntaxNode Dim result = MyBase.VisitForStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitForEachStatement(node As ForEachStatementSyntax) As SyntaxNode Dim result = MyBase.VisitForEachStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitTryStatement(node As TryStatementSyntax) As SyntaxNode Dim result = MyBase.VisitTryStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitCatchStatement(node As CatchStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitCatchStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitFinallyStatement(node As FinallyStatementSyntax) As SyntaxNode _indentationDepth -= 1 Dim result = MyBase.VisitFinallyStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitUsingStatement(node As UsingStatementSyntax) As SyntaxNode Dim result = MyBase.VisitUsingStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitMethodStatement(node As MethodStatementSyntax) As SyntaxNode Dim result = MyBase.VisitMethodStatement(node) ' only indent if this is a block If node.Parent IsNot Nothing AndAlso (node.Parent.Kind = SyntaxKind.SubBlock OrElse node.Parent.Kind = SyntaxKind.FunctionBlock) Then _indentationDepth += 1 End If Return result End Function Public Overrides Function VisitSubNewStatement(node As SubNewStatementSyntax) As SyntaxNode Dim result = MyBase.VisitSubNewStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitAccessorStatement(node As AccessorStatementSyntax) As SyntaxNode Dim result = MyBase.VisitAccessorStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitOperatorStatement(node As OperatorStatementSyntax) As SyntaxNode Dim result = MyBase.VisitOperatorStatement(node) _indentationDepth += 1 Return result End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SyntaxNode Dim result = MyBase.VisitEventStatement(node) ' only indent if this is a block If node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.EventBlock Then _indentationDepth += 1 End If Return result End Function Public Overrides Function VisitPropertyStatement(node As PropertyStatementSyntax) As SyntaxNode Dim result = MyBase.VisitPropertyStatement(node) ' only indent if this is a block If node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.PropertyBlock Then _indentationDepth += 1 End If Return result End Function Public Overrides Function VisitLabelStatement(node As LabelStatementSyntax) As SyntaxNode ' labels are never indented. Dim previousIndentationDepth = _indentationDepth _indentationDepth = 0 Dim result = MyBase.VisitLabelStatement(node) _indentationDepth = previousIndentationDepth Return result End Function Public Overrides Function VisitNextStatement(node As NextStatementSyntax) As SyntaxNode ' next statements with multiple control variables are attached to the inner most for statement, ' but it should be indented as it is attached to the outer most one. Dim variableCount = node.ControlVariables.Count If variableCount = 0 Then variableCount = 1 End If _indentationDepth -= variableCount Return MyBase.VisitNextStatement(node) End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/LiveShare/Impl/Client/ExternalAccess/VSTypeScript/VSTypeScriptRemoteLanguageServiceWorkspaceAccessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.ExternalAccess.VSTypeScript { [Export(typeof(IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor))] internal sealed class VSTypeScriptRemoteLanguageServiceWorkspaceAccessor : IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor { private readonly RemoteLanguageServiceWorkspace _remoteLanguageServiceWorkspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptRemoteLanguageServiceWorkspaceAccessor(RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace) { _remoteLanguageServiceWorkspace = remoteLanguageServiceWorkspace; } CodeAnalysis.Workspace IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor.RemoteLanguageServiceWorkspace => _remoteLanguageServiceWorkspace; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServices.ExternalAccess.VSTypeScript.Api; namespace Microsoft.VisualStudio.LanguageServices.LiveShare.Client.ExternalAccess.VSTypeScript { [Export(typeof(IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor))] internal sealed class VSTypeScriptRemoteLanguageServiceWorkspaceAccessor : IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor { private readonly RemoteLanguageServiceWorkspace _remoteLanguageServiceWorkspace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VSTypeScriptRemoteLanguageServiceWorkspaceAccessor(RemoteLanguageServiceWorkspace remoteLanguageServiceWorkspace) { _remoteLanguageServiceWorkspace = remoteLanguageServiceWorkspace; } CodeAnalysis.Workspace IVsTypeScriptRemoteLanguageServiceWorkspaceAccessor.RemoteLanguageServiceWorkspace => _remoteLanguageServiceWorkspace; } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/Structure/AbstractVisualBasicSyntaxTriviaStructureTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Structure Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public MustInherit Class AbstractVisualBasicSyntaxTriviaStructureProviderTests Inherits AbstractSyntaxTriviaStructureProviderTests Protected NotOverridable Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.Structure Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public MustInherit Class AbstractVisualBasicSyntaxTriviaStructureProviderTests Inherits AbstractSyntaxTriviaStructureProviderTests Protected NotOverridable Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Portable/Parser/ParserExtensions.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------- ' Contains extension method helpers for object derived from SyntaxNode '----------------------------------------------------------------------------- Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Module ParserExtensions <Extension()> Friend Function Any(Of T As VisualBasicSyntaxNode)(this As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of T), ParamArray kinds As SyntaxKind()) As Boolean Debug.Assert(kinds IsNot Nothing) For i = 0 To kinds.Length - 1 If this.Any(kinds(i)) Then Return True End If Next Return False End Function <Extension()> Friend Function AnyAndOnly(Of T As VisualBasicSyntaxNode)(this As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of T), ParamArray kinds As SyntaxKind()) As Boolean Debug.Assert(kinds IsNot Nothing) Dim found As Boolean = False For i = 0 To this.Count - 1 found = kinds.Contains(this(i).Kind) If Not found Then Return False End If Next Return found End Function <Extension()> Friend Function ContainsDiagnostics(Of T As VisualBasicSyntaxNode)(this As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of T)) As Boolean For i = 0 To this.Count - 1 If this.Item(i).ContainsDiagnostics Then Return True End If Next Return False End Function <Extension()> Friend Function ContainsDiagnostics(Of T As VisualBasicSyntaxNode)(this As SyntaxListBuilder(Of T)) As Boolean For i = 0 To this.Count - 1 If this(i).ContainsDiagnostics Then Return True End If Next Return False End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------- ' Contains extension method helpers for object derived from SyntaxNode '----------------------------------------------------------------------------- Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports InternalSyntaxFactory = Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax.SyntaxFactory Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax Friend Module ParserExtensions <Extension()> Friend Function Any(Of T As VisualBasicSyntaxNode)(this As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of T), ParamArray kinds As SyntaxKind()) As Boolean Debug.Assert(kinds IsNot Nothing) For i = 0 To kinds.Length - 1 If this.Any(kinds(i)) Then Return True End If Next Return False End Function <Extension()> Friend Function AnyAndOnly(Of T As VisualBasicSyntaxNode)(this As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of T), ParamArray kinds As SyntaxKind()) As Boolean Debug.Assert(kinds IsNot Nothing) Dim found As Boolean = False For i = 0 To this.Count - 1 found = kinds.Contains(this(i).Kind) If Not found Then Return False End If Next Return found End Function <Extension()> Friend Function ContainsDiagnostics(Of T As VisualBasicSyntaxNode)(this As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of T)) As Boolean For i = 0 To this.Count - 1 If this.Item(i).ContainsDiagnostics Then Return True End If Next Return False End Function <Extension()> Friend Function ContainsDiagnostics(Of T As VisualBasicSyntaxNode)(this As SyntaxListBuilder(Of T)) As Boolean For i = 0 To this.Count - 1 If this(i).ContainsDiagnostics Then Return True End If Next Return False End Function End Module End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxTree.LazySyntaxTree.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree Private NotInheritable Class LazySyntaxTree Inherits VisualBasicSyntaxTree Private ReadOnly _text As SourceText Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _path As String Private ReadOnly _diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Private _lazyRoot As VisualBasicSyntaxNode ''' <summary> ''' Used to create new tree incrementally. ''' </summary> Friend Sub New(text As SourceText, options As VisualBasicParseOptions, path As String, diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic)) Debug.Assert(options IsNot Nothing) _text = text _options = options _path = If(path, String.Empty) _diagnosticOptions = If(diagnosticOptions, EmptyDiagnosticOptions) End Sub Public Overrides ReadOnly Property FilePath As String Get Return _path End Get End Property Friend Overrides ReadOnly Property IsMyTemplate As Boolean Get Return False End Get End Property Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText Return _text End Function Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean text = _text Return True End Function Public Overrides ReadOnly Property Encoding As Encoding Get Return _text.Encoding End Get End Property Public Overrides ReadOnly Property Length As Integer Get Return _text.Length End Get End Property Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode If _lazyRoot Is Nothing Then ' Parse the syntax tree Dim tree = SyntaxFactory.ParseSyntaxTree(_text, _options, _path, cancellationToken) Dim root = CloneNodeAsRoot(CType(tree.GetRoot(cancellationToken), VisualBasicSyntaxNode)) Interlocked.CompareExchange(_lazyRoot, root, Nothing) End If Return _lazyRoot End Function Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean root = _lazyRoot Return root IsNot Nothing End Function Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Public Overrides ReadOnly Property DiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Get Return _diagnosticOptions End Get End Property ''' <summary> ''' Get a reference to the given node. ''' </summary> Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference Return New SimpleSyntaxReference(Me, node) End Function Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree If _lazyRoot Is root AndAlso _options Is options Then Return Me End If Return New ParsedSyntaxTree( Nothing, _text.Encoding, _text.ChecksumAlgorithm, _path, DirectCast(options, VisualBasicParseOptions), DirectCast(root, VisualBasicSyntaxNode), isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithFilePath(path As String) As SyntaxTree If String.Equals(Me._path, path) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, path, _options, root, isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, path, _diagnosticOptions) End If End Function Public Overrides Function WithDiagnosticOptions(options As ImmutableDictionary(Of String, ReportDiagnostic)) As SyntaxTree If options Is Nothing Then options = EmptyDiagnosticOptions End If If ReferenceEquals(_diagnosticOptions, options) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, _path, _options, root, isMyTemplate:=False, options, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, _path, options) End If End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports System.Threading Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic Partial Public Class VisualBasicSyntaxTree Private NotInheritable Class LazySyntaxTree Inherits VisualBasicSyntaxTree Private ReadOnly _text As SourceText Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _path As String Private ReadOnly _diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Private _lazyRoot As VisualBasicSyntaxNode ''' <summary> ''' Used to create new tree incrementally. ''' </summary> Friend Sub New(text As SourceText, options As VisualBasicParseOptions, path As String, diagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic)) Debug.Assert(options IsNot Nothing) _text = text _options = options _path = If(path, String.Empty) _diagnosticOptions = If(diagnosticOptions, EmptyDiagnosticOptions) End Sub Public Overrides ReadOnly Property FilePath As String Get Return _path End Get End Property Friend Overrides ReadOnly Property IsMyTemplate As Boolean Get Return False End Get End Property Public Overrides Function GetText(Optional cancellationToken As CancellationToken = Nothing) As SourceText Return _text End Function Public Overrides Function TryGetText(ByRef text As SourceText) As Boolean text = _text Return True End Function Public Overrides ReadOnly Property Encoding As Encoding Get Return _text.Encoding End Get End Property Public Overrides ReadOnly Property Length As Integer Get Return _text.Length End Get End Property Public Overrides Function GetRoot(Optional cancellationToken As CancellationToken = Nothing) As VisualBasicSyntaxNode If _lazyRoot Is Nothing Then ' Parse the syntax tree Dim tree = SyntaxFactory.ParseSyntaxTree(_text, _options, _path, cancellationToken) Dim root = CloneNodeAsRoot(CType(tree.GetRoot(cancellationToken), VisualBasicSyntaxNode)) Interlocked.CompareExchange(_lazyRoot, root, Nothing) End If Return _lazyRoot End Function Public Overrides Function TryGetRoot(ByRef root As VisualBasicSyntaxNode) As Boolean root = _lazyRoot Return root IsNot Nothing End Function Public Overrides ReadOnly Property HasCompilationUnitRoot As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Public Overrides ReadOnly Property DiagnosticOptions As ImmutableDictionary(Of String, ReportDiagnostic) Get Return _diagnosticOptions End Get End Property ''' <summary> ''' Get a reference to the given node. ''' </summary> Public Overrides Function GetReference(node As SyntaxNode) As SyntaxReference Return New SimpleSyntaxReference(Me, node) End Function Public Overrides Function WithRootAndOptions(root As SyntaxNode, options As ParseOptions) As SyntaxTree If _lazyRoot Is root AndAlso _options Is options Then Return Me End If Return New ParsedSyntaxTree( Nothing, _text.Encoding, _text.ChecksumAlgorithm, _path, DirectCast(options, VisualBasicParseOptions), DirectCast(root, VisualBasicSyntaxNode), isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) End Function Public Overrides Function WithFilePath(path As String) As SyntaxTree If String.Equals(Me._path, path) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, path, _options, root, isMyTemplate:=False, _diagnosticOptions, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, path, _diagnosticOptions) End If End Function Public Overrides Function WithDiagnosticOptions(options As ImmutableDictionary(Of String, ReportDiagnostic)) As SyntaxTree If options Is Nothing Then options = EmptyDiagnosticOptions End If If ReferenceEquals(_diagnosticOptions, options) Then Return Me End If Dim root As VisualBasicSyntaxNode = Nothing If TryGetRoot(root) Then Return New ParsedSyntaxTree( _text, _text.Encoding, _text.ChecksumAlgorithm, _path, _options, root, isMyTemplate:=False, options, cloneRoot:=True) Else Return New LazySyntaxTree(_text, _options, _path, options) End If End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Test/Syntax/Syntax/SyntaxTreeTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestHelpers Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class VisualBasicSyntaxTreeTests ' Diagnostic options on syntax trees are now obsolete #Disable warning BC40000 <Fact> Public Sub CreateTreeWithDiagnosticOptions() Dim options = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim tree = VisualBasicSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), diagnosticOptions:=options) Assert.Same(options, tree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeWithChangesPreservesDiagnosticOptions() Dim options = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=options) Assert.Same(options, tree.DiagnosticOptions) Dim newTree = tree.WithChangedText(SourceText.From("Class B : End Class")) Assert.Same(options, newTree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeNullDiagnosticOptions() Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=Nothing) Assert.NotNull(tree.DiagnosticOptions) Assert.True(tree.DiagnosticOptions.IsEmpty) ' The default options are case insensitive but the default empty ImmutableDictionary is not Assert.NotSame(ImmutableDictionary(Of String, ReportDiagnostic).Empty, tree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeEmptyDiagnosticOptions() Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=ImmutableDictionary(Of String, ReportDiagnostic).Empty) Assert.NotNull(tree.DiagnosticOptions) Assert.True(tree.DiagnosticOptions.IsEmpty) Assert.Same(ImmutableDictionary(Of String, ReportDiagnostic).Empty, tree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeCustomDiagnosticOptions() Dim options = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=options) Assert.Same(options, tree.DiagnosticOptions) End Sub <Fact> Public Sub DefaultTreeDiagnosticOptions() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Assert.NotNull(tree.DiagnosticOptions) Assert.True(tree.DiagnosticOptions.IsEmpty) End Sub <Fact> Public Sub WithDiagnosticOptionsNull() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Dim newTree = tree.WithDiagnosticOptions(Nothing) Assert.NotNull(newTree.DiagnosticOptions) Assert.True(newTree.DiagnosticOptions.IsEmpty) Assert.Same(tree, newTree) End Sub <Fact> Public Sub WithDiagnosticOptionsEmpty() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Dim newTree = tree.WithDiagnosticOptions(ImmutableDictionary(Of String, ReportDiagnostic).Empty) Assert.NotNull(tree.DiagnosticOptions) Assert.True(newTree.DiagnosticOptions.IsEmpty) ' Default empty immutable dictionary is not case insensitive Assert.NotSame(tree.DiagnosticOptions, newTree.DiagnosticOptions) End Sub <Fact> Public Sub PerTreeDiagnosticOptionsNewDict() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Dim map = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim newTree = tree.WithDiagnosticOptions(map) Assert.NotNull(newTree.DiagnosticOptions) Assert.Same(map, newTree.DiagnosticOptions) Assert.NotEqual(tree, newTree) End Sub #Enable warning BC40000 <Fact> Public Sub WithRootAndOptions_ParsedTree() Dim oldTree = SyntaxFactory.ParseSyntaxTree("Class B : End Class") Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class") Dim newOptions = New VisualBasicParseOptions() Dim newTree = oldTree.WithRootAndOptions(newRoot, newOptions) Dim newText = newTree.GetText() Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()) Assert.Same(newOptions, newTree.Options) Assert.Null(newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithRootAndOptions_ParsedTreeWithText() Dim oldText = SourceText.From("Class B : End Class", Encoding.Unicode, SourceHashAlgorithm.Sha256) Dim oldTree = SyntaxFactory.ParseSyntaxTree(oldText) Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class") Dim newOptions = New VisualBasicParseOptions() Dim newTree = oldTree.WithRootAndOptions(newRoot, newOptions) Dim newText = newTree.GetText() Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()) Assert.Same(newOptions, newTree.Options) Assert.Same(Encoding.Unicode, newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithRootAndOptions_DummyTree() Dim dummy = New VisualBasicSyntaxTree.DummySyntaxTree() Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class") Dim newOptions = New VisualBasicParseOptions() Dim newTree = dummy.WithRootAndOptions(newRoot, newOptions) Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()) Assert.Same(newOptions, newTree.Options) End Sub <Fact> Public Sub WithFilePath_ParsedTree() Dim oldTree = SyntaxFactory.ParseSyntaxTree("Class B : End Class", path:="old.vb") Dim newTree = oldTree.WithFilePath("new.vb") Dim newText = newTree.GetText() Assert.Equal(newTree.FilePath, "new.vb") Assert.Equal(oldTree.ToString(), newTree.ToString()) Assert.Null(newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithFilePath_ParsedTreeWithText() Dim oldText = SourceText.From("Class B : End Class", Encoding.Unicode, SourceHashAlgorithm.Sha256) Dim oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path:="old.vb") Dim newTree = oldTree.WithFilePath("new.vb") Dim newText = newTree.GetText() Assert.Equal(newTree.FilePath, "new.vb") Assert.Equal(oldTree.ToString(), newTree.ToString()) Assert.Same(Encoding.Unicode, newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithFilePath_DummyTree() Dim oldTree = New VisualBasicSyntaxTree.DummySyntaxTree() Dim newTree = oldTree.WithFilePath("new.vb") Assert.Equal(newTree.FilePath, "new.vb") Assert.Equal(oldTree.ToString(), newTree.ToString()) End Sub <Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")> Public Sub WithFilePath_Nothing() Dim oldTree As SyntaxTree = New VisualBasicSyntaxTree.DummySyntaxTree() Assert.Equal(String.Empty, oldTree.WithFilePath(Nothing).FilePath) oldTree = SyntaxFactory.ParseSyntaxTree("", path:="old.vb") Assert.Equal(String.Empty, oldTree.WithFilePath(Nothing).FilePath) Assert.Equal(String.Empty, SyntaxFactory.ParseSyntaxTree("", path:=Nothing).FilePath) Assert.Equal(String.Empty, VisualBasicSyntaxTree.Create(CType(oldTree.GetRoot, VisualBasicSyntaxNode), path:=Nothing).FilePath) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Text Imports Microsoft.CodeAnalysis.Text Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestHelpers Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class VisualBasicSyntaxTreeTests ' Diagnostic options on syntax trees are now obsolete #Disable warning BC40000 <Fact> Public Sub CreateTreeWithDiagnosticOptions() Dim options = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim tree = VisualBasicSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), diagnosticOptions:=options) Assert.Same(options, tree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeWithChangesPreservesDiagnosticOptions() Dim options = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=options) Assert.Same(options, tree.DiagnosticOptions) Dim newTree = tree.WithChangedText(SourceText.From("Class B : End Class")) Assert.Same(options, newTree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeNullDiagnosticOptions() Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=Nothing) Assert.NotNull(tree.DiagnosticOptions) Assert.True(tree.DiagnosticOptions.IsEmpty) ' The default options are case insensitive but the default empty ImmutableDictionary is not Assert.NotSame(ImmutableDictionary(Of String, ReportDiagnostic).Empty, tree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeEmptyDiagnosticOptions() Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=ImmutableDictionary(Of String, ReportDiagnostic).Empty) Assert.NotNull(tree.DiagnosticOptions) Assert.True(tree.DiagnosticOptions.IsEmpty) Assert.Same(ImmutableDictionary(Of String, ReportDiagnostic).Empty, tree.DiagnosticOptions) End Sub <Fact> Public Sub ParseTreeCustomDiagnosticOptions() Dim options = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim tree = VisualBasicSyntaxTree.ParseText( SourceText.From(""), diagnosticOptions:=options) Assert.Same(options, tree.DiagnosticOptions) End Sub <Fact> Public Sub DefaultTreeDiagnosticOptions() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Assert.NotNull(tree.DiagnosticOptions) Assert.True(tree.DiagnosticOptions.IsEmpty) End Sub <Fact> Public Sub WithDiagnosticOptionsNull() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Dim newTree = tree.WithDiagnosticOptions(Nothing) Assert.NotNull(newTree.DiagnosticOptions) Assert.True(newTree.DiagnosticOptions.IsEmpty) Assert.Same(tree, newTree) End Sub <Fact> Public Sub WithDiagnosticOptionsEmpty() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Dim newTree = tree.WithDiagnosticOptions(ImmutableDictionary(Of String, ReportDiagnostic).Empty) Assert.NotNull(tree.DiagnosticOptions) Assert.True(newTree.DiagnosticOptions.IsEmpty) ' Default empty immutable dictionary is not case insensitive Assert.NotSame(tree.DiagnosticOptions, newTree.DiagnosticOptions) End Sub <Fact> Public Sub PerTreeDiagnosticOptionsNewDict() Dim tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()) Dim map = CreateImmutableDictionary(("BC000", ReportDiagnostic.Suppress)) Dim newTree = tree.WithDiagnosticOptions(map) Assert.NotNull(newTree.DiagnosticOptions) Assert.Same(map, newTree.DiagnosticOptions) Assert.NotEqual(tree, newTree) End Sub #Enable warning BC40000 <Fact> Public Sub WithRootAndOptions_ParsedTree() Dim oldTree = SyntaxFactory.ParseSyntaxTree("Class B : End Class") Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class") Dim newOptions = New VisualBasicParseOptions() Dim newTree = oldTree.WithRootAndOptions(newRoot, newOptions) Dim newText = newTree.GetText() Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()) Assert.Same(newOptions, newTree.Options) Assert.Null(newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithRootAndOptions_ParsedTreeWithText() Dim oldText = SourceText.From("Class B : End Class", Encoding.Unicode, SourceHashAlgorithm.Sha256) Dim oldTree = SyntaxFactory.ParseSyntaxTree(oldText) Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class") Dim newOptions = New VisualBasicParseOptions() Dim newTree = oldTree.WithRootAndOptions(newRoot, newOptions) Dim newText = newTree.GetText() Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()) Assert.Same(newOptions, newTree.Options) Assert.Same(Encoding.Unicode, newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithRootAndOptions_DummyTree() Dim dummy = New VisualBasicSyntaxTree.DummySyntaxTree() Dim newRoot = SyntaxFactory.ParseCompilationUnit("Class C : End Class") Dim newOptions = New VisualBasicParseOptions() Dim newTree = dummy.WithRootAndOptions(newRoot, newOptions) Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()) Assert.Same(newOptions, newTree.Options) End Sub <Fact> Public Sub WithFilePath_ParsedTree() Dim oldTree = SyntaxFactory.ParseSyntaxTree("Class B : End Class", path:="old.vb") Dim newTree = oldTree.WithFilePath("new.vb") Dim newText = newTree.GetText() Assert.Equal(newTree.FilePath, "new.vb") Assert.Equal(oldTree.ToString(), newTree.ToString()) Assert.Null(newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithFilePath_ParsedTreeWithText() Dim oldText = SourceText.From("Class B : End Class", Encoding.Unicode, SourceHashAlgorithm.Sha256) Dim oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path:="old.vb") Dim newTree = oldTree.WithFilePath("new.vb") Dim newText = newTree.GetText() Assert.Equal(newTree.FilePath, "new.vb") Assert.Equal(oldTree.ToString(), newTree.ToString()) Assert.Same(Encoding.Unicode, newText.Encoding) Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm) End Sub <Fact> Public Sub WithFilePath_DummyTree() Dim oldTree = New VisualBasicSyntaxTree.DummySyntaxTree() Dim newTree = oldTree.WithFilePath("new.vb") Assert.Equal(newTree.FilePath, "new.vb") Assert.Equal(oldTree.ToString(), newTree.ToString()) End Sub <Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")> Public Sub WithFilePath_Nothing() Dim oldTree As SyntaxTree = New VisualBasicSyntaxTree.DummySyntaxTree() Assert.Equal(String.Empty, oldTree.WithFilePath(Nothing).FilePath) oldTree = SyntaxFactory.ParseSyntaxTree("", path:="old.vb") Assert.Equal(String.Empty, oldTree.WithFilePath(Nothing).FilePath) Assert.Equal(String.Empty, SyntaxFactory.ParseSyntaxTree("", path:=Nothing).FilePath) Assert.Equal(String.Empty, VisualBasicSyntaxTree.Create(CType(oldTree.GetRoot, VisualBasicSyntaxNode), path:=Nothing).FilePath) End Sub End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/CodeRefactorings/MoveType/AbstractMoveTypeService.Editor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { /// <summary> /// An abstract class for different edits performed by the Move Type Code Action. /// </summary> private abstract class Editor { public Editor( TService service, State state, string fileName, CancellationToken cancellationToken) { State = state; Service = service; FileName = fileName; CancellationToken = cancellationToken; } protected State State { get; } protected TService Service { get; } protected string FileName { get; } protected CancellationToken CancellationToken { get; } protected SemanticDocument SemanticDocument => State.SemanticDocument; /// <summary> /// Operations performed by CodeAction. /// </summary> public virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = await GetModifiedSolutionAsync().ConfigureAwait(false); if (solution == null) { return ImmutableArray<CodeActionOperation>.Empty; } return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solution)); } /// <summary> /// Incremental solution edits that correlate to code operations /// </summary> public abstract Task<Solution> GetModifiedSolutionAsync(); public static Editor GetEditor(MoveTypeOperationKind operationKind, TService service, State state, string fileName, CancellationToken cancellationToken) => operationKind switch { MoveTypeOperationKind.MoveType => new MoveTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameType => new RenameTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameFile => new RenameFileEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, state, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType { internal abstract partial class AbstractMoveTypeService<TService, TTypeDeclarationSyntax, TNamespaceDeclarationSyntax, TMemberDeclarationSyntax, TCompilationUnitSyntax> { /// <summary> /// An abstract class for different edits performed by the Move Type Code Action. /// </summary> private abstract class Editor { public Editor( TService service, State state, string fileName, CancellationToken cancellationToken) { State = state; Service = service; FileName = fileName; CancellationToken = cancellationToken; } protected State State { get; } protected TService Service { get; } protected string FileName { get; } protected CancellationToken CancellationToken { get; } protected SemanticDocument SemanticDocument => State.SemanticDocument; /// <summary> /// Operations performed by CodeAction. /// </summary> public virtual async Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync() { var solution = await GetModifiedSolutionAsync().ConfigureAwait(false); if (solution == null) { return ImmutableArray<CodeActionOperation>.Empty; } return ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(solution)); } /// <summary> /// Incremental solution edits that correlate to code operations /// </summary> public abstract Task<Solution> GetModifiedSolutionAsync(); public static Editor GetEditor(MoveTypeOperationKind operationKind, TService service, State state, string fileName, CancellationToken cancellationToken) => operationKind switch { MoveTypeOperationKind.MoveType => new MoveTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameType => new RenameTypeEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.RenameFile => new RenameFileEditor(service, state, fileName, cancellationToken), MoveTypeOperationKind.MoveTypeNamespaceScope => new MoveTypeNamespaceScopeEditor(service, state, fileName, cancellationToken), _ => throw ExceptionUtilities.UnexpectedValue(operationKind), }; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasic/Utilities/NavigationPointHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Friend Module NavigationPointHelpers Public Function GetNavigationPoint(text As SourceText, indentSize As Integer, eventBlock As EventBlockSyntax) As VirtualTreePoint Dim line As Integer If eventBlock.EndEventStatement Is Nothing OrElse eventBlock.EndEventStatement.IsMissing Then line = text.Lines.GetLineFromPosition(GetHeaderStartPosition(eventBlock)).LineNumber Else line = text.Lines.GetLineFromPosition(eventBlock.EventStatement.Span.End).LineNumber + 1 End If Return GetNavigationPoint(text, indentSize, eventBlock.EventStatement, line) End Function Public Function GetNavigationPoint(text As SourceText, indentSize As Integer, methodBlock As MethodBlockBaseSyntax) As VirtualTreePoint Dim line As Integer If methodBlock.EndBlockStatement Is Nothing OrElse methodBlock.EndBlockStatement.IsMissing Then line = text.Lines.GetLineFromPosition(GetHeaderStartPosition(methodBlock)).LineNumber Else line = text.Lines.GetLineFromPosition(methodBlock.BlockStatement.Span.End).LineNumber + 1 End If Return GetNavigationPoint(text, indentSize, methodBlock.BlockStatement, line) End Function Public Function GetHeaderStartPosition(eventBlock As EventBlockSyntax) As Integer If eventBlock.EventStatement.AttributeLists.Count > 0 Then Return eventBlock.EventStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else Return eventBlock.EventStatement.SpanStart End If End Function Public Function GetHeaderStartPosition(methodBlock As MethodBlockBaseSyntax) As Integer If methodBlock.BlockStatement.Modifiers.Count > 0 Then Return methodBlock.BlockStatement.Modifiers.First().SpanStart Else Return methodBlock.BlockStatement.DeclarationKeyword.SpanStart End If End Function ' TODO: this function conflates tab size and indent size. Public Function GetNavigationPoint(text As SourceText, indentSize As Integer, beginStatement As StatementSyntax, lineNumber As Integer) As VirtualTreePoint Dim line = text.Lines(lineNumber) Dim nonWhitespaceOffset = line.GetFirstNonWhitespacePosition() If nonWhitespaceOffset.HasValue Then ' Simply go to the start of the line Return New VirtualTreePoint(beginStatement.SyntaxTree, text, nonWhitespaceOffset.Value) Else ' We have whitespace only. Compute the indent. We subtract 1 since the CompilationUnitSyntax doesn't count. Dim indents = beginStatement.Ancestors().Count() - 1 ' Compute the total column size of the current line Dim totalLineSize = line.GetColumnFromLineOffset(line.Span.Length, indentSize) Dim targetColumn As Integer = indents * indentSize ' If we need to go past the end, then we'll be in virtual space If totalLineSize < targetColumn Then Return New VirtualTreePoint(beginStatement.SyntaxTree, text, line.End, targetColumn - totalLineSize) Else Return New VirtualTreePoint(beginStatement.SyntaxTree, text, line.GetLineOffsetFromColumn(targetColumn, indentSize) + line.Start) End If End If End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Friend Module NavigationPointHelpers Public Function GetNavigationPoint(text As SourceText, indentSize As Integer, eventBlock As EventBlockSyntax) As VirtualTreePoint Dim line As Integer If eventBlock.EndEventStatement Is Nothing OrElse eventBlock.EndEventStatement.IsMissing Then line = text.Lines.GetLineFromPosition(GetHeaderStartPosition(eventBlock)).LineNumber Else line = text.Lines.GetLineFromPosition(eventBlock.EventStatement.Span.End).LineNumber + 1 End If Return GetNavigationPoint(text, indentSize, eventBlock.EventStatement, line) End Function Public Function GetNavigationPoint(text As SourceText, indentSize As Integer, methodBlock As MethodBlockBaseSyntax) As VirtualTreePoint Dim line As Integer If methodBlock.EndBlockStatement Is Nothing OrElse methodBlock.EndBlockStatement.IsMissing Then line = text.Lines.GetLineFromPosition(GetHeaderStartPosition(methodBlock)).LineNumber Else line = text.Lines.GetLineFromPosition(methodBlock.BlockStatement.Span.End).LineNumber + 1 End If Return GetNavigationPoint(text, indentSize, methodBlock.BlockStatement, line) End Function Public Function GetHeaderStartPosition(eventBlock As EventBlockSyntax) As Integer If eventBlock.EventStatement.AttributeLists.Count > 0 Then Return eventBlock.EventStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else Return eventBlock.EventStatement.SpanStart End If End Function Public Function GetHeaderStartPosition(methodBlock As MethodBlockBaseSyntax) As Integer If methodBlock.BlockStatement.Modifiers.Count > 0 Then Return methodBlock.BlockStatement.Modifiers.First().SpanStart Else Return methodBlock.BlockStatement.DeclarationKeyword.SpanStart End If End Function ' TODO: this function conflates tab size and indent size. Public Function GetNavigationPoint(text As SourceText, indentSize As Integer, beginStatement As StatementSyntax, lineNumber As Integer) As VirtualTreePoint Dim line = text.Lines(lineNumber) Dim nonWhitespaceOffset = line.GetFirstNonWhitespacePosition() If nonWhitespaceOffset.HasValue Then ' Simply go to the start of the line Return New VirtualTreePoint(beginStatement.SyntaxTree, text, nonWhitespaceOffset.Value) Else ' We have whitespace only. Compute the indent. We subtract 1 since the CompilationUnitSyntax doesn't count. Dim indents = beginStatement.Ancestors().Count() - 1 ' Compute the total column size of the current line Dim totalLineSize = line.GetColumnFromLineOffset(line.Span.Length, indentSize) Dim targetColumn As Integer = indents * indentSize ' If we need to go past the end, then we'll be in virtual space If totalLineSize < targetColumn Then Return New VirtualTreePoint(beginStatement.SyntaxTree, text, line.End, targetColumn - totalLineSize) Else Return New VirtualTreePoint(beginStatement.SyntaxTree, text, line.GetLineOffsetFromColumn(targetColumn, indentSize) + line.Start) End If End If End Function End Module End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Tools/ExternalAccess/FSharp/Completion/FSharpCommonCompletionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCommonCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, CompletionItemRules rules, FSharpGlyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string inlineDescription = null) { var roslynGlyph = glyph.HasValue ? FSharpGlyphHelpers.ConvertTo(glyph.Value) : (Glyph?)null; return CommonCompletionItem.Create( displayText, displayTextSuffix, rules, roslynGlyph, description, sortText, filterText, showsWarningIcon, properties, tags, inlineDescription); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCommonCompletionItem { public static CompletionItem Create( string displayText, string displayTextSuffix, CompletionItemRules rules, FSharpGlyph? glyph = null, ImmutableArray<SymbolDisplayPart> description = default, string sortText = null, string filterText = null, bool showsWarningIcon = false, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, string inlineDescription = null) { var roslynGlyph = glyph.HasValue ? FSharpGlyphHelpers.ConvertTo(glyph.Value) : (Glyph?)null; return CommonCompletionItem.Create( displayText, displayTextSuffix, rules, roslynGlyph, description, sortText, filterText, showsWarningIcon, properties, tags, inlineDescription); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Test/VsNavInfo/VsNavInfoTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library Imports Microsoft.VisualStudio.LanguageServices.UnitTests.Utilities.VsNavInfo Imports Microsoft.VisualStudio.Shell.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.VsNavInfo <UseExportProvider, Trait(Traits.Feature, Traits.Features.VsNavInfo)> Public Class VsNavInfoTests #Region "C# Tests" <WpfFact> Public Async Function TestCSharp_TestNamespace() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace $$N { } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N") }) End Function <WpfFact> Public Async Function TestCSharp_TestClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace N { class $$C { } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C") }) End Function <WpfFact> Public Async Function TestCSharp_TestMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace N { class C { void $$M() { } } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }) End Function <WpfFact> Public Async Function TestCSharp_TestMethod_Parameters() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace N { class C { int $$M(int x, int y) { return x + y; } } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(int, int)") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(int, int)") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Class1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { String$$ s; } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Class2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System.Text; class C { StringBuilder$$ sb; } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Ctor1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System.Text; class C { StringBuilder sb = new StringBuilder$$(); } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder"), Member("StringBuilder()") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder"), Member("StringBuilder()") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Ctor2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { String s = new String$$(' ', 42); } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("String(char, int)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("String(char, int)") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Method() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { String s = new String(' ', 42).Replace$$(' ', '\r'); } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(char, char)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(char, char)") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_GenericType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System.Collections.Generic; class C { $$List&lt;int&gt; s; } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Collections"), [Namespace]("Generic"), [Class]("List<T>") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Collections.Generic"), [Class]("List<T>") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_GenericMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { void M() { var a = new int[] { 1, 2, 3, 4, 5 }; var r = Array.AsReadOnly$$(a); } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly<T>(T[])") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly<T>(T[])") }) End Function <WpfFact> Public Async Function TestCSharp_TestNull_Parameter() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> class C { void M(int i$$) { } } </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestCSharp_TestNull_Local() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> class C { void M() { int i$$; } } </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestCSharp_TestNull_Label() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> class C { void M() { label$$: int i; } } </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function #End Region #Region "Visual Basic Tests" <WpfFact> Public Async Function TestVisualBasic_TestNamespace() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace $$N End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class $$C End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMember_Sub() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class C Sub $$M() End Sub End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMember_Function() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class C Function $$M() As Integer End Function End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M() As Integer") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M() As Integer") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMember_Parameters() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class C Function $$M(x As Integer, y As Integer) As Integer End Function End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(Integer, Integer) As Integer") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(Integer, Integer) As Integer") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Class1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System Class C Dim s As String$$ End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Class2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System.Text Class C Dim s As StringBuilder$$ End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Ctor1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System.Text Class C Dim s As New StringBuilder$$() End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder"), Member("New()") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder"), Member("New()") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Ctor2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System Class C Dim s As String = New String$$(" "c, 42) End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("New(Char, Integer)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("New(Char, Integer)") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Method() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System Class C Dim s As String = New String(" "c, 42).Replace$$(" "c, "."c) End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(Char, Char) As String") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(Char, Char) As String") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_GenericType() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System.Collections.Generic Class C Dim s As List$$(Of Integer) End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Collections"), [Namespace]("Generic"), [Class]("List(Of T)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Collections.Generic"), [Class]("List(Of T)") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_GenericMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VisualBasicTestAssembly"> <Document> Imports System Class C Sub M() Dim a = New Integer() { 1, 2, 3, 4, 5 } Dim r = Array.AsReadOnly$$(a) End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly(Of T)(T()) As System.Collections.ObjectModel.ReadOnlyCollection(Of T)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly(Of T)(T()) As System.Collections.ObjectModel.ReadOnlyCollection(Of T)") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestNull_Parameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Class C Sub M(i$$ As Integer) End Sub End Class </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestVisualBasic_TestNull_Local() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Class C Sub M() Dim i$$ As Integer End Sub End Class </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestVisualBasic_TestNull_Label() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Class C void M() { Sub M() label$$: Dim i As Integer End Sub } End Class </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function #End Region Private Shared Async Function TestAsync( workspaceDefinition As XElement, Optional useExpandedHierarchy As Boolean = False, Optional canonicalNodes As NodeVerifier() = Nothing, Optional presentationNodes As NodeVerifier() = Nothing ) As Task Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=VisualStudioTestCompositions.LanguageServices) Dim hostDocument = workspace.DocumentWithCursor Assert.True(hostDocument IsNot Nothing, "Test defined without cursor position") Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim position As Integer = hostDocument.CursorPosition.Value Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace).ConfigureAwait(False) Assert.True(symbol IsNot Nothing, $"Could not find symbol as position, {position}") Dim libraryService = document.GetLanguageService(Of ILibraryService) Dim project = document.Project Dim compilation = Await project.GetCompilationAsync() Dim navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, compilation, useExpandedHierarchy) Assert.True(navInfo IsNot Nothing, $"Could not retrieve nav info for {symbol.ToDisplayString()}") If canonicalNodes IsNot Nothing Then Dim enumerator As IVsEnumNavInfoNodes = Nothing IsOK(navInfo.EnumCanonicalNodes(enumerator)) VerifyNodes(enumerator, canonicalNodes) End If If presentationNodes IsNot Nothing Then Dim enumerator As IVsEnumNavInfoNodes = Nothing IsOK(navInfo.EnumPresentationNodes(CUInt(_LIB_LISTFLAGS.LLF_NONE), enumerator)) VerifyNodes(enumerator, presentationNodes) End If End Using End Function Private Shared Async Function TestIsNullAsync( workspaceDefinition As XElement, Optional useExpandedHierarchy As Boolean = False ) As Task Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=VisualStudioTestCompositions.LanguageServices) Dim hostDocument = workspace.DocumentWithCursor Assert.True(hostDocument IsNot Nothing, "Test defined without cursor position") Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim position As Integer = hostDocument.CursorPosition.Value Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace).ConfigureAwait(False) Assert.True(symbol IsNot Nothing, $"Could not find symbol as position, {position}") Dim libraryService = document.GetLanguageService(Of ILibraryService) Dim project = document.Project Dim compilation = Await project.GetCompilationAsync() Dim navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, compilation, useExpandedHierarchy) Assert.Null(navInfo) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.FindSymbols Imports Microsoft.CodeAnalysis.Shared.Extensions Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.LanguageServices.Implementation.Library Imports Microsoft.VisualStudio.LanguageServices.UnitTests.Utilities.VsNavInfo Imports Microsoft.VisualStudio.Shell.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.VsNavInfo <UseExportProvider, Trait(Traits.Feature, Traits.Features.VsNavInfo)> Public Class VsNavInfoTests #Region "C# Tests" <WpfFact> Public Async Function TestCSharp_TestNamespace() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace $$N { } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N") }) End Function <WpfFact> Public Async Function TestCSharp_TestClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace N { class $$C { } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C") }) End Function <WpfFact> Public Async Function TestCSharp_TestMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace N { class C { void $$M() { } } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }) End Function <WpfFact> Public Async Function TestCSharp_TestMethod_Parameters() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> namespace N { class C { int $$M(int x, int y) { return x + y; } } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(int, int)") }, presentationNodes:={ Package("CSharpTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(int, int)") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Class1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { String$$ s; } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Class2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System.Text; class C { StringBuilder$$ sb; } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Ctor1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System.Text; class C { StringBuilder sb = new StringBuilder$$(); } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder"), Member("StringBuilder()") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder"), Member("StringBuilder()") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Ctor2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { String s = new String$$(' ', 42); } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("String(char, int)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("String(char, int)") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_Method() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { String s = new String(' ', 42).Replace$$(' ', '\r'); } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(char, char)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(char, char)") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_GenericType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System.Collections.Generic; class C { $$List&lt;int&gt; s; } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Collections"), [Namespace]("Generic"), [Class]("List<T>") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Collections.Generic"), [Class]("List<T>") }) End Function <WpfFact> Public Async Function TestCSharp_TestMetadata_GenericMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> using System; class C { void M() { var a = new int[] { 1, 2, 3, 4, 5 }; var r = Array.AsReadOnly$$(a); } } </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly<T>(T[])") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly<T>(T[])") }) End Function <WpfFact> Public Async Function TestCSharp_TestNull_Parameter() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> class C { void M(int i$$) { } } </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestCSharp_TestNull_Local() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> class C { void M() { int i$$; } } </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestCSharp_TestNull_Label() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSharpTestAssembly"> <Document> class C { void M() { label$$: int i; } } </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function #End Region #Region "Visual Basic Tests" <WpfFact> Public Async Function TestVisualBasic_TestNamespace() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace $$N End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class $$C End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMember_Sub() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class C Sub $$M() End Sub End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M()") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMember_Function() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class C Function $$M() As Integer End Function End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M() As Integer") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M() As Integer") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMember_Parameters() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Namespace N Class C Function $$M(x As Integer, y As Integer) As Integer End Function End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(Integer, Integer) As Integer") }, presentationNodes:={ Package("VBTestAssembly"), [Namespace]("N"), [Class]("C"), Member("M(Integer, Integer) As Integer") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Class1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System Class C Dim s As String$$ End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Class2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System.Text Class C Dim s As StringBuilder$$ End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Ctor1() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System.Text Class C Dim s As New StringBuilder$$() End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Text"), [Class]("StringBuilder"), Member("New()") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Text"), [Class]("StringBuilder"), Member("New()") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Ctor2() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System Class C Dim s As String = New String$$(" "c, 42) End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("New(Char, Integer)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("New(Char, Integer)") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_Method() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System Class C Dim s As String = New String(" "c, 42).Replace$$(" "c, "."c) End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(Char, Char) As String") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("String"), Member("Replace(Char, Char) As String") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_GenericType() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Imports System.Collections.Generic Class C Dim s As List$$(Of Integer) End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Namespace]("Collections"), [Namespace]("Generic"), [Class]("List(Of T)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System.Collections.Generic"), [Class]("List(Of T)") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestMetadata_GenericMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VisualBasicTestAssembly"> <Document> Imports System Class C Sub M() Dim a = New Integer() { 1, 2, 3, 4, 5 } Dim r = Array.AsReadOnly$$(a) End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace, canonicalNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly(Of T)(T()) As System.Collections.ObjectModel.ReadOnlyCollection(Of T)") }, presentationNodes:={ Package("Z:\FxReferenceAssembliesUri"), [Namespace]("System"), [Class]("Array"), Member("AsReadOnly(Of T)(T()) As System.Collections.ObjectModel.ReadOnlyCollection(Of T)") }) End Function <WpfFact> Public Async Function TestVisualBasic_TestNull_Parameter() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Class C Sub M(i$$ As Integer) End Sub End Class </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestVisualBasic_TestNull_Local() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Class C Sub M() Dim i$$ As Integer End Sub End Class </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function <WpfFact> Public Async Function TestVisualBasic_TestNull_Label() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBTestAssembly"> <Document> Class C void M() { Sub M() label$$: Dim i As Integer End Sub } End Class </Document> </Project> </Workspace> Await TestIsNullAsync(workspace) End Function #End Region Private Shared Async Function TestAsync( workspaceDefinition As XElement, Optional useExpandedHierarchy As Boolean = False, Optional canonicalNodes As NodeVerifier() = Nothing, Optional presentationNodes As NodeVerifier() = Nothing ) As Task Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=VisualStudioTestCompositions.LanguageServices) Dim hostDocument = workspace.DocumentWithCursor Assert.True(hostDocument IsNot Nothing, "Test defined without cursor position") Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim position As Integer = hostDocument.CursorPosition.Value Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace).ConfigureAwait(False) Assert.True(symbol IsNot Nothing, $"Could not find symbol as position, {position}") Dim libraryService = document.GetLanguageService(Of ILibraryService) Dim project = document.Project Dim compilation = Await project.GetCompilationAsync() Dim navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, compilation, useExpandedHierarchy) Assert.True(navInfo IsNot Nothing, $"Could not retrieve nav info for {symbol.ToDisplayString()}") If canonicalNodes IsNot Nothing Then Dim enumerator As IVsEnumNavInfoNodes = Nothing IsOK(navInfo.EnumCanonicalNodes(enumerator)) VerifyNodes(enumerator, canonicalNodes) End If If presentationNodes IsNot Nothing Then Dim enumerator As IVsEnumNavInfoNodes = Nothing IsOK(navInfo.EnumPresentationNodes(CUInt(_LIB_LISTFLAGS.LLF_NONE), enumerator)) VerifyNodes(enumerator, presentationNodes) End If End Using End Function Private Shared Async Function TestIsNullAsync( workspaceDefinition As XElement, Optional useExpandedHierarchy As Boolean = False ) As Task Using workspace = TestWorkspace.Create(workspaceDefinition, composition:=VisualStudioTestCompositions.LanguageServices) Dim hostDocument = workspace.DocumentWithCursor Assert.True(hostDocument IsNot Nothing, "Test defined without cursor position") Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim position As Integer = hostDocument.CursorPosition.Value Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(semanticModel, position, workspace).ConfigureAwait(False) Assert.True(symbol IsNot Nothing, $"Could not find symbol as position, {position}") Dim libraryService = document.GetLanguageService(Of ILibraryService) Dim project = document.Project Dim compilation = Await project.GetCompilationAsync() Dim navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, compilation, useExpandedHierarchy) Assert.Null(navInfo) End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/AddImport/SymbolResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private readonly struct SearchResult { public readonly IReadOnlyList<string> NameParts; // How good a match this was. 0 means it was a perfect match. Larger numbers are less // and less good. public readonly double Weight; // The desired name to change the user text to if this was a fuzzy (spell-checking) match. public readonly string? DesiredName; // The node to convert to the desired name public readonly TSimpleNameSyntax NameNode; public SearchResult(SymbolResult<INamespaceOrTypeSymbol> result) : this(result.DesiredName, result.NameNode, INamespaceOrTypeSymbolExtensions.GetNameParts(result.Symbol), result.Weight) { } public SearchResult(string? desiredName, TSimpleNameSyntax nameNode, IReadOnlyList<string> nameParts, double weight) { DesiredName = desiredName; Weight = weight; NameNode = nameNode; NameParts = nameParts; } public bool DesiredNameDiffersFromSourceName() { return !string.IsNullOrEmpty(DesiredName) && NameNode != null && NameNode.GetFirstToken().ValueText != DesiredName; } public bool DesiredNameDiffersFromSourceNameOnlyByCase() { Debug.Assert(DesiredNameDiffersFromSourceName()); return StringComparer.OrdinalIgnoreCase.Equals( NameNode.GetFirstToken().ValueText, DesiredName); } public bool DesiredNameMatchesSourceName(Document document) { if (!DesiredNameDiffersFromSourceName()) { // Names match in any language. return true; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Names differ. But in a case insensitive language they may match. if (!syntaxFacts.IsCaseSensitive && DesiredNameDiffersFromSourceNameOnlyByCase()) { return true; } // Name are totally different in any language. return false; } } private readonly struct SymbolResult<T> where T : ISymbol { // The symbol that matched the string being searched for. public readonly T Symbol; // How good a match this was. 0 means it was a perfect match. Larger numbers are less // and less good. public readonly double Weight; // The desired name to change the user text to if this was a fuzzy (spell-checking) match. public readonly string DesiredName; // The node to convert to the desired name public readonly TSimpleNameSyntax NameNode; public SymbolResult(string desiredName, TSimpleNameSyntax nameNode, T symbol, double weight) { DesiredName = desiredName; Symbol = symbol; Weight = weight; NameNode = nameNode; } public SymbolResult<T2> WithSymbol<T2>(T2 symbol) where T2 : ISymbol => new(DesiredName, NameNode, symbol, Weight); internal SymbolResult<T> WithDesiredName(string desiredName) => new(desiredName, NameNode, Symbol, Weight); } private struct SymbolResult { public static SymbolResult<T> Create<T>(string desiredName, TSimpleNameSyntax nameNode, T symbol, double weight) where T : ISymbol => new(desiredName, nameNode, symbol, weight); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private readonly struct SearchResult { public readonly IReadOnlyList<string> NameParts; // How good a match this was. 0 means it was a perfect match. Larger numbers are less // and less good. public readonly double Weight; // The desired name to change the user text to if this was a fuzzy (spell-checking) match. public readonly string? DesiredName; // The node to convert to the desired name public readonly TSimpleNameSyntax NameNode; public SearchResult(SymbolResult<INamespaceOrTypeSymbol> result) : this(result.DesiredName, result.NameNode, INamespaceOrTypeSymbolExtensions.GetNameParts(result.Symbol), result.Weight) { } public SearchResult(string? desiredName, TSimpleNameSyntax nameNode, IReadOnlyList<string> nameParts, double weight) { DesiredName = desiredName; Weight = weight; NameNode = nameNode; NameParts = nameParts; } public bool DesiredNameDiffersFromSourceName() { return !string.IsNullOrEmpty(DesiredName) && NameNode != null && NameNode.GetFirstToken().ValueText != DesiredName; } public bool DesiredNameDiffersFromSourceNameOnlyByCase() { Debug.Assert(DesiredNameDiffersFromSourceName()); return StringComparer.OrdinalIgnoreCase.Equals( NameNode.GetFirstToken().ValueText, DesiredName); } public bool DesiredNameMatchesSourceName(Document document) { if (!DesiredNameDiffersFromSourceName()) { // Names match in any language. return true; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); // Names differ. But in a case insensitive language they may match. if (!syntaxFacts.IsCaseSensitive && DesiredNameDiffersFromSourceNameOnlyByCase()) { return true; } // Name are totally different in any language. return false; } } private readonly struct SymbolResult<T> where T : ISymbol { // The symbol that matched the string being searched for. public readonly T Symbol; // How good a match this was. 0 means it was a perfect match. Larger numbers are less // and less good. public readonly double Weight; // The desired name to change the user text to if this was a fuzzy (spell-checking) match. public readonly string DesiredName; // The node to convert to the desired name public readonly TSimpleNameSyntax NameNode; public SymbolResult(string desiredName, TSimpleNameSyntax nameNode, T symbol, double weight) { DesiredName = desiredName; Symbol = symbol; Weight = weight; NameNode = nameNode; } public SymbolResult<T2> WithSymbol<T2>(T2 symbol) where T2 : ISymbol => new(DesiredName, NameNode, symbol, Weight); internal SymbolResult<T> WithDesiredName(string desiredName) => new(desiredName, NameNode, Symbol, Weight); } private struct SymbolResult { public static SymbolResult<T> Create<T>(string desiredName, TSimpleNameSyntax nameNode, T symbol, double weight) where T : ISymbol => new(desiredName, nameNode, symbol, weight); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Core/Implementation/Interactive/InteractiveEvaluatorLanguageInfoProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal abstract class InteractiveEvaluatorLanguageInfoProvider { public abstract string LanguageName { get; } public abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports); public abstract ParseOptions ParseOptions { get; } public abstract CommandLineParser CommandLineParser { get; } public abstract bool IsCompleteSubmission(string text); public abstract string InteractiveResponseFileName { get; } public abstract Type ReplServiceProviderType { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Editor.Interactive { internal abstract class InteractiveEvaluatorLanguageInfoProvider { public abstract string LanguageName { get; } public abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports); public abstract ParseOptions ParseOptions { get; } public abstract CommandLineParser CommandLineParser { get; } public abstract bool IsCompleteSubmission(string text); public abstract string InteractiveResponseFileName { get; } public abstract Type ReplServiceProviderType { get; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/PDB/ImportRecord.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct ImportRecord { public readonly ImportTargetKind TargetKind; public readonly string? Alias; // target type of a type import (C#) public readonly ITypeSymbolInternal? TargetType; // target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB) public readonly string? TargetString; // target assembly of a namespace import (C#, Portable) public readonly IAssemblySymbolInternal? TargetAssembly; // target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB) public readonly string? TargetAssemblyAlias; public ImportRecord( ImportTargetKind targetKind, string? alias = null, ITypeSymbolInternal? targetType = null, string? targetString = null, IAssemblySymbolInternal? targetAssembly = null, string? targetAssemblyAlias = null) { TargetKind = targetKind; Alias = alias; TargetType = targetType; TargetString = targetString; TargetAssembly = targetAssembly; TargetAssemblyAlias = targetAssemblyAlias; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Debugging; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct ImportRecord { public readonly ImportTargetKind TargetKind; public readonly string? Alias; // target type of a type import (C#) public readonly ITypeSymbolInternal? TargetType; // target of an import (type, namespace or XML namespace) that needs to be bound (C#, VB) public readonly string? TargetString; // target assembly of a namespace import (C#, Portable) public readonly IAssemblySymbolInternal? TargetAssembly; // target assembly of a namespace import is identified by an extern alias which needs to be bound in the context (C#, native PDB) public readonly string? TargetAssemblyAlias; public ImportRecord( ImportTargetKind targetKind, string? alias = null, ITypeSymbolInternal? targetType = null, string? targetString = null, IAssemblySymbolInternal? targetAssembly = null, string? targetAssemblyAlias = null) { TargetKind = targetKind; Alias = alias; TargetType = targetType; TargetString = targetString; TargetAssembly = targetAssembly; TargetAssemblyAlias = targetAssemblyAlias; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Portable/Binding/Binder_Operators.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of binary and unary operators is implemented in this part. Partial Friend Class Binder Private Function BindIsExpression( node As BinaryExpressionSyntax, diagnostics As BindingDiagnosticBag ) As BoundExpression Debug.Assert(node.Kind = SyntaxKind.IsExpression OrElse node.Kind = SyntaxKind.IsNotExpression) Dim [isNot] As Boolean = (node.Kind = SyntaxKind.IsNotExpression) ' The function below will make sure they are RValues. Dim left As BoundExpression = BindExpression(node.Left, diagnostics) Dim right As BoundExpression = BindExpression(node.Right, diagnostics) Return BindIsExpression(left, right, node, [isNot], diagnostics) End Function Private Function BindIsExpression( left As BoundExpression, right As BoundExpression, node As SyntaxNode, [isNot] As Boolean, diagnostics As BindingDiagnosticBag ) As BoundExpression left = MakeRValue(left, diagnostics) right = MakeRValue(right, diagnostics) left = ValidateAndConvertIsExpressionArgument(left, right, [isNot], diagnostics) right = ValidateAndConvertIsExpressionArgument(right, left, [isNot], diagnostics) Dim result As BoundExpression Dim booleanType = GetSpecialType(SpecialType.System_Boolean, node, diagnostics) result = New BoundBinaryOperator(node, If([isNot], BinaryOperatorKind.IsNot, BinaryOperatorKind.Is), left, right, checked:=False, type:=booleanType, hasErrors:=booleanType.IsErrorType()) ' TODO: Add rewrite for Nullable. Return result End Function ''' <summary> ''' Validate and apply appropriate conversion for the target argument of Is/IsNot expression. ''' </summary> Private Function ValidateAndConvertIsExpressionArgument( targetArgument As BoundExpression, otherArgument As BoundExpression, [isNot] As Boolean, diagnostics As BindingDiagnosticBag ) As BoundExpression Dim targetArgumentType As TypeSymbol = targetArgument.Type Dim result As BoundExpression If targetArgument.IsNothingLiteral() Then result = targetArgument ElseIf targetArgumentType.IsErrorType() Then result = targetArgument ElseIf targetArgumentType.IsReferenceType Then result = ApplyImplicitConversion(targetArgument.Syntax, GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics), targetArgument, diagnostics) ElseIf targetArgumentType.IsNullableType() Then If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then ReportDiagnostic(diagnostics, targetArgument.Syntax, If([isNot], ERRID.ERR_IsNotOperatorNullable1, ERRID.ERR_IsOperatorNullable1), targetArgumentType) End If result = targetArgument ElseIf targetArgumentType.IsTypeParameter() AndAlso Not targetArgumentType.IsValueType Then If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then ReportDiagnostic(diagnostics, targetArgument.Syntax, If([isNot], ERRID.ERR_IsNotOperatorGenericParam1, ERRID.ERR_IsOperatorGenericParam1), targetArgumentType) End If ' If any of the left or right operands of the Is or IsNot operands ' are entities of type parameters types, then they need to be boxed. result = ApplyImplicitConversion(targetArgument.Syntax, GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics), targetArgument, diagnostics) Else ReportDiagnostic(diagnostics, targetArgument.Syntax, If([isNot], ERRID.ERR_IsNotOpRequiresReferenceTypes1, ERRID.ERR_IsOperatorRequiresReferenceTypes1), targetArgumentType) result = targetArgument End If Return result End Function Private Function BindBinaryOperator( node As BinaryExpressionSyntax, isOperandOfConditionalBranch As Boolean, diagnostics As BindingDiagnosticBag ) As BoundExpression ' Some tools, such as ASP .NET, generate expressions containing thousands ' of string concatenations. For this reason, for string concatenations, ' avoid the usual recursion along the left side of the parse. Also, attempt ' to flatten whole sequences of string literal concatenations to avoid ' allocating space for intermediate results. Dim preliminaryOperatorKind As BinaryOperatorKind = OverloadResolution.MapBinaryOperatorKind(node.Kind) Dim propagateIsOperandOfConditionalBranch = isOperandOfConditionalBranch AndAlso (preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse preliminaryOperatorKind = BinaryOperatorKind.OrElse) Dim binary As BinaryExpressionSyntax = node Dim child As ExpressionSyntax Do child = binary.Left Select Case child.Kind Case SyntaxKind.AddExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.LikeExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.OrExpression, SyntaxKind.AndExpression If propagateIsOperandOfConditionalBranch Then Exit Do End If Case SyntaxKind.OrElseExpression, SyntaxKind.AndAlsoExpression Exit Select Case Else Exit Do End Select binary = DirectCast(child, BinaryExpressionSyntax) Loop Dim left As BoundExpression = BindValue(child, diagnostics, propagateIsOperandOfConditionalBranch) Do binary = DirectCast(child.Parent, BinaryExpressionSyntax) Dim right As BoundExpression = BindValue(binary.Right, diagnostics, propagateIsOperandOfConditionalBranch) left = BindBinaryOperator(binary, left, right, binary.OperatorToken.Kind, OverloadResolution.MapBinaryOperatorKind(binary.Kind), If(binary Is node, isOperandOfConditionalBranch, propagateIsOperandOfConditionalBranch), diagnostics) child = binary Loop While child IsNot node Return left End Function Private Function BindBinaryOperator( node As SyntaxNode, left As BoundExpression, right As BoundExpression, operatorTokenKind As SyntaxKind, preliminaryOperatorKind As BinaryOperatorKind, isOperandOfConditionalBranch As Boolean, diagnostics As BindingDiagnosticBag, Optional isSelectCase As Boolean = False ) As BoundExpression Debug.Assert(left.IsValue) Debug.Assert(right.IsValue) Dim originalDiagnostics = diagnostics If (left.HasErrors OrElse right.HasErrors) Then ' Suppress any additional diagnostics by overriding DiagnosticBag. diagnostics = BindingDiagnosticBag.Discarded End If ' Deal with NOTHING literal as an input. ConvertNothingLiterals(preliminaryOperatorKind, left, right, diagnostics) left = MakeRValue(left, diagnostics) right = MakeRValue(right, diagnostics) If (left.HasErrors OrElse right.HasErrors) Then ' Suppress any additional diagnostics by overriding DiagnosticBag. If diagnostics Is originalDiagnostics Then diagnostics = BindingDiagnosticBag.Discarded End If End If Dim leftType As TypeSymbol = left.Type Dim rightType As TypeSymbol = right.Type Dim leftIsDBNull As Boolean = leftType.IsDBNullType() Dim rightIsDBNull As Boolean = rightType.IsDBNullType() '§11.16 Concatenation Operator 'A System.DBNull value is converted to the literal Nothing typed as String. If (preliminaryOperatorKind = BinaryOperatorKind.Concatenate AndAlso leftIsDBNull <> rightIsDBNull) OrElse (preliminaryOperatorKind = BinaryOperatorKind.Add AndAlso ((leftType.IsStringType() AndAlso rightIsDBNull) OrElse (leftIsDBNull AndAlso rightType.IsStringType))) Then Debug.Assert(leftIsDBNull Xor rightIsDBNull) If leftIsDBNull Then leftType = SubstituteDBNullWithNothingString(left, rightType, diagnostics) Else rightType = SubstituteDBNullWithNothingString(right, leftType, diagnostics) End If End If ' For comparison operators, the result type computed here is not ' the result type of the comparison (which is typically boolean), ' but is the type to which the operands are to be converted. For ' other operators, the type computed here is both the result type ' and the common operand type. Dim intrinsicOperatorType As SpecialType = SpecialType.None Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim operatorKind As BinaryOperatorKind = OverloadResolution.ResolveBinaryOperator(preliminaryOperatorKind, left, right, Me, True, intrinsicOperatorType, userDefinedOperator, useSiteInfo) If diagnostics.Add(node, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If operatorKind = BinaryOperatorKind.UserDefined Then Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue, userDefinedOperator.BestResult.Value.Candidate, Nothing) If bestCandidate Is Nothing OrElse Not bestCandidate.IsLifted OrElse (OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(1).Type) AndAlso OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then If preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse preliminaryOperatorKind = BinaryOperatorKind.OrElse Then Return BindUserDefinedShortCircuitingOperator(node, preliminaryOperatorKind, left, right, userDefinedOperator, diagnostics) Else Return BindUserDefinedNonShortCircuitingBinaryOperator(node, preliminaryOperatorKind, left, right, userDefinedOperator, diagnostics) End If End If operatorKind = BinaryOperatorKind.Error End If If operatorKind = BinaryOperatorKind.Error Then ReportUndefinedOperatorError(node, left, right, operatorTokenKind, preliminaryOperatorKind, diagnostics) Return New BoundBinaryOperator(node, preliminaryOperatorKind Or BinaryOperatorKind.Error, left, right, CheckOverflow, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If ' We are dealing with intrinsic operator ' Get the symbol for operand type Dim operandType As TypeSymbol If intrinsicOperatorType = SpecialType.None Then ' Must be a bitwise operation with enum type. Debug.Assert(leftType.GetNullableUnderlyingTypeOrSelf().IsEnumType() AndAlso leftType.GetNullableUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(rightType.GetNullableUnderlyingTypeOrSelf())) If (operatorKind And BinaryOperatorKind.Lifted) = 0 OrElse leftType.IsNullableType() Then operandType = leftType Else Debug.Assert(rightType.IsNullableType()) operandType = rightType End If Else operandType = GetSpecialTypeForBinaryOperator(node, leftType, rightType, intrinsicOperatorType, (operatorKind And BinaryOperatorKind.Lifted) <> 0, diagnostics) End If ' Get the symbol for result type Dim operatorResultType As TypeSymbol = operandType Dim forceToBooleanType As TypeSymbol = Nothing Select Case preliminaryOperatorKind Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Like If OptionCompareText AndAlso (operandType.IsObjectType() OrElse operandType.IsStringType()) Then operatorKind = operatorKind Or BinaryOperatorKind.CompareText End If If Not operatorResultType.IsObjectType() OrElse (isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like) Then Dim booleanType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Boolean, False, diagnostics) If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then operatorResultType = GetNullableTypeForBinaryOperator(leftType, rightType, booleanType) If (preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals) AndAlso (IsKnownToBeNullableNothing(left) OrElse IsKnownToBeNullableNothing(right)) Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo( If(preliminaryOperatorKind = BinaryOperatorKind.Equals, ERRID.WRN_EqualToLiteralNothing, ERRID.WRN_NotEqualToLiteralNothing))) End If Else If Not operatorResultType.IsObjectType() Then operatorResultType = booleanType Else ' I believe this is just an optimization to prevent Object from bubbling up the tree. Debug.Assert(isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like) forceToBooleanType = booleanType End If End If End If End Select If operandType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse operatorResultType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse (forceToBooleanType IsNot Nothing AndAlso forceToBooleanType.GetNullableUnderlyingTypeOrSelf().IsErrorType()) Then ' Suppress any additional diagnostics by overriding DiagnosticBag. If diagnostics Is originalDiagnostics Then diagnostics = BindingDiagnosticBag.Discarded End If End If Dim hasError As Boolean = False ' Option Strict disallows all operations on Object operands. Or, at least, warn. If OptionStrict = VisualBasic.OptionStrict.On Then Dim reportedAnEror As Boolean = False If leftType.IsObjectType Then ReportBinaryOperatorOnObject(operatorTokenKind, left, preliminaryOperatorKind, diagnostics) reportedAnEror = True End If If rightType.IsObjectType() Then ReportBinaryOperatorOnObject(operatorTokenKind, right, preliminaryOperatorKind, diagnostics) reportedAnEror = True End If If reportedAnEror Then hasError = True ' Suppress any additional diagnostics by overriding DiagnosticBag. If diagnostics Is originalDiagnostics Then diagnostics = BindingDiagnosticBag.Discarded End If End If ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then 'warn if option strict is off If Not isSelectCase OrElse preliminaryOperatorKind <> BinaryOperatorKind.OrElse Then Dim errorId = If(isSelectCase, ERRID.WRN_ObjectMathSelectCase, If(preliminaryOperatorKind = BinaryOperatorKind.Equals, ERRID.WRN_ObjectMath1, If(preliminaryOperatorKind = BinaryOperatorKind.NotEquals, ERRID.WRN_ObjectMath1Not, ERRID.WRN_ObjectMath2))) If leftType.IsObjectType Then ReportDiagnostic(diagnostics, left.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind)) End If If rightType.IsObjectType Then ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind)) End If End If End If ' Apply conversions to operands. Dim explicitSemanticForConcatArgument As Boolean = False ' Concatenation will apply conversions to its operands as if the ' conversions were explicit. Effectively, the use of the concatenation ' operator is treated as an explicit conversion to String. If preliminaryOperatorKind = BinaryOperatorKind.Concatenate Then explicitSemanticForConcatArgument = True Debug.Assert((operatorKind And BinaryOperatorKind.Lifted) = 0) If operandType.IsStringType() Then If left.Type.IsNullableType Then left = ForceLiftToEmptyString(left, operandType, diagnostics) End If If right.Type.IsNullableType Then right = ForceLiftToEmptyString(right, operandType, diagnostics) End If End If End If Dim beforeConversion As BoundExpression = left left = ApplyConversion(left.Syntax, operandType, left, explicitSemanticForConcatArgument, diagnostics, explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument) If explicitSemanticForConcatArgument AndAlso left IsNot beforeConversion AndAlso left.Kind = BoundKind.Conversion Then Dim conversion = DirectCast(left, BoundConversion) left = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False, constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt, type:=conversion.Type) End If If (preliminaryOperatorKind = BinaryOperatorKind.LeftShift OrElse preliminaryOperatorKind = BinaryOperatorKind.RightShift) AndAlso Not operandType.IsObjectType() Then Dim rightTargetType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Int32, False, diagnostics) '§11.18 Shift Operators 'The type of the right operand must be implicitly convertible to Integer ' If operator is lifted, convert right operand to Nullable(Of Integer) If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then rightTargetType = GetNullableTypeForBinaryOperator(leftType, rightType, rightTargetType) End If right = ApplyImplicitConversion(right.Syntax, rightTargetType, right, diagnostics) Else beforeConversion = right right = ApplyConversion(right.Syntax, operandType, right, explicitSemanticForConcatArgument, diagnostics, explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument) If explicitSemanticForConcatArgument AndAlso right IsNot beforeConversion AndAlso right.Kind = BoundKind.Conversion Then Dim conversion = DirectCast(right, BoundConversion) right = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False, constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt, type:=conversion.Type) End If End If If (operatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Add AndAlso operatorResultType.IsStringType() Then ' Transform the addition into a string concatenation. This won't use a runtime helper - it will turn into System.String::Concat operatorKind = (operatorKind And (Not BinaryOperatorKind.OpMask)) operatorKind = operatorKind Or BinaryOperatorKind.Concatenate End If ' Perform constant folding. Dim value As ConstantValue = Nothing If Not (left.HasErrors OrElse right.HasErrors) Then Dim integerOverflow As Boolean = False Dim divideByZero As Boolean = False Dim lengthOutOfLimit As Boolean = False value = OverloadResolution.TryFoldConstantBinaryOperator(operatorKind, left, right, operatorResultType, integerOverflow, divideByZero, lengthOutOfLimit) If value IsNot Nothing Then If divideByZero Then Debug.Assert(value.IsBad) ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ZeroDivide)) ElseIf lengthOutOfLimit Then Debug.Assert(value.IsBad) ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(ERRID.ERR_ConstantStringTooLong)) ElseIf (value.IsBad OrElse integerOverflow) Then ' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior. ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, operatorResultType)) ' there should be no constant value in case of overflows. If Not value.IsBad Then value = ConstantValue.Bad End If End If End If End If Dim result As BoundExpression = New BoundBinaryOperator(node, operatorKind Or If(isOperandOfConditionalBranch, BinaryOperatorKind.IsOperandOfConditionalBranch, Nothing), left, right, CheckOverflow, value, operatorResultType, hasError) If forceToBooleanType IsNot Nothing Then Debug.Assert(forceToBooleanType.IsBooleanType()) result = ApplyConversion(node, forceToBooleanType, result, isExplicit:=True, diagnostics:=diagnostics) End If Return result End Function ''' <summary> ''' This helper is used to wrap nullable argument into something that would return null string if argument is null. ''' ''' Unlike conversion to a string where nullable nulls result in an exception, ''' concatenation requires that nullable nulls are treated as null strings. ''' Note that conversion is treated as explicit conversion. ''' </summary> Private Function ForceLiftToEmptyString(left As BoundExpression, stringType As TypeSymbol, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(stringType.IsStringType) Dim nothingStr = New BoundLiteral(left.Syntax, ConstantValue.Nothing, stringType).MakeCompilerGenerated() Return AnalyzeConversionAndCreateBinaryConditionalExpression(left.Syntax, left, nothingStr, Nothing, stringType, False, diagnostics, explicitConversion:=True).MakeCompilerGenerated() End Function Private Function BindUserDefinedNonShortCircuitingBinaryOperator( node As SyntaxNode, opKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, <[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag ) As BoundUserDefinedBinaryOperator Debug.Assert(userDefinedOperator.Candidates.Length > 0) opKind = opKind Or BinaryOperatorKind.UserDefined Dim result As BoundExpression If userDefinedOperator.BestResult.HasValue Then Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, New BoundMethodGroup(node, Nothing, ImmutableArray.Create(Of MethodSymbol)( DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)), LookupResultKind.Good, Nothing, QualificationKind.Unqualified).MakeCompilerGenerated(), ImmutableArray.Create(Of BoundExpression)(left, right), bestCandidate, userDefinedOperator.AsyncLambdaSubToFunctionMismatch, diagnostics) If bestCandidate.Candidate.IsLifted Then opKind = opKind Or BinaryOperatorKind.Lifted End If Else result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good, ImmutableArray.Create(Of BoundExpression)(left, right), Nothing, userDefinedOperator, diagnostics, callerInfoOpt:=Nothing) End If Return New BoundUserDefinedBinaryOperator(node, opKind, result, CheckOverflow, result.Type) End Function ''' <summary> ''' This function builds a bound tree representing an overloaded short circuiting expression ''' after determining that the necessary semantic conditions are met. ''' ''' An expression of the form: ''' ''' x AndAlso y (where the type of x is X and the type of y is Y) ''' ''' is an overloaded short circuit operation if X and Y are user-defined types and an ''' applicable operator And exists after applying normal operator resolution rules. ''' ''' Given an applicable And operator declared in type T, the following must be true: ''' ''' - The return type and parameter types must be T. ''' - T must contain a declaration of operator IsFalse. ''' ''' If these conditions are met, the expression "x AndAlso y" is translated into: ''' ''' !T.IsFalse(temp = x) ? T.And(temp, y) : temp ''' ''' The temporary is necessary for evaluating x only once. Similarly, "x OrElse y" is ''' translated into: ''' ''' !T.IsTrue(temp = x) ? T.Or(temp, y) : temp ''' </summary> Private Function BindUserDefinedShortCircuitingOperator( node As SyntaxNode, opKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, <[In]> ByRef bitwiseOperator As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag ) As BoundUserDefinedShortCircuitingOperator Debug.Assert(opKind = BinaryOperatorKind.AndAlso OrElse opKind = BinaryOperatorKind.OrElse) Debug.Assert(bitwiseOperator.Candidates.Length > 0) Dim bitwiseKind As BinaryOperatorKind = If(opKind = BinaryOperatorKind.AndAlso, BinaryOperatorKind.And, BinaryOperatorKind.Or) Or BinaryOperatorKind.UserDefined Dim operatorType As TypeSymbol Dim leftOperand As BoundExpression = Nothing Dim leftPlaceholder As BoundRValuePlaceholder = Nothing Dim test As BoundExpression = Nothing Dim bitwise As BoundUserDefinedBinaryOperator Dim hasErrors As Boolean = False If Not bitwiseOperator.BestResult.HasValue Then ' This will take care of the diagnostic. bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics) operatorType = bitwise.Type hasErrors = True GoTo Done End If Dim bitwiseAnalysis As OverloadResolution.CandidateAnalysisResult = bitwiseOperator.BestResult.Value Dim bitwiseCandidate As OverloadResolution.Candidate = bitwiseAnalysis.Candidate operatorType = bitwiseCandidate.ReturnType If bitwiseCandidate.IsLifted Then bitwiseKind = bitwiseKind Or BinaryOperatorKind.Lifted End If If Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(0).Type) OrElse Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(1).Type) Then ReportDiagnostic(diagnostics, node, ERRID.ERR_UnacceptableLogicalOperator3, bitwiseCandidate.UnderlyingSymbol, bitwiseCandidate.UnderlyingSymbol.ContainingType, SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword))) bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics. hasErrors = True GoTo Done End If leftPlaceholder = New BoundRValuePlaceholder(left.Syntax, operatorType).MakeCompilerGenerated() ' Find IsTrue/IsFalse operator Dim leftCheckOperator As OverloadResolution.OverloadResolutionResult Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) If opKind = BinaryOperatorKind.AndAlso Then leftCheckOperator = OverloadResolution.ResolveIsFalseOperator(leftPlaceholder, Me, useSiteInfo) Else leftCheckOperator = OverloadResolution.ResolveIsTrueOperator(leftPlaceholder, Me, useSiteInfo) End If If diagnostics.Add(node, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If Not leftCheckOperator.BestResult.HasValue Then ReportDiagnostic(diagnostics, node, ERRID.ERR_ConditionOperatorRequired3, operatorType, SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword)), SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword))) bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics. leftPlaceholder = Nothing hasErrors = True GoTo Done End If Dim checkCandidate As OverloadResolution.Candidate = leftCheckOperator.BestResult.Value.Candidate Debug.Assert(checkCandidate.ReturnType.IsBooleanType() OrElse checkCandidate.ReturnType.IsNullableOfBoolean()) If Not operatorType.IsSameTypeIgnoringAll(checkCandidate.Parameters(0).Type) Then ReportDiagnostic(diagnostics, node, ERRID.ERR_BinaryOperands3, SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)), left.Type, right.Type) hasErrors = True diagnostics = BindingDiagnosticBag.Discarded ' Ignore any additional diagnostics. bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics) Else ' Convert the operands to the operator type. Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node, bitwiseAnalysis, ImmutableArray.Create(Of BoundExpression)(left, right), diagnostics) Debug.Assert(argumentInfo.DefaultArguments.IsNull) bitwiseAnalysis.ConversionsOpt = Nothing bitwise = New BoundUserDefinedBinaryOperator(node, bitwiseKind, CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, New BoundMethodGroup(node, Nothing, ImmutableArray.Create(Of MethodSymbol)( DirectCast(bitwiseCandidate.UnderlyingSymbol, MethodSymbol)), LookupResultKind.Good, Nothing, QualificationKind.Unqualified).MakeCompilerGenerated(), ImmutableArray.Create(Of BoundExpression)(leftPlaceholder, argumentInfo.Arguments(1)), bitwiseAnalysis, bitwiseOperator.AsyncLambdaSubToFunctionMismatch, diagnostics), CheckOverflow, operatorType) leftOperand = argumentInfo.Arguments(0) End If Dim testOp As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node, If(opKind = BinaryOperatorKind.AndAlso, UnaryOperatorKind.IsFalse, UnaryOperatorKind.IsTrue), leftPlaceholder, leftCheckOperator, diagnostics).MakeCompilerGenerated() testOp.UnderlyingExpression.SetWasCompilerGenerated() If hasErrors Then leftPlaceholder = Nothing End If If checkCandidate.IsLifted Then test = ApplyNullableIsTrueOperator(testOp, checkCandidate.ReturnType.GetNullableUnderlyingTypeOrSelf()) Else test = testOp End If Done: Debug.Assert(hasErrors OrElse (leftOperand IsNot Nothing AndAlso leftPlaceholder IsNot Nothing AndAlso test IsNot Nothing)) Debug.Assert(Not hasErrors OrElse (leftOperand Is Nothing AndAlso leftPlaceholder Is Nothing)) bitwise.UnderlyingExpression.SetWasCompilerGenerated() bitwise.SetWasCompilerGenerated() Return New BoundUserDefinedShortCircuitingOperator(node, leftOperand, leftPlaceholder, test, bitwise, operatorType, hasErrors) End Function Private Shared Sub ReportBinaryOperatorOnObject( operatorTokenKind As SyntaxKind, operand As BoundExpression, preliminaryOperatorKind As BinaryOperatorKind, diagnostics As BindingDiagnosticBag ) ReportDiagnostic(diagnostics, operand.Syntax, ErrorFactory.ErrorInfo( If(preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals, ERRID.ERR_StrictDisallowsObjectComparison1, ERRID.ERR_StrictDisallowsObjectOperand1), operatorTokenKind)) End Sub ''' <summary> ''' Returns Symbol for String type. ''' </summary> Private Function SubstituteDBNullWithNothingString( ByRef dbNullOperand As BoundExpression, otherOperandType As TypeSymbol, diagnostics As BindingDiagnosticBag ) As TypeSymbol Dim stringType As TypeSymbol If otherOperandType.IsStringType() Then stringType = otherOperandType Else stringType = GetSpecialType(SpecialType.System_String, dbNullOperand.Syntax, diagnostics) End If dbNullOperand = New BoundConversion(dbNullOperand.Syntax, dbNullOperand, ConversionKind.Widening, checked:=False, explicitCastInCode:=False, type:=stringType, constantValueOpt:=ConstantValue.Nothing) Return stringType End Function ''' <summary> ''' Get symbol for a special type, reuse symbols for operand types to avoid type ''' lookups and construction of new instances of symbols. ''' </summary> Private Function GetSpecialTypeForBinaryOperator( node As SyntaxNode, leftType As TypeSymbol, rightType As TypeSymbol, specialType As SpecialType, makeNullable As Boolean, diagnostics As BindingDiagnosticBag ) As TypeSymbol Debug.Assert(specialType <> Microsoft.CodeAnalysis.SpecialType.None) Debug.Assert(Not makeNullable OrElse leftType.IsNullableType() OrElse rightType.IsNullableType()) Dim resultType As TypeSymbol Dim leftNullableUnderlying = leftType.GetNullableUnderlyingTypeOrSelf() Dim leftSpecialType = leftNullableUnderlying.SpecialType Dim rightNullableUnderlying = rightType.GetNullableUnderlyingTypeOrSelf() Dim rightSpecialType = rightNullableUnderlying.SpecialType If leftSpecialType = specialType Then If Not makeNullable Then resultType = leftNullableUnderlying ElseIf leftType.IsNullableType() Then resultType = leftType ElseIf rightSpecialType = specialType Then Debug.Assert(makeNullable AndAlso rightType.IsNullableType()) resultType = rightType Else Debug.Assert(makeNullable AndAlso rightType.IsNullableType() AndAlso Not leftType.IsNullableType()) resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(leftType) End If ElseIf rightSpecialType = specialType Then If Not makeNullable Then resultType = rightNullableUnderlying ElseIf rightType.IsNullableType() Then resultType = rightType Else Debug.Assert(makeNullable AndAlso Not rightType.IsNullableType() AndAlso leftType.IsNullableType()) resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(rightNullableUnderlying) End If Else resultType = GetSpecialType(specialType, node, diagnostics) If makeNullable Then If leftType.IsNullableType() Then resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(resultType) Else Debug.Assert(rightType.IsNullableType()) resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(resultType) End If End If End If Return resultType End Function ''' <summary> ''' Get symbol for a Nullable type of particular type, reuse symbols for operand types to avoid type ''' lookups and construction of new instances of symbols. ''' </summary> Private Shared Function GetNullableTypeForBinaryOperator( leftType As TypeSymbol, rightType As TypeSymbol, ofType As TypeSymbol ) As TypeSymbol Dim leftIsNullable = leftType.IsNullableType() Dim rightIsNullable = rightType.IsNullableType() Dim ofSpecialType = ofType.SpecialType Debug.Assert(leftIsNullable OrElse rightIsNullable) If ofSpecialType <> SpecialType.None Then If leftIsNullable AndAlso leftType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then Return leftType ElseIf rightIsNullable AndAlso rightType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then Return rightType End If End If If leftIsNullable Then Return DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(ofType) Else Return DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(ofType) End If End Function Private Shared Function IsKnownToBeNullableNothing(expr As BoundExpression) As Boolean Dim cast = expr ' TODO: Add handling for TryCast, similar to DirectCast While cast.Kind = BoundKind.Conversion OrElse cast.Kind = BoundKind.DirectCast If cast.HasErrors Then Return False End If Dim resultType As TypeSymbol = Nothing Select Case cast.Kind Case BoundKind.Conversion Dim conv = DirectCast(cast, BoundConversion) resultType = conv.Type cast = conv.Operand Case BoundKind.DirectCast Dim conv = DirectCast(cast, BoundDirectCast) resultType = conv.Type cast = conv.Operand End Select If resultType Is Nothing OrElse Not (resultType.IsNullableType() OrElse resultType.IsObjectType()) Then Return False End If End While Return cast.IsNothingLiteral() End Function Private Sub ReportUndefinedOperatorError( syntax As SyntaxNode, left As BoundExpression, right As BoundExpression, operatorTokenKind As SyntaxKind, operatorKind As BinaryOperatorKind, diagnostics As BindingDiagnosticBag ) Dim leftType = left.Type Dim rightType = right.Type Debug.Assert(leftType IsNot Nothing) Debug.Assert(rightType IsNot Nothing) If leftType.IsErrorType() OrElse rightType.IsErrorType() Then Return ' Let's not report more errors. End If Dim operatorTokenText = SyntaxFacts.GetText(operatorTokenKind) If OverloadResolution.UseUserDefinedBinaryOperators(operatorKind, leftType, rightType) AndAlso Not leftType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso Not rightType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso (operatorKind = BinaryOperatorKind.Equals OrElse operatorKind = BinaryOperatorKind.NotEquals) AndAlso leftType.IsReferenceType() AndAlso rightType.IsReferenceType() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ReferenceComparison3, operatorTokenText, leftType, rightType) ElseIf IsIEnumerableOfXElement(leftType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, leftType) ElseIf IsIEnumerableOfXElement(rightType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, rightType) Else ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperands3, operatorTokenText, leftType, rightType) End If End Sub ''' <summary> ''' §11.12.2 Object Operands ''' The value Nothing is treated as the default value of the type of ''' the other operand in a binary operator expression. In a unary operator expression, ''' or if both operands are Nothing in a binary operator expression, ''' the type of the operation is Integer or the only result type of the operator, ''' if the operator does not result in Integer. ''' </summary> Private Sub ConvertNothingLiterals( operatorKind As BinaryOperatorKind, ByRef left As BoundExpression, ByRef right As BoundExpression, diagnostics As BindingDiagnosticBag ) Debug.Assert((operatorKind And BinaryOperatorKind.OpMask) = operatorKind AndAlso operatorKind <> 0) Dim rightType As TypeSymbol Dim leftType As TypeSymbol If left.IsNothingLiteral() Then If right.IsNothingLiteral() Then ' Both are NOTHING Dim defaultRightSpecialType As SpecialType Select Case operatorKind Case BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like defaultRightSpecialType = SpecialType.System_String Case BinaryOperatorKind.OrElse, BinaryOperatorKind.AndAlso defaultRightSpecialType = SpecialType.System_Boolean Case BinaryOperatorKind.Add, BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Subtract, BinaryOperatorKind.Multiply, BinaryOperatorKind.Power, BinaryOperatorKind.Divide, BinaryOperatorKind.Modulo, BinaryOperatorKind.IntegerDivide, BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift, BinaryOperatorKind.Xor, BinaryOperatorKind.Or, BinaryOperatorKind.And defaultRightSpecialType = SpecialType.System_Int32 Case Else Throw ExceptionUtilities.UnexpectedValue(operatorKind) End Select rightType = GetSpecialType(defaultRightSpecialType, right.Syntax, diagnostics) right = ApplyImplicitConversion(right.Syntax, rightType, right, diagnostics) Else rightType = right.Type If rightType Is Nothing Then Return End If End If Debug.Assert(rightType IsNot Nothing) Dim defaultLeftSpecialType As SpecialType = SpecialType.None Select Case operatorKind Case BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like If rightType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse rightType.IsCharSZArray() OrElse rightType.IsDBNullType() Then ' For & and Like, a Nothing operand is typed String unless the other operand ' is non-intrinsic (VSW#240203). ' The same goes for DBNull (VSW#278518) ' The same goes for enum types (VSW#288077) defaultLeftSpecialType = SpecialType.System_String End If Case BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift ' Nothing should default to Integer for Shift operations. defaultLeftSpecialType = SpecialType.System_Int32 End Select If defaultLeftSpecialType = SpecialType.None OrElse defaultLeftSpecialType = rightType.SpecialType Then leftType = rightType Else leftType = GetSpecialType(defaultLeftSpecialType, left.Syntax, diagnostics) End If left = ApplyImplicitConversion(left.Syntax, leftType, left, diagnostics) ElseIf right.IsNothingLiteral() Then leftType = left.Type If leftType Is Nothing Then Return End If rightType = leftType Select Case operatorKind Case BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like If leftType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse leftType.IsCharSZArray() OrElse leftType.IsDBNullType() Then ' For & and Like, a Nothing operand is typed String unless the other operand ' is non-intrinsic (VSW#240203). ' The same goes for DBNull (VSW#278518) ' The same goes for enum types (VSW#288077) If leftType.SpecialType <> SpecialType.System_String Then rightType = GetSpecialType(SpecialType.System_String, right.Syntax, diagnostics) End If End If End Select right = ApplyImplicitConversion(right.Syntax, rightType, right, diagnostics) End If End Sub Private Function BindUnaryOperator(node As UnaryExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression Dim operand As BoundExpression = BindValue(node.Operand, diagnostics) Dim preliminaryOperatorKind As UnaryOperatorKind = OverloadResolution.MapUnaryOperatorKind(node.Kind) If Not operand.HasErrors AndAlso operand.IsNothingLiteral Then '§11.12.2 Object Operands 'In a unary operator expression, or if both operands are Nothing in a 'binary operator expression, the type of the operation is Integer Dim int32Type = GetSpecialType(SpecialType.System_Int32, node.Operand, diagnostics) operand = ApplyImplicitConversion(node.Operand, int32Type, operand, diagnostics) Else operand = MakeRValue(operand, diagnostics) End If If operand.HasErrors Then ' Suppress any additional diagnostics by overriding DiagnosticBag. diagnostics = BindingDiagnosticBag.Discarded End If Dim intrinsicOperatorType As SpecialType = SpecialType.None Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim operatorKind As UnaryOperatorKind = OverloadResolution.ResolveUnaryOperator(preliminaryOperatorKind, operand, Me, intrinsicOperatorType, userDefinedOperator, useSiteInfo) If diagnostics.Add(node, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If operatorKind = UnaryOperatorKind.UserDefined Then Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue, userDefinedOperator.BestResult.Value.Candidate, Nothing) If bestCandidate Is Nothing OrElse Not bestCandidate.IsLifted OrElse (OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then Return BindUserDefinedUnaryOperator(node, preliminaryOperatorKind, operand, userDefinedOperator, diagnostics) End If operatorKind = UnaryOperatorKind.Error End If If operatorKind = UnaryOperatorKind.Error Then ReportUndefinedOperatorError(node, operand, diagnostics) Return New BoundUnaryOperator(node, preliminaryOperatorKind Or UnaryOperatorKind.Error, operand, CheckOverflow, ErrorTypeSymbol.UnknownResultType, HasErrors:=True) End If ' We are dealing with intrinsic operator Dim operandType As TypeSymbol = operand.Type Dim resultType As TypeSymbol = Nothing If intrinsicOperatorType = SpecialType.None Then Debug.Assert(operandType.GetNullableUnderlyingTypeOrSelf().IsEnumType()) resultType = operandType Else If operandType.GetNullableUnderlyingTypeOrSelf().SpecialType = intrinsicOperatorType Then resultType = operandType Else resultType = GetSpecialType(intrinsicOperatorType, node.Operand, diagnostics) If operandType.IsNullableType() Then resultType = DirectCast(operandType.OriginalDefinition, NamedTypeSymbol).Construct(resultType) End If End If End If Debug.Assert(((operatorKind And UnaryOperatorKind.Lifted) <> 0) = resultType.IsNullableType()) ' Option Strict disallows all unary operations on Object operands. Otherwise just warn. If operandType.SpecialType = SpecialType.System_Object Then If OptionStrict = VisualBasic.OptionStrict.On Then ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.ERR_StrictDisallowsObjectOperand1, node.OperatorToken)) ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectMath2, node.OperatorToken)) End If End If operand = ApplyImplicitConversion(node.Operand, resultType, operand, diagnostics) Dim constantValue As ConstantValue = Nothing If Not operand.HasErrors Then Dim integerOverflow As Boolean = False constantValue = OverloadResolution.TryFoldConstantUnaryOperator(operatorKind, operand, resultType, integerOverflow) ' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior. If constantValue IsNot Nothing AndAlso (constantValue.IsBad OrElse integerOverflow) Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, resultType)) ' there should be no constant value in case of overflows. If Not constantValue.IsBad Then constantValue = constantValue.Bad End If End If End If Return New BoundUnaryOperator(node, operatorKind, operand, CheckOverflow, constantValue, resultType) End Function Private Function BindUserDefinedUnaryOperator( node As SyntaxNode, opKind As UnaryOperatorKind, operand As BoundExpression, <[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag ) As BoundUserDefinedUnaryOperator Debug.Assert(userDefinedOperator.Candidates.Length > 0) Dim result As BoundExpression opKind = opKind Or UnaryOperatorKind.UserDefined If userDefinedOperator.BestResult.HasValue Then Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, New BoundMethodGroup(node, Nothing, ImmutableArray.Create(Of MethodSymbol)( DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)), LookupResultKind.Good, Nothing, QualificationKind.Unqualified).MakeCompilerGenerated(), ImmutableArray.Create(Of BoundExpression)(operand), bestCandidate, userDefinedOperator.AsyncLambdaSubToFunctionMismatch, diagnostics) If bestCandidate.Candidate.IsLifted Then opKind = opKind Or UnaryOperatorKind.Lifted End If Else result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good, ImmutableArray.Create(Of BoundExpression)(operand), Nothing, userDefinedOperator, diagnostics, callerInfoOpt:=Nothing) End If Return New BoundUserDefinedUnaryOperator(node, opKind, result, result.Type) End Function Private Shared Sub ReportUndefinedOperatorError( syntax As UnaryExpressionSyntax, operand As BoundExpression, diagnostics As BindingDiagnosticBag ) If operand.Type.IsErrorType() Then Return ' Let's not report more errors. End If ReportDiagnostic(diagnostics, syntax, ErrorFactory.ErrorInfo(ERRID.ERR_UnaryOperand2, syntax.OperatorToken, operand.Type)) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of binary and unary operators is implemented in this part. Partial Friend Class Binder Private Function BindIsExpression( node As BinaryExpressionSyntax, diagnostics As BindingDiagnosticBag ) As BoundExpression Debug.Assert(node.Kind = SyntaxKind.IsExpression OrElse node.Kind = SyntaxKind.IsNotExpression) Dim [isNot] As Boolean = (node.Kind = SyntaxKind.IsNotExpression) ' The function below will make sure they are RValues. Dim left As BoundExpression = BindExpression(node.Left, diagnostics) Dim right As BoundExpression = BindExpression(node.Right, diagnostics) Return BindIsExpression(left, right, node, [isNot], diagnostics) End Function Private Function BindIsExpression( left As BoundExpression, right As BoundExpression, node As SyntaxNode, [isNot] As Boolean, diagnostics As BindingDiagnosticBag ) As BoundExpression left = MakeRValue(left, diagnostics) right = MakeRValue(right, diagnostics) left = ValidateAndConvertIsExpressionArgument(left, right, [isNot], diagnostics) right = ValidateAndConvertIsExpressionArgument(right, left, [isNot], diagnostics) Dim result As BoundExpression Dim booleanType = GetSpecialType(SpecialType.System_Boolean, node, diagnostics) result = New BoundBinaryOperator(node, If([isNot], BinaryOperatorKind.IsNot, BinaryOperatorKind.Is), left, right, checked:=False, type:=booleanType, hasErrors:=booleanType.IsErrorType()) ' TODO: Add rewrite for Nullable. Return result End Function ''' <summary> ''' Validate and apply appropriate conversion for the target argument of Is/IsNot expression. ''' </summary> Private Function ValidateAndConvertIsExpressionArgument( targetArgument As BoundExpression, otherArgument As BoundExpression, [isNot] As Boolean, diagnostics As BindingDiagnosticBag ) As BoundExpression Dim targetArgumentType As TypeSymbol = targetArgument.Type Dim result As BoundExpression If targetArgument.IsNothingLiteral() Then result = targetArgument ElseIf targetArgumentType.IsErrorType() Then result = targetArgument ElseIf targetArgumentType.IsReferenceType Then result = ApplyImplicitConversion(targetArgument.Syntax, GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics), targetArgument, diagnostics) ElseIf targetArgumentType.IsNullableType() Then If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then ReportDiagnostic(diagnostics, targetArgument.Syntax, If([isNot], ERRID.ERR_IsNotOperatorNullable1, ERRID.ERR_IsOperatorNullable1), targetArgumentType) End If result = targetArgument ElseIf targetArgumentType.IsTypeParameter() AndAlso Not targetArgumentType.IsValueType Then If Not otherArgument.HasErrors AndAlso Not otherArgument.IsNothingLiteral() Then ReportDiagnostic(diagnostics, targetArgument.Syntax, If([isNot], ERRID.ERR_IsNotOperatorGenericParam1, ERRID.ERR_IsOperatorGenericParam1), targetArgumentType) End If ' If any of the left or right operands of the Is or IsNot operands ' are entities of type parameters types, then they need to be boxed. result = ApplyImplicitConversion(targetArgument.Syntax, GetSpecialType(SpecialType.System_Object, targetArgument.Syntax, diagnostics), targetArgument, diagnostics) Else ReportDiagnostic(diagnostics, targetArgument.Syntax, If([isNot], ERRID.ERR_IsNotOpRequiresReferenceTypes1, ERRID.ERR_IsOperatorRequiresReferenceTypes1), targetArgumentType) result = targetArgument End If Return result End Function Private Function BindBinaryOperator( node As BinaryExpressionSyntax, isOperandOfConditionalBranch As Boolean, diagnostics As BindingDiagnosticBag ) As BoundExpression ' Some tools, such as ASP .NET, generate expressions containing thousands ' of string concatenations. For this reason, for string concatenations, ' avoid the usual recursion along the left side of the parse. Also, attempt ' to flatten whole sequences of string literal concatenations to avoid ' allocating space for intermediate results. Dim preliminaryOperatorKind As BinaryOperatorKind = OverloadResolution.MapBinaryOperatorKind(node.Kind) Dim propagateIsOperandOfConditionalBranch = isOperandOfConditionalBranch AndAlso (preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse preliminaryOperatorKind = BinaryOperatorKind.OrElse) Dim binary As BinaryExpressionSyntax = node Dim child As ExpressionSyntax Do child = binary.Left Select Case child.Kind Case SyntaxKind.AddExpression, SyntaxKind.ConcatenateExpression, SyntaxKind.LikeExpression, SyntaxKind.EqualsExpression, SyntaxKind.NotEqualsExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.SubtractExpression, SyntaxKind.MultiplyExpression, SyntaxKind.ExponentiateExpression, SyntaxKind.DivideExpression, SyntaxKind.ModuloExpression, SyntaxKind.IntegerDivideExpression, SyntaxKind.LeftShiftExpression, SyntaxKind.RightShiftExpression, SyntaxKind.ExclusiveOrExpression, SyntaxKind.OrExpression, SyntaxKind.AndExpression If propagateIsOperandOfConditionalBranch Then Exit Do End If Case SyntaxKind.OrElseExpression, SyntaxKind.AndAlsoExpression Exit Select Case Else Exit Do End Select binary = DirectCast(child, BinaryExpressionSyntax) Loop Dim left As BoundExpression = BindValue(child, diagnostics, propagateIsOperandOfConditionalBranch) Do binary = DirectCast(child.Parent, BinaryExpressionSyntax) Dim right As BoundExpression = BindValue(binary.Right, diagnostics, propagateIsOperandOfConditionalBranch) left = BindBinaryOperator(binary, left, right, binary.OperatorToken.Kind, OverloadResolution.MapBinaryOperatorKind(binary.Kind), If(binary Is node, isOperandOfConditionalBranch, propagateIsOperandOfConditionalBranch), diagnostics) child = binary Loop While child IsNot node Return left End Function Private Function BindBinaryOperator( node As SyntaxNode, left As BoundExpression, right As BoundExpression, operatorTokenKind As SyntaxKind, preliminaryOperatorKind As BinaryOperatorKind, isOperandOfConditionalBranch As Boolean, diagnostics As BindingDiagnosticBag, Optional isSelectCase As Boolean = False ) As BoundExpression Debug.Assert(left.IsValue) Debug.Assert(right.IsValue) Dim originalDiagnostics = diagnostics If (left.HasErrors OrElse right.HasErrors) Then ' Suppress any additional diagnostics by overriding DiagnosticBag. diagnostics = BindingDiagnosticBag.Discarded End If ' Deal with NOTHING literal as an input. ConvertNothingLiterals(preliminaryOperatorKind, left, right, diagnostics) left = MakeRValue(left, diagnostics) right = MakeRValue(right, diagnostics) If (left.HasErrors OrElse right.HasErrors) Then ' Suppress any additional diagnostics by overriding DiagnosticBag. If diagnostics Is originalDiagnostics Then diagnostics = BindingDiagnosticBag.Discarded End If End If Dim leftType As TypeSymbol = left.Type Dim rightType As TypeSymbol = right.Type Dim leftIsDBNull As Boolean = leftType.IsDBNullType() Dim rightIsDBNull As Boolean = rightType.IsDBNullType() '§11.16 Concatenation Operator 'A System.DBNull value is converted to the literal Nothing typed as String. If (preliminaryOperatorKind = BinaryOperatorKind.Concatenate AndAlso leftIsDBNull <> rightIsDBNull) OrElse (preliminaryOperatorKind = BinaryOperatorKind.Add AndAlso ((leftType.IsStringType() AndAlso rightIsDBNull) OrElse (leftIsDBNull AndAlso rightType.IsStringType))) Then Debug.Assert(leftIsDBNull Xor rightIsDBNull) If leftIsDBNull Then leftType = SubstituteDBNullWithNothingString(left, rightType, diagnostics) Else rightType = SubstituteDBNullWithNothingString(right, leftType, diagnostics) End If End If ' For comparison operators, the result type computed here is not ' the result type of the comparison (which is typically boolean), ' but is the type to which the operands are to be converted. For ' other operators, the type computed here is both the result type ' and the common operand type. Dim intrinsicOperatorType As SpecialType = SpecialType.None Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim operatorKind As BinaryOperatorKind = OverloadResolution.ResolveBinaryOperator(preliminaryOperatorKind, left, right, Me, True, intrinsicOperatorType, userDefinedOperator, useSiteInfo) If diagnostics.Add(node, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If operatorKind = BinaryOperatorKind.UserDefined Then Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue, userDefinedOperator.BestResult.Value.Candidate, Nothing) If bestCandidate Is Nothing OrElse Not bestCandidate.IsLifted OrElse (OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(1).Type) AndAlso OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then If preliminaryOperatorKind = BinaryOperatorKind.AndAlso OrElse preliminaryOperatorKind = BinaryOperatorKind.OrElse Then Return BindUserDefinedShortCircuitingOperator(node, preliminaryOperatorKind, left, right, userDefinedOperator, diagnostics) Else Return BindUserDefinedNonShortCircuitingBinaryOperator(node, preliminaryOperatorKind, left, right, userDefinedOperator, diagnostics) End If End If operatorKind = BinaryOperatorKind.Error End If If operatorKind = BinaryOperatorKind.Error Then ReportUndefinedOperatorError(node, left, right, operatorTokenKind, preliminaryOperatorKind, diagnostics) Return New BoundBinaryOperator(node, preliminaryOperatorKind Or BinaryOperatorKind.Error, left, right, CheckOverflow, ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If ' We are dealing with intrinsic operator ' Get the symbol for operand type Dim operandType As TypeSymbol If intrinsicOperatorType = SpecialType.None Then ' Must be a bitwise operation with enum type. Debug.Assert(leftType.GetNullableUnderlyingTypeOrSelf().IsEnumType() AndAlso leftType.GetNullableUnderlyingTypeOrSelf().IsSameTypeIgnoringAll(rightType.GetNullableUnderlyingTypeOrSelf())) If (operatorKind And BinaryOperatorKind.Lifted) = 0 OrElse leftType.IsNullableType() Then operandType = leftType Else Debug.Assert(rightType.IsNullableType()) operandType = rightType End If Else operandType = GetSpecialTypeForBinaryOperator(node, leftType, rightType, intrinsicOperatorType, (operatorKind And BinaryOperatorKind.Lifted) <> 0, diagnostics) End If ' Get the symbol for result type Dim operatorResultType As TypeSymbol = operandType Dim forceToBooleanType As TypeSymbol = Nothing Select Case preliminaryOperatorKind Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Like If OptionCompareText AndAlso (operandType.IsObjectType() OrElse operandType.IsStringType()) Then operatorKind = operatorKind Or BinaryOperatorKind.CompareText End If If Not operatorResultType.IsObjectType() OrElse (isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like) Then Dim booleanType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Boolean, False, diagnostics) If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then operatorResultType = GetNullableTypeForBinaryOperator(leftType, rightType, booleanType) If (preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals) AndAlso (IsKnownToBeNullableNothing(left) OrElse IsKnownToBeNullableNothing(right)) Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo( If(preliminaryOperatorKind = BinaryOperatorKind.Equals, ERRID.WRN_EqualToLiteralNothing, ERRID.WRN_NotEqualToLiteralNothing))) End If Else If Not operatorResultType.IsObjectType() Then operatorResultType = booleanType Else ' I believe this is just an optimization to prevent Object from bubbling up the tree. Debug.Assert(isOperandOfConditionalBranch AndAlso preliminaryOperatorKind <> BinaryOperatorKind.Like) forceToBooleanType = booleanType End If End If End If End Select If operandType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse operatorResultType.GetNullableUnderlyingTypeOrSelf().IsErrorType() OrElse (forceToBooleanType IsNot Nothing AndAlso forceToBooleanType.GetNullableUnderlyingTypeOrSelf().IsErrorType()) Then ' Suppress any additional diagnostics by overriding DiagnosticBag. If diagnostics Is originalDiagnostics Then diagnostics = BindingDiagnosticBag.Discarded End If End If Dim hasError As Boolean = False ' Option Strict disallows all operations on Object operands. Or, at least, warn. If OptionStrict = VisualBasic.OptionStrict.On Then Dim reportedAnEror As Boolean = False If leftType.IsObjectType Then ReportBinaryOperatorOnObject(operatorTokenKind, left, preliminaryOperatorKind, diagnostics) reportedAnEror = True End If If rightType.IsObjectType() Then ReportBinaryOperatorOnObject(operatorTokenKind, right, preliminaryOperatorKind, diagnostics) reportedAnEror = True End If If reportedAnEror Then hasError = True ' Suppress any additional diagnostics by overriding DiagnosticBag. If diagnostics Is originalDiagnostics Then diagnostics = BindingDiagnosticBag.Discarded End If End If ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then 'warn if option strict is off If Not isSelectCase OrElse preliminaryOperatorKind <> BinaryOperatorKind.OrElse Then Dim errorId = If(isSelectCase, ERRID.WRN_ObjectMathSelectCase, If(preliminaryOperatorKind = BinaryOperatorKind.Equals, ERRID.WRN_ObjectMath1, If(preliminaryOperatorKind = BinaryOperatorKind.NotEquals, ERRID.WRN_ObjectMath1Not, ERRID.WRN_ObjectMath2))) If leftType.IsObjectType Then ReportDiagnostic(diagnostics, left.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind)) End If If rightType.IsObjectType Then ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(errorId, operatorTokenKind)) End If End If End If ' Apply conversions to operands. Dim explicitSemanticForConcatArgument As Boolean = False ' Concatenation will apply conversions to its operands as if the ' conversions were explicit. Effectively, the use of the concatenation ' operator is treated as an explicit conversion to String. If preliminaryOperatorKind = BinaryOperatorKind.Concatenate Then explicitSemanticForConcatArgument = True Debug.Assert((operatorKind And BinaryOperatorKind.Lifted) = 0) If operandType.IsStringType() Then If left.Type.IsNullableType Then left = ForceLiftToEmptyString(left, operandType, diagnostics) End If If right.Type.IsNullableType Then right = ForceLiftToEmptyString(right, operandType, diagnostics) End If End If End If Dim beforeConversion As BoundExpression = left left = ApplyConversion(left.Syntax, operandType, left, explicitSemanticForConcatArgument, diagnostics, explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument) If explicitSemanticForConcatArgument AndAlso left IsNot beforeConversion AndAlso left.Kind = BoundKind.Conversion Then Dim conversion = DirectCast(left, BoundConversion) left = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False, constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt, type:=conversion.Type) End If If (preliminaryOperatorKind = BinaryOperatorKind.LeftShift OrElse preliminaryOperatorKind = BinaryOperatorKind.RightShift) AndAlso Not operandType.IsObjectType() Then Dim rightTargetType As TypeSymbol = GetSpecialTypeForBinaryOperator(node, leftType, rightType, SpecialType.System_Int32, False, diagnostics) '§11.18 Shift Operators 'The type of the right operand must be implicitly convertible to Integer ' If operator is lifted, convert right operand to Nullable(Of Integer) If (operatorKind And BinaryOperatorKind.Lifted) <> 0 Then rightTargetType = GetNullableTypeForBinaryOperator(leftType, rightType, rightTargetType) End If right = ApplyImplicitConversion(right.Syntax, rightTargetType, right, diagnostics) Else beforeConversion = right right = ApplyConversion(right.Syntax, operandType, right, explicitSemanticForConcatArgument, diagnostics, explicitSemanticForConcatArgument:=explicitSemanticForConcatArgument) If explicitSemanticForConcatArgument AndAlso right IsNot beforeConversion AndAlso right.Kind = BoundKind.Conversion Then Dim conversion = DirectCast(right, BoundConversion) right = conversion.Update(conversion.Operand, conversion.ConversionKind, conversion.Checked, explicitCastInCode:=False, constantValueOpt:=conversion.ConstantValueOpt, extendedInfoOpt:=conversion.ExtendedInfoOpt, type:=conversion.Type) End If End If If (operatorKind And BinaryOperatorKind.OpMask) = BinaryOperatorKind.Add AndAlso operatorResultType.IsStringType() Then ' Transform the addition into a string concatenation. This won't use a runtime helper - it will turn into System.String::Concat operatorKind = (operatorKind And (Not BinaryOperatorKind.OpMask)) operatorKind = operatorKind Or BinaryOperatorKind.Concatenate End If ' Perform constant folding. Dim value As ConstantValue = Nothing If Not (left.HasErrors OrElse right.HasErrors) Then Dim integerOverflow As Boolean = False Dim divideByZero As Boolean = False Dim lengthOutOfLimit As Boolean = False value = OverloadResolution.TryFoldConstantBinaryOperator(operatorKind, left, right, operatorResultType, integerOverflow, divideByZero, lengthOutOfLimit) If value IsNot Nothing Then If divideByZero Then Debug.Assert(value.IsBad) ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ZeroDivide)) ElseIf lengthOutOfLimit Then Debug.Assert(value.IsBad) ReportDiagnostic(diagnostics, right.Syntax, ErrorFactory.ErrorInfo(ERRID.ERR_ConstantStringTooLong)) ElseIf (value.IsBad OrElse integerOverflow) Then ' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior. ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, operatorResultType)) ' there should be no constant value in case of overflows. If Not value.IsBad Then value = ConstantValue.Bad End If End If End If End If Dim result As BoundExpression = New BoundBinaryOperator(node, operatorKind Or If(isOperandOfConditionalBranch, BinaryOperatorKind.IsOperandOfConditionalBranch, Nothing), left, right, CheckOverflow, value, operatorResultType, hasError) If forceToBooleanType IsNot Nothing Then Debug.Assert(forceToBooleanType.IsBooleanType()) result = ApplyConversion(node, forceToBooleanType, result, isExplicit:=True, diagnostics:=diagnostics) End If Return result End Function ''' <summary> ''' This helper is used to wrap nullable argument into something that would return null string if argument is null. ''' ''' Unlike conversion to a string where nullable nulls result in an exception, ''' concatenation requires that nullable nulls are treated as null strings. ''' Note that conversion is treated as explicit conversion. ''' </summary> Private Function ForceLiftToEmptyString(left As BoundExpression, stringType As TypeSymbol, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(stringType.IsStringType) Dim nothingStr = New BoundLiteral(left.Syntax, ConstantValue.Nothing, stringType).MakeCompilerGenerated() Return AnalyzeConversionAndCreateBinaryConditionalExpression(left.Syntax, left, nothingStr, Nothing, stringType, False, diagnostics, explicitConversion:=True).MakeCompilerGenerated() End Function Private Function BindUserDefinedNonShortCircuitingBinaryOperator( node As SyntaxNode, opKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, <[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag ) As BoundUserDefinedBinaryOperator Debug.Assert(userDefinedOperator.Candidates.Length > 0) opKind = opKind Or BinaryOperatorKind.UserDefined Dim result As BoundExpression If userDefinedOperator.BestResult.HasValue Then Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, New BoundMethodGroup(node, Nothing, ImmutableArray.Create(Of MethodSymbol)( DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)), LookupResultKind.Good, Nothing, QualificationKind.Unqualified).MakeCompilerGenerated(), ImmutableArray.Create(Of BoundExpression)(left, right), bestCandidate, userDefinedOperator.AsyncLambdaSubToFunctionMismatch, diagnostics) If bestCandidate.Candidate.IsLifted Then opKind = opKind Or BinaryOperatorKind.Lifted End If Else result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good, ImmutableArray.Create(Of BoundExpression)(left, right), Nothing, userDefinedOperator, diagnostics, callerInfoOpt:=Nothing) End If Return New BoundUserDefinedBinaryOperator(node, opKind, result, CheckOverflow, result.Type) End Function ''' <summary> ''' This function builds a bound tree representing an overloaded short circuiting expression ''' after determining that the necessary semantic conditions are met. ''' ''' An expression of the form: ''' ''' x AndAlso y (where the type of x is X and the type of y is Y) ''' ''' is an overloaded short circuit operation if X and Y are user-defined types and an ''' applicable operator And exists after applying normal operator resolution rules. ''' ''' Given an applicable And operator declared in type T, the following must be true: ''' ''' - The return type and parameter types must be T. ''' - T must contain a declaration of operator IsFalse. ''' ''' If these conditions are met, the expression "x AndAlso y" is translated into: ''' ''' !T.IsFalse(temp = x) ? T.And(temp, y) : temp ''' ''' The temporary is necessary for evaluating x only once. Similarly, "x OrElse y" is ''' translated into: ''' ''' !T.IsTrue(temp = x) ? T.Or(temp, y) : temp ''' </summary> Private Function BindUserDefinedShortCircuitingOperator( node As SyntaxNode, opKind As BinaryOperatorKind, left As BoundExpression, right As BoundExpression, <[In]> ByRef bitwiseOperator As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag ) As BoundUserDefinedShortCircuitingOperator Debug.Assert(opKind = BinaryOperatorKind.AndAlso OrElse opKind = BinaryOperatorKind.OrElse) Debug.Assert(bitwiseOperator.Candidates.Length > 0) Dim bitwiseKind As BinaryOperatorKind = If(opKind = BinaryOperatorKind.AndAlso, BinaryOperatorKind.And, BinaryOperatorKind.Or) Or BinaryOperatorKind.UserDefined Dim operatorType As TypeSymbol Dim leftOperand As BoundExpression = Nothing Dim leftPlaceholder As BoundRValuePlaceholder = Nothing Dim test As BoundExpression = Nothing Dim bitwise As BoundUserDefinedBinaryOperator Dim hasErrors As Boolean = False If Not bitwiseOperator.BestResult.HasValue Then ' This will take care of the diagnostic. bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics) operatorType = bitwise.Type hasErrors = True GoTo Done End If Dim bitwiseAnalysis As OverloadResolution.CandidateAnalysisResult = bitwiseOperator.BestResult.Value Dim bitwiseCandidate As OverloadResolution.Candidate = bitwiseAnalysis.Candidate operatorType = bitwiseCandidate.ReturnType If bitwiseCandidate.IsLifted Then bitwiseKind = bitwiseKind Or BinaryOperatorKind.Lifted End If If Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(0).Type) OrElse Not operatorType.IsSameTypeIgnoringAll(bitwiseCandidate.Parameters(1).Type) Then ReportDiagnostic(diagnostics, node, ERRID.ERR_UnacceptableLogicalOperator3, bitwiseCandidate.UnderlyingSymbol, bitwiseCandidate.UnderlyingSymbol.ContainingType, SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword))) bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics. hasErrors = True GoTo Done End If leftPlaceholder = New BoundRValuePlaceholder(left.Syntax, operatorType).MakeCompilerGenerated() ' Find IsTrue/IsFalse operator Dim leftCheckOperator As OverloadResolution.OverloadResolutionResult Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) If opKind = BinaryOperatorKind.AndAlso Then leftCheckOperator = OverloadResolution.ResolveIsFalseOperator(leftPlaceholder, Me, useSiteInfo) Else leftCheckOperator = OverloadResolution.ResolveIsTrueOperator(leftPlaceholder, Me, useSiteInfo) End If If diagnostics.Add(node, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If Not leftCheckOperator.BestResult.HasValue Then ReportDiagnostic(diagnostics, node, ERRID.ERR_ConditionOperatorRequired3, operatorType, SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.IsFalseKeyword, SyntaxKind.IsTrueKeyword)), SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword))) bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, BindingDiagnosticBag.Discarded) ' Ignore any additional diagnostics. leftPlaceholder = Nothing hasErrors = True GoTo Done End If Dim checkCandidate As OverloadResolution.Candidate = leftCheckOperator.BestResult.Value.Candidate Debug.Assert(checkCandidate.ReturnType.IsBooleanType() OrElse checkCandidate.ReturnType.IsNullableOfBoolean()) If Not operatorType.IsSameTypeIgnoringAll(checkCandidate.Parameters(0).Type) Then ReportDiagnostic(diagnostics, node, ERRID.ERR_BinaryOperands3, SyntaxFacts.GetText(If(opKind = BinaryOperatorKind.AndAlso, SyntaxKind.AndAlsoKeyword, SyntaxKind.OrElseKeyword)), left.Type, right.Type) hasErrors = True diagnostics = BindingDiagnosticBag.Discarded ' Ignore any additional diagnostics. bitwise = BindUserDefinedNonShortCircuitingBinaryOperator(node, bitwiseKind, left, right, bitwiseOperator, diagnostics) Else ' Convert the operands to the operator type. Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node, bitwiseAnalysis, ImmutableArray.Create(Of BoundExpression)(left, right), diagnostics) Debug.Assert(argumentInfo.DefaultArguments.IsNull) bitwiseAnalysis.ConversionsOpt = Nothing bitwise = New BoundUserDefinedBinaryOperator(node, bitwiseKind, CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, New BoundMethodGroup(node, Nothing, ImmutableArray.Create(Of MethodSymbol)( DirectCast(bitwiseCandidate.UnderlyingSymbol, MethodSymbol)), LookupResultKind.Good, Nothing, QualificationKind.Unqualified).MakeCompilerGenerated(), ImmutableArray.Create(Of BoundExpression)(leftPlaceholder, argumentInfo.Arguments(1)), bitwiseAnalysis, bitwiseOperator.AsyncLambdaSubToFunctionMismatch, diagnostics), CheckOverflow, operatorType) leftOperand = argumentInfo.Arguments(0) End If Dim testOp As BoundUserDefinedUnaryOperator = BindUserDefinedUnaryOperator(node, If(opKind = BinaryOperatorKind.AndAlso, UnaryOperatorKind.IsFalse, UnaryOperatorKind.IsTrue), leftPlaceholder, leftCheckOperator, diagnostics).MakeCompilerGenerated() testOp.UnderlyingExpression.SetWasCompilerGenerated() If hasErrors Then leftPlaceholder = Nothing End If If checkCandidate.IsLifted Then test = ApplyNullableIsTrueOperator(testOp, checkCandidate.ReturnType.GetNullableUnderlyingTypeOrSelf()) Else test = testOp End If Done: Debug.Assert(hasErrors OrElse (leftOperand IsNot Nothing AndAlso leftPlaceholder IsNot Nothing AndAlso test IsNot Nothing)) Debug.Assert(Not hasErrors OrElse (leftOperand Is Nothing AndAlso leftPlaceholder Is Nothing)) bitwise.UnderlyingExpression.SetWasCompilerGenerated() bitwise.SetWasCompilerGenerated() Return New BoundUserDefinedShortCircuitingOperator(node, leftOperand, leftPlaceholder, test, bitwise, operatorType, hasErrors) End Function Private Shared Sub ReportBinaryOperatorOnObject( operatorTokenKind As SyntaxKind, operand As BoundExpression, preliminaryOperatorKind As BinaryOperatorKind, diagnostics As BindingDiagnosticBag ) ReportDiagnostic(diagnostics, operand.Syntax, ErrorFactory.ErrorInfo( If(preliminaryOperatorKind = BinaryOperatorKind.Equals OrElse preliminaryOperatorKind = BinaryOperatorKind.NotEquals, ERRID.ERR_StrictDisallowsObjectComparison1, ERRID.ERR_StrictDisallowsObjectOperand1), operatorTokenKind)) End Sub ''' <summary> ''' Returns Symbol for String type. ''' </summary> Private Function SubstituteDBNullWithNothingString( ByRef dbNullOperand As BoundExpression, otherOperandType As TypeSymbol, diagnostics As BindingDiagnosticBag ) As TypeSymbol Dim stringType As TypeSymbol If otherOperandType.IsStringType() Then stringType = otherOperandType Else stringType = GetSpecialType(SpecialType.System_String, dbNullOperand.Syntax, diagnostics) End If dbNullOperand = New BoundConversion(dbNullOperand.Syntax, dbNullOperand, ConversionKind.Widening, checked:=False, explicitCastInCode:=False, type:=stringType, constantValueOpt:=ConstantValue.Nothing) Return stringType End Function ''' <summary> ''' Get symbol for a special type, reuse symbols for operand types to avoid type ''' lookups and construction of new instances of symbols. ''' </summary> Private Function GetSpecialTypeForBinaryOperator( node As SyntaxNode, leftType As TypeSymbol, rightType As TypeSymbol, specialType As SpecialType, makeNullable As Boolean, diagnostics As BindingDiagnosticBag ) As TypeSymbol Debug.Assert(specialType <> Microsoft.CodeAnalysis.SpecialType.None) Debug.Assert(Not makeNullable OrElse leftType.IsNullableType() OrElse rightType.IsNullableType()) Dim resultType As TypeSymbol Dim leftNullableUnderlying = leftType.GetNullableUnderlyingTypeOrSelf() Dim leftSpecialType = leftNullableUnderlying.SpecialType Dim rightNullableUnderlying = rightType.GetNullableUnderlyingTypeOrSelf() Dim rightSpecialType = rightNullableUnderlying.SpecialType If leftSpecialType = specialType Then If Not makeNullable Then resultType = leftNullableUnderlying ElseIf leftType.IsNullableType() Then resultType = leftType ElseIf rightSpecialType = specialType Then Debug.Assert(makeNullable AndAlso rightType.IsNullableType()) resultType = rightType Else Debug.Assert(makeNullable AndAlso rightType.IsNullableType() AndAlso Not leftType.IsNullableType()) resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(leftType) End If ElseIf rightSpecialType = specialType Then If Not makeNullable Then resultType = rightNullableUnderlying ElseIf rightType.IsNullableType() Then resultType = rightType Else Debug.Assert(makeNullable AndAlso Not rightType.IsNullableType() AndAlso leftType.IsNullableType()) resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(rightNullableUnderlying) End If Else resultType = GetSpecialType(specialType, node, diagnostics) If makeNullable Then If leftType.IsNullableType() Then resultType = DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(resultType) Else Debug.Assert(rightType.IsNullableType()) resultType = DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(resultType) End If End If End If Return resultType End Function ''' <summary> ''' Get symbol for a Nullable type of particular type, reuse symbols for operand types to avoid type ''' lookups and construction of new instances of symbols. ''' </summary> Private Shared Function GetNullableTypeForBinaryOperator( leftType As TypeSymbol, rightType As TypeSymbol, ofType As TypeSymbol ) As TypeSymbol Dim leftIsNullable = leftType.IsNullableType() Dim rightIsNullable = rightType.IsNullableType() Dim ofSpecialType = ofType.SpecialType Debug.Assert(leftIsNullable OrElse rightIsNullable) If ofSpecialType <> SpecialType.None Then If leftIsNullable AndAlso leftType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then Return leftType ElseIf rightIsNullable AndAlso rightType.GetNullableUnderlyingType().SpecialType = ofSpecialType Then Return rightType End If End If If leftIsNullable Then Return DirectCast(leftType.OriginalDefinition, NamedTypeSymbol).Construct(ofType) Else Return DirectCast(rightType.OriginalDefinition, NamedTypeSymbol).Construct(ofType) End If End Function Private Shared Function IsKnownToBeNullableNothing(expr As BoundExpression) As Boolean Dim cast = expr ' TODO: Add handling for TryCast, similar to DirectCast While cast.Kind = BoundKind.Conversion OrElse cast.Kind = BoundKind.DirectCast If cast.HasErrors Then Return False End If Dim resultType As TypeSymbol = Nothing Select Case cast.Kind Case BoundKind.Conversion Dim conv = DirectCast(cast, BoundConversion) resultType = conv.Type cast = conv.Operand Case BoundKind.DirectCast Dim conv = DirectCast(cast, BoundDirectCast) resultType = conv.Type cast = conv.Operand End Select If resultType Is Nothing OrElse Not (resultType.IsNullableType() OrElse resultType.IsObjectType()) Then Return False End If End While Return cast.IsNothingLiteral() End Function Private Sub ReportUndefinedOperatorError( syntax As SyntaxNode, left As BoundExpression, right As BoundExpression, operatorTokenKind As SyntaxKind, operatorKind As BinaryOperatorKind, diagnostics As BindingDiagnosticBag ) Dim leftType = left.Type Dim rightType = right.Type Debug.Assert(leftType IsNot Nothing) Debug.Assert(rightType IsNot Nothing) If leftType.IsErrorType() OrElse rightType.IsErrorType() Then Return ' Let's not report more errors. End If Dim operatorTokenText = SyntaxFacts.GetText(operatorTokenKind) If OverloadResolution.UseUserDefinedBinaryOperators(operatorKind, leftType, rightType) AndAlso Not leftType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso Not rightType.CanContainUserDefinedOperators(useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) AndAlso (operatorKind = BinaryOperatorKind.Equals OrElse operatorKind = BinaryOperatorKind.NotEquals) AndAlso leftType.IsReferenceType() AndAlso rightType.IsReferenceType() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_ReferenceComparison3, operatorTokenText, leftType, rightType) ElseIf IsIEnumerableOfXElement(leftType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, leftType) ElseIf IsIEnumerableOfXElement(rightType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperandsForXml4, operatorTokenText, leftType, rightType, rightType) Else ReportDiagnostic(diagnostics, syntax, ERRID.ERR_BinaryOperands3, operatorTokenText, leftType, rightType) End If End Sub ''' <summary> ''' §11.12.2 Object Operands ''' The value Nothing is treated as the default value of the type of ''' the other operand in a binary operator expression. In a unary operator expression, ''' or if both operands are Nothing in a binary operator expression, ''' the type of the operation is Integer or the only result type of the operator, ''' if the operator does not result in Integer. ''' </summary> Private Sub ConvertNothingLiterals( operatorKind As BinaryOperatorKind, ByRef left As BoundExpression, ByRef right As BoundExpression, diagnostics As BindingDiagnosticBag ) Debug.Assert((operatorKind And BinaryOperatorKind.OpMask) = operatorKind AndAlso operatorKind <> 0) Dim rightType As TypeSymbol Dim leftType As TypeSymbol If left.IsNothingLiteral() Then If right.IsNothingLiteral() Then ' Both are NOTHING Dim defaultRightSpecialType As SpecialType Select Case operatorKind Case BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like defaultRightSpecialType = SpecialType.System_String Case BinaryOperatorKind.OrElse, BinaryOperatorKind.AndAlso defaultRightSpecialType = SpecialType.System_Boolean Case BinaryOperatorKind.Add, BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThanOrEqual, BinaryOperatorKind.LessThan, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.Subtract, BinaryOperatorKind.Multiply, BinaryOperatorKind.Power, BinaryOperatorKind.Divide, BinaryOperatorKind.Modulo, BinaryOperatorKind.IntegerDivide, BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift, BinaryOperatorKind.Xor, BinaryOperatorKind.Or, BinaryOperatorKind.And defaultRightSpecialType = SpecialType.System_Int32 Case Else Throw ExceptionUtilities.UnexpectedValue(operatorKind) End Select rightType = GetSpecialType(defaultRightSpecialType, right.Syntax, diagnostics) right = ApplyImplicitConversion(right.Syntax, rightType, right, diagnostics) Else rightType = right.Type If rightType Is Nothing Then Return End If End If Debug.Assert(rightType IsNot Nothing) Dim defaultLeftSpecialType As SpecialType = SpecialType.None Select Case operatorKind Case BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like If rightType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse rightType.IsCharSZArray() OrElse rightType.IsDBNullType() Then ' For & and Like, a Nothing operand is typed String unless the other operand ' is non-intrinsic (VSW#240203). ' The same goes for DBNull (VSW#278518) ' The same goes for enum types (VSW#288077) defaultLeftSpecialType = SpecialType.System_String End If Case BinaryOperatorKind.LeftShift, BinaryOperatorKind.RightShift ' Nothing should default to Integer for Shift operations. defaultLeftSpecialType = SpecialType.System_Int32 End Select If defaultLeftSpecialType = SpecialType.None OrElse defaultLeftSpecialType = rightType.SpecialType Then leftType = rightType Else leftType = GetSpecialType(defaultLeftSpecialType, left.Syntax, diagnostics) End If left = ApplyImplicitConversion(left.Syntax, leftType, left, diagnostics) ElseIf right.IsNothingLiteral() Then leftType = left.Type If leftType Is Nothing Then Return End If rightType = leftType Select Case operatorKind Case BinaryOperatorKind.Concatenate, BinaryOperatorKind.Like If leftType.GetNullableUnderlyingTypeOrSelf().GetEnumUnderlyingTypeOrSelf().IsIntrinsicType() OrElse leftType.IsCharSZArray() OrElse leftType.IsDBNullType() Then ' For & and Like, a Nothing operand is typed String unless the other operand ' is non-intrinsic (VSW#240203). ' The same goes for DBNull (VSW#278518) ' The same goes for enum types (VSW#288077) If leftType.SpecialType <> SpecialType.System_String Then rightType = GetSpecialType(SpecialType.System_String, right.Syntax, diagnostics) End If End If End Select right = ApplyImplicitConversion(right.Syntax, rightType, right, diagnostics) End If End Sub Private Function BindUnaryOperator(node As UnaryExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression Dim operand As BoundExpression = BindValue(node.Operand, diagnostics) Dim preliminaryOperatorKind As UnaryOperatorKind = OverloadResolution.MapUnaryOperatorKind(node.Kind) If Not operand.HasErrors AndAlso operand.IsNothingLiteral Then '§11.12.2 Object Operands 'In a unary operator expression, or if both operands are Nothing in a 'binary operator expression, the type of the operation is Integer Dim int32Type = GetSpecialType(SpecialType.System_Int32, node.Operand, diagnostics) operand = ApplyImplicitConversion(node.Operand, int32Type, operand, diagnostics) Else operand = MakeRValue(operand, diagnostics) End If If operand.HasErrors Then ' Suppress any additional diagnostics by overriding DiagnosticBag. diagnostics = BindingDiagnosticBag.Discarded End If Dim intrinsicOperatorType As SpecialType = SpecialType.None Dim userDefinedOperator As OverloadResolution.OverloadResolutionResult = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim operatorKind As UnaryOperatorKind = OverloadResolution.ResolveUnaryOperator(preliminaryOperatorKind, operand, Me, intrinsicOperatorType, userDefinedOperator, useSiteInfo) If diagnostics.Add(node, useSiteInfo) Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If If operatorKind = UnaryOperatorKind.UserDefined Then Dim bestCandidate As OverloadResolution.Candidate = If(userDefinedOperator.BestResult.HasValue, userDefinedOperator.BestResult.Value.Candidate, Nothing) If bestCandidate Is Nothing OrElse Not bestCandidate.IsLifted OrElse (OverloadResolution.IsValidInLiftedSignature(bestCandidate.Parameters(0).Type) AndAlso OverloadResolution.IsValidInLiftedSignature(bestCandidate.ReturnType)) Then Return BindUserDefinedUnaryOperator(node, preliminaryOperatorKind, operand, userDefinedOperator, diagnostics) End If operatorKind = UnaryOperatorKind.Error End If If operatorKind = UnaryOperatorKind.Error Then ReportUndefinedOperatorError(node, operand, diagnostics) Return New BoundUnaryOperator(node, preliminaryOperatorKind Or UnaryOperatorKind.Error, operand, CheckOverflow, ErrorTypeSymbol.UnknownResultType, HasErrors:=True) End If ' We are dealing with intrinsic operator Dim operandType As TypeSymbol = operand.Type Dim resultType As TypeSymbol = Nothing If intrinsicOperatorType = SpecialType.None Then Debug.Assert(operandType.GetNullableUnderlyingTypeOrSelf().IsEnumType()) resultType = operandType Else If operandType.GetNullableUnderlyingTypeOrSelf().SpecialType = intrinsicOperatorType Then resultType = operandType Else resultType = GetSpecialType(intrinsicOperatorType, node.Operand, diagnostics) If operandType.IsNullableType() Then resultType = DirectCast(operandType.OriginalDefinition, NamedTypeSymbol).Construct(resultType) End If End If End If Debug.Assert(((operatorKind And UnaryOperatorKind.Lifted) <> 0) = resultType.IsNullableType()) ' Option Strict disallows all unary operations on Object operands. Otherwise just warn. If operandType.SpecialType = SpecialType.System_Object Then If OptionStrict = VisualBasic.OptionStrict.On Then ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.ERR_StrictDisallowsObjectOperand1, node.OperatorToken)) ElseIf OptionStrict = VisualBasic.OptionStrict.Custom Then ReportDiagnostic(diagnostics, node.Operand, ErrorFactory.ErrorInfo(ERRID.WRN_ObjectMath2, node.OperatorToken)) End If End If operand = ApplyImplicitConversion(node.Operand, resultType, operand, diagnostics) Dim constantValue As ConstantValue = Nothing If Not operand.HasErrors Then Dim integerOverflow As Boolean = False constantValue = OverloadResolution.TryFoldConstantUnaryOperator(operatorKind, operand, resultType, integerOverflow) ' Overflows are reported regardless of the value of OptionRemoveIntegerOverflowChecks, Dev10 behavior. If constantValue IsNot Nothing AndAlso (constantValue.IsBad OrElse integerOverflow) Then ReportDiagnostic(diagnostics, node, ErrorFactory.ErrorInfo(ERRID.ERR_ExpressionOverflow1, resultType)) ' there should be no constant value in case of overflows. If Not constantValue.IsBad Then constantValue = constantValue.Bad End If End If End If Return New BoundUnaryOperator(node, operatorKind, operand, CheckOverflow, constantValue, resultType) End Function Private Function BindUserDefinedUnaryOperator( node As SyntaxNode, opKind As UnaryOperatorKind, operand As BoundExpression, <[In]> ByRef userDefinedOperator As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag ) As BoundUserDefinedUnaryOperator Debug.Assert(userDefinedOperator.Candidates.Length > 0) Dim result As BoundExpression opKind = opKind Or UnaryOperatorKind.UserDefined If userDefinedOperator.BestResult.HasValue Then Dim bestCandidate As OverloadResolution.CandidateAnalysisResult = userDefinedOperator.BestResult.Value result = CreateBoundCallOrPropertyAccess(node, node, TypeCharacter.None, New BoundMethodGroup(node, Nothing, ImmutableArray.Create(Of MethodSymbol)( DirectCast(bestCandidate.Candidate.UnderlyingSymbol, MethodSymbol)), LookupResultKind.Good, Nothing, QualificationKind.Unqualified).MakeCompilerGenerated(), ImmutableArray.Create(Of BoundExpression)(operand), bestCandidate, userDefinedOperator.AsyncLambdaSubToFunctionMismatch, diagnostics) If bestCandidate.Candidate.IsLifted Then opKind = opKind Or UnaryOperatorKind.Lifted End If Else result = ReportOverloadResolutionFailureAndProduceBoundNode(node, LookupResultKind.Good, ImmutableArray.Create(Of BoundExpression)(operand), Nothing, userDefinedOperator, diagnostics, callerInfoOpt:=Nothing) End If Return New BoundUserDefinedUnaryOperator(node, opKind, result, result.Type) End Function Private Shared Sub ReportUndefinedOperatorError( syntax As UnaryExpressionSyntax, operand As BoundExpression, diagnostics As BindingDiagnosticBag ) If operand.Type.IsErrorType() Then Return ' Let's not report more errors. End If ReportDiagnostic(diagnostics, syntax, ErrorFactory.ErrorInfo(ERRID.ERR_UnaryOperand2, syntax.OperatorToken, operand.Type)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Def/ExternalAccess/ProjectSystem/Api/ProjectSystemReferenceUpdate.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { internal sealed class ProjectSystemReferenceUpdate { /// <summary> /// Indicates action to perform on the reference. /// </summary> public ProjectSystemUpdateAction Action { get; } /// <summary> /// Gets the reference to be updated. /// </summary> public ProjectSystemReferenceInfo ReferenceInfo { get; } public ProjectSystemReferenceUpdate(ProjectSystemUpdateAction action, ProjectSystemReferenceInfo referenceInfo) { Action = action; ReferenceInfo = referenceInfo; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api { internal sealed class ProjectSystemReferenceUpdate { /// <summary> /// Indicates action to perform on the reference. /// </summary> public ProjectSystemUpdateAction Action { get; } /// <summary> /// Gets the reference to be updated. /// </summary> public ProjectSystemReferenceInfo ReferenceInfo { get; } public ProjectSystemReferenceUpdate(ProjectSystemUpdateAction action, ProjectSystemReferenceInfo referenceInfo) { Action = action; ReferenceInfo = referenceInfo; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/SignatureHelp/AbstractVisualBasicSignatureHelpProviderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public MustInherit Class AbstractVisualBasicSignatureHelpProviderTests Inherits AbstractSignatureHelpProviderTests(Of VisualBasicTestWorkspaceFixture) ' We want to skip script testing in all VB stuff for now. Protected Overrides Function TestAsync(markupWithPositionAndOptSpan As String, Optional expectedOrderedItemsOrNull As IEnumerable(Of SignatureHelpTestItem) = Nothing, Optional usePreviousCharAsTrigger As Boolean = False, Optional sourceCodeKind As Microsoft.CodeAnalysis.SourceCodeKind? = Nothing, Optional experimental As Boolean = False) As Threading.Tasks.Task If (sourceCodeKind.HasValue) Then Return MyBase.TestAsync(markupWithPositionAndOptSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger, sourceCodeKind, experimental) Else Return MyBase.TestAsync(markupWithPositionAndOptSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger, Microsoft.CodeAnalysis.SourceCodeKind.Regular, experimental) End If End Function Protected Overrides Function VerifyCurrentParameterNameAsync(markupWithPosition As String, expectedParameterName As String, Optional sourceCodeKind As Microsoft.CodeAnalysis.SourceCodeKind? = Nothing) As Threading.Tasks.Task If (sourceCodeKind.HasValue) Then Return MyBase.VerifyCurrentParameterNameAsync(markupWithPosition, expectedParameterName, sourceCodeKind) Else Return MyBase.VerifyCurrentParameterNameAsync(markupWithPosition, expectedParameterName, Microsoft.CodeAnalysis.SourceCodeKind.Regular) End If End Function Protected Overrides Function CreateExperimentalParseOptions() As ParseOptions ' There are no experimental features at this time. Return New VisualBasicParseOptions() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public MustInherit Class AbstractVisualBasicSignatureHelpProviderTests Inherits AbstractSignatureHelpProviderTests(Of VisualBasicTestWorkspaceFixture) ' We want to skip script testing in all VB stuff for now. Protected Overrides Function TestAsync(markupWithPositionAndOptSpan As String, Optional expectedOrderedItemsOrNull As IEnumerable(Of SignatureHelpTestItem) = Nothing, Optional usePreviousCharAsTrigger As Boolean = False, Optional sourceCodeKind As Microsoft.CodeAnalysis.SourceCodeKind? = Nothing, Optional experimental As Boolean = False) As Threading.Tasks.Task If (sourceCodeKind.HasValue) Then Return MyBase.TestAsync(markupWithPositionAndOptSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger, sourceCodeKind, experimental) Else Return MyBase.TestAsync(markupWithPositionAndOptSpan, expectedOrderedItemsOrNull, usePreviousCharAsTrigger, Microsoft.CodeAnalysis.SourceCodeKind.Regular, experimental) End If End Function Protected Overrides Function VerifyCurrentParameterNameAsync(markupWithPosition As String, expectedParameterName As String, Optional sourceCodeKind As Microsoft.CodeAnalysis.SourceCodeKind? = Nothing) As Threading.Tasks.Task If (sourceCodeKind.HasValue) Then Return MyBase.VerifyCurrentParameterNameAsync(markupWithPosition, expectedParameterName, sourceCodeKind) Else Return MyBase.VerifyCurrentParameterNameAsync(markupWithPosition, expectedParameterName, Microsoft.CodeAnalysis.SourceCodeKind.Regular) End If End Function Protected Overrides Function CreateExperimentalParseOptions() As ParseOptions ' There are no experimental features at this time. Return New VisualBasicParseOptions() End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Def/Implementation/VisualStudioWorkspaceContextService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IWorkspaceContextService), ServiceLayer.Host), Shared] internal sealed class VisualStudioWorkspaceContextService : IWorkspaceContextService { // UI context defined by Live Share when connected as a guest in a Live Share session // https://devdiv.visualstudio.com/DevDiv/_git/Cascade?path=%2Fsrc%2FVS%2FContracts%2FGuidList.cs&version=GBmain&line=32&lineEnd=33&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents private static readonly Guid s_liveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e"); private readonly IGlobalOptionService _globalOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioWorkspaceContextService(IGlobalOptionService globalOptions) { _globalOptions = globalOptions; } public bool IsCloudEnvironmentClient() => UIContext.FromUIContextGuid(VSConstants.UICONTEXT.CloudEnvironmentConnected_guid).IsActive; public bool IsInLspEditorContext() => IsLiveShareGuest() || IsCloudEnvironmentClient() || _globalOptions.GetOption(LspOptions.LspEditorFeatureFlag); /// <summary> /// Checks if the VS instance is running as a Live Share guest session. /// </summary> private static bool IsLiveShareGuest() => UIContext.FromUIContextGuid(s_liveShareGuestUIContextGuid).IsActive; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.Shell; namespace Microsoft.VisualStudio.LanguageServices.Implementation { [ExportWorkspaceService(typeof(IWorkspaceContextService), ServiceLayer.Host), Shared] internal sealed class VisualStudioWorkspaceContextService : IWorkspaceContextService { // UI context defined by Live Share when connected as a guest in a Live Share session // https://devdiv.visualstudio.com/DevDiv/_git/Cascade?path=%2Fsrc%2FVS%2FContracts%2FGuidList.cs&version=GBmain&line=32&lineEnd=33&lineStartColumn=1&lineEndColumn=1&lineStyle=plain&_a=contents private static readonly Guid s_liveShareGuestUIContextGuid = Guid.Parse("fd93f3eb-60da-49cd-af15-acda729e357e"); private readonly IGlobalOptionService _globalOptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualStudioWorkspaceContextService(IGlobalOptionService globalOptions) { _globalOptions = globalOptions; } public bool IsCloudEnvironmentClient() => UIContext.FromUIContextGuid(VSConstants.UICONTEXT.CloudEnvironmentConnected_guid).IsActive; public bool IsInLspEditorContext() => IsLiveShareGuest() || IsCloudEnvironmentClient() || _globalOptions.GetOption(LspOptions.LspEditorFeatureFlag); /// <summary> /// Checks if the VS instance is running as a Live Share guest session. /// </summary> private static bool IsLiveShareGuest() => UIContext.FromUIContextGuid(s_liveShareGuestUIContextGuid).IsActive; } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/JoinKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class JoinKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public JoinKeywordRecommender() : base(SyntaxKind.JoinKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsValidContextForJoinClause(position, context.LeftToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class JoinKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public JoinKeywordRecommender() : base(SyntaxKind.JoinKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsValidContextForJoinClause(position, context.LeftToken); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/CallHierarchyProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { [Export(typeof(CallHierarchyProvider))] internal partial class CallHierarchyProvider { private readonly IAsynchronousOperationListener _asyncListener; public IGlyphService GlyphService { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallHierarchyProvider( IAsynchronousOperationListenerProvider listenerProvider, IGlyphService glyphService) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.CallHierarchy); this.GlyphService = glyphService; } public async Task<ICallHierarchyMemberItem> CreateItemAsync(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFindersAsync(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; } private ISymbol GetTargetSymbol(ISymbol symbol) { if (symbol is IMethodSymbol methodSymbol) { methodSymbol = methodSymbol.ReducedFrom ?? methodSymbol; methodSymbol = methodSymbol.ConstructedFrom ?? methodSymbol; return methodSymbol; } return symbol; } public FieldInitializerItem CreateInitializerItem(IEnumerable<CallHierarchyDetail> details) { return new FieldInitializerItem(EditorFeaturesResources.Initializers, "__" + EditorFeaturesResources.Initializers, Glyph.FieldPublic.GetImageSource(GlyphService), details); } public async Task<IEnumerable<AbstractCallFinder>> CreateFindersAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Method) { var finders = new List<AbstractCallFinder>(); finders.Add(new MethodCallFinder(symbol, project.Id, _asyncListener, this)); if (symbol.IsVirtual || symbol.IsAbstract) { finders.Add(new OverridingMemberFinder(symbol, project.Id, _asyncListener, this)); } var @overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); if (overrides.Any()) { finders.Add(new CallToOverrideFinder(symbol, project.Id, _asyncListener, this)); } if (symbol.GetOverriddenMember() != null) { finders.Add(new BaseMemberFinder(symbol.GetOverriddenMember(), project.Id, _asyncListener, this)); } var implementedInterfaceMembers = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { finders.Add(new InterfaceImplementationCallFinder(implementedInterfaceMember, project.Id, _asyncListener, this)); } if (symbol.IsImplementableMember()) { finders.Add(new ImplementerFinder(symbol, project.Id, _asyncListener, this)); } return finders; } if (symbol.Kind == SymbolKind.Field) { return SpecializedCollections.SingletonEnumerable(new FieldReferenceFinder(symbol, project.Id, _asyncListener, this)); } return null; } public void NavigateTo(SymbolKey id, Project project, CancellationToken cancellationToken) { var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var resolution = id.Resolve(compilation, cancellationToken: cancellationToken); var workspace = project.Solution.Workspace; var options = project.Solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); var symbolNavigationService = workspace.Services.GetService<ISymbolNavigationService>(); symbolNavigationService.TryNavigateToSymbol(resolution.Symbol, project, options, cancellationToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Language.CallHierarchy; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy { [Export(typeof(CallHierarchyProvider))] internal partial class CallHierarchyProvider { private readonly IAsynchronousOperationListener _asyncListener; public IGlyphService GlyphService { get; } [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CallHierarchyProvider( IAsynchronousOperationListenerProvider listenerProvider, IGlyphService glyphService) { _asyncListener = listenerProvider.GetListener(FeatureAttribute.CallHierarchy); this.GlyphService = glyphService; } public async Task<ICallHierarchyMemberItem> CreateItemAsync(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFindersAsync(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; } private ISymbol GetTargetSymbol(ISymbol symbol) { if (symbol is IMethodSymbol methodSymbol) { methodSymbol = methodSymbol.ReducedFrom ?? methodSymbol; methodSymbol = methodSymbol.ConstructedFrom ?? methodSymbol; return methodSymbol; } return symbol; } public FieldInitializerItem CreateInitializerItem(IEnumerable<CallHierarchyDetail> details) { return new FieldInitializerItem(EditorFeaturesResources.Initializers, "__" + EditorFeaturesResources.Initializers, Glyph.FieldPublic.GetImageSource(GlyphService), details); } public async Task<IEnumerable<AbstractCallFinder>> CreateFindersAsync(ISymbol symbol, Project project, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Method) { var finders = new List<AbstractCallFinder>(); finders.Add(new MethodCallFinder(symbol, project.Id, _asyncListener, this)); if (symbol.IsVirtual || symbol.IsAbstract) { finders.Add(new OverridingMemberFinder(symbol, project.Id, _asyncListener, this)); } var @overrides = await SymbolFinder.FindOverridesAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); if (overrides.Any()) { finders.Add(new CallToOverrideFinder(symbol, project.Id, _asyncListener, this)); } if (symbol.GetOverriddenMember() != null) { finders.Add(new BaseMemberFinder(symbol.GetOverriddenMember(), project.Id, _asyncListener, this)); } var implementedInterfaceMembers = await SymbolFinder.FindImplementedInterfaceMembersAsync(symbol, project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var implementedInterfaceMember in implementedInterfaceMembers) { finders.Add(new InterfaceImplementationCallFinder(implementedInterfaceMember, project.Id, _asyncListener, this)); } if (symbol.IsImplementableMember()) { finders.Add(new ImplementerFinder(symbol, project.Id, _asyncListener, this)); } return finders; } if (symbol.Kind == SymbolKind.Field) { return SpecializedCollections.SingletonEnumerable(new FieldReferenceFinder(symbol, project.Id, _asyncListener, this)); } return null; } public void NavigateTo(SymbolKey id, Project project, CancellationToken cancellationToken) { var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var resolution = id.Resolve(compilation, cancellationToken: cancellationToken); var workspace = project.Solution.Workspace; var options = project.Solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true); var symbolNavigationService = workspace.Services.GetService<ISymbolNavigationService>(); symbolNavigationService.TryNavigateToSymbol(resolution.Symbol, project, options, cancellationToken); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Symbols/EEMethodSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Delegate Function GenerateMethodBody( method As EEMethodSymbol, diagnostics As DiagnosticBag, <Out> ByRef properties As ResultProperties) As BoundStatement Friend NotInheritable Class EEMethodSymbol Inherits MethodSymbol Friend ReadOnly TypeMap As TypeSubstitution Friend ReadOnly SubstitutedSourceMethod As MethodSymbol Friend ReadOnly Locals As ImmutableArray(Of LocalSymbol) Friend ReadOnly LocalsForBinding As ImmutableArray(Of LocalSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _container As EENamedTypeSymbol Private ReadOnly _name As String Private ReadOnly _locations As ImmutableArray(Of Location) Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _meParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _voidType As NamedTypeSymbol ''' <summary> ''' Invoked at most once to generate the method body. ''' (If the compilation has no errors, it will be invoked ''' exactly once, otherwise it may be skipped.) ''' </summary> Private ReadOnly _generateMethodBody As GenerateMethodBody Private _lazyReturnType As TypeSymbol Private _lazyResultProperties As ResultProperties ' NOTE: This is only used for asserts, so it could be conditional on DEBUG. Private ReadOnly _allTypeParameters As ImmutableArray(Of TypeParameterSymbol) Friend Sub New( compilation As VisualBasicCompilation, container As EENamedTypeSymbol, name As String, location As Location, sourceMethod As MethodSymbol, sourceLocals As ImmutableArray(Of LocalSymbol), sourceLocalsForBinding As ImmutableArray(Of LocalSymbol), sourceDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), voidType As NamedTypeSymbol, generateMethodBody As GenerateMethodBody) Debug.Assert(sourceMethod.IsDefinition) Debug.Assert(TypeSymbol.Equals(sourceMethod.ContainingType, container.SubstitutedSourceType.OriginalDefinition, TypeCompareKind.ConsiderEverything)) Debug.Assert(sourceLocals.All(Function(l) l.ContainingSymbol = sourceMethod)) _compilation = compilation _container = container _name = name _locations = ImmutableArray.Create(location) _voidType = voidType ' What we want is to map all original type parameters to the corresponding new type parameters ' (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: ' 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. ' 2) The map cannot be constructed until all new type parameters exist. ' Our solution is to pass each new type parameter a lazy reference to the type map. We then ' initialize the map as soon as the new type parameters are available - and before they are ' handed out - so that there is never a period where they can require the type map and find ' it uninitialized. Dim sourceMethodTypeParameters = sourceMethod.TypeParameters Dim allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters) Dim getTypeMap As New Func(Of TypeSubstitution)(Function() TypeMap) _typeParameters = sourceMethodTypeParameters.SelectAsArray( Function(tp As TypeParameterSymbol, i As Integer, arg As Object) DirectCast(New EETypeParameterSymbol(Me, tp, i, getTypeMap), TypeParameterSymbol), DirectCast(Nothing, Object)) _allTypeParameters = container.TypeParameters.Concat(_typeParameters) Me.TypeMap = TypeSubstitution.Create(sourceMethod, allSourceTypeParameters, ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_allTypeParameters)) EENamedTypeSymbol.VerifyTypeParameters(Me, _typeParameters) Dim substitutedSourceType = container.SubstitutedSourceType Me.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType) If _typeParameters.Any() Then Me.SubstitutedSourceMethod = Me.SubstitutedSourceMethod.Construct(_typeParameters.As(Of TypeSymbol)()) End If TypeParameterChecker.Check(Me.SubstitutedSourceMethod, _allTypeParameters) ' Create a map from original parameter to target parameter. Dim parameterBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim substitutedSourceMeParameter = Me.SubstitutedSourceMethod.MeParameter Dim substitutedSourceHasMeParameter = substitutedSourceMeParameter IsNot Nothing If substitutedSourceHasMeParameter Then _meParameter = MakeParameterSymbol(0, GeneratedNames.MakeStateMachineCapturedMeName(), substitutedSourceMeParameter) ' NOTE: Name doesn't actually matter. Debug.Assert(TypeSymbol.Equals(_meParameter.Type, Me.SubstitutedSourceMethod.ContainingType, TypeCompareKind.ConsiderEverything)) parameterBuilder.Add(_meParameter) End If Dim ordinalOffset = If(substitutedSourceHasMeParameter, 1, 0) For Each substitutedSourceParameter In Me.SubstitutedSourceMethod.Parameters Dim ordinal = substitutedSourceParameter.Ordinal + ordinalOffset Debug.Assert(ordinal = parameterBuilder.Count) Dim parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter) parameterBuilder.Add(parameter) Next _parameters = parameterBuilder.ToImmutableAndFree() Dim localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim localsMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() For Each sourceLocal In sourceLocals Dim local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) localsBuilder.Add(local) Next Me.Locals = localsBuilder.ToImmutableAndFree() localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each sourceLocal In sourceLocalsForBinding Dim local As LocalSymbol = Nothing If Not localsMap.TryGetValue(sourceLocal, local) Then local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) End If localsBuilder.Add(local) Next Me.LocalsForBinding = localsBuilder.ToImmutableAndFree() ' Create a map from variable name to display class field. _displayClassVariables = SubstituteDisplayClassVariables(sourceDisplayClassVariables, localsMap, Me, Me.TypeMap) localsMap.Free() _generateMethodBody = generateMethodBody End Sub Private Shared Function SubstituteDisplayClassVariables( oldDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), localsMap As Dictionary(Of LocalSymbol, LocalSymbol), otherMethod As MethodSymbol, typeMap As TypeSubstitution) As ImmutableDictionary(Of String, DisplayClassVariable) ' Create a map from variable name to display class field. Dim newDisplayClassVariables = PooledDictionary(Of String, DisplayClassVariable).GetInstance() For Each pair In oldDisplayClassVariables Dim variable = pair.Value Dim oldDisplayClassInstance = variable.DisplayClassInstance ' Note: we don't call ToOtherMethod in the local case because doing so would produce ' a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. Dim oldDisplayClassInstanceFromLocal = TryCast(oldDisplayClassInstance, DisplayClassInstanceFromLocal) Dim newDisplayClassInstance = If(oldDisplayClassInstanceFromLocal Is Nothing, oldDisplayClassInstance.ToOtherMethod(otherMethod, typeMap), New DisplayClassInstanceFromLocal(DirectCast(localsMap(oldDisplayClassInstanceFromLocal.Local), EELocalSymbol))) variable = variable.SubstituteFields(newDisplayClassInstance, typeMap) newDisplayClassVariables.Add(pair.Key, variable) Next Dim result = newDisplayClassVariables.ToImmutableDictionary() newDisplayClassVariables.Free() Return result End Function Private Function MakeParameterSymbol(ordinal As Integer, name As String, sourceParameter As ParameterSymbol) As ParameterSymbol Return SynthesizedParameterSymbol.Create( Me, sourceParameter.Type, ordinal, sourceParameter.IsByRef, name, sourceParameter.CustomModifiers, sourceParameter.RefCustomModifiers) End Function Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As MethodImplAttributes Get Return Nothing End Get End Property Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean meParameter = Nothing Return True End Function Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return ReturnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get If _lazyReturnType Is Nothing Then Throw New InvalidOperationException() End If Return _lazyReturnType End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention Get Debug.Assert(Me.IsShared) Dim cc = Cci.CallingConvention.Default If Me.IsVararg Then cc = cc Or Cci.CallingConvention.ExtraArguments End If If Me.IsGenericMethod Then cc = cc Or Cci.CallingConvention.Generic End If Return cc End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Internal End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Friend ReadOnly Property ResultProperties As ResultProperties Get Return _lazyResultProperties End Get End Property #Disable Warning CA1200 ' Avoid using cref tags with a prefix ''' <remarks> ''' The corresponding C# method, ''' <see cref="M:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EEMethodSymbol.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.TypeCompilationState,Microsoft.CodeAnalysis.DiagnosticBag)"/>, ''' invokes the <see cref="LocalRewriter"/> and the <see cref="LambdaRewriter"/> explicitly. ''' In VB, the caller (of this method) does that. ''' </remarks> #Enable Warning CA1200 ' Avoid using cref tags with a prefix Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, <Out> ByRef Optional methodBodyBinder As Binder = Nothing) As BoundBlock Debug.Assert(diagnostics.DiagnosticBag IsNot Nothing) Dim body = _generateMethodBody(Me, diagnostics.DiagnosticBag, _lazyResultProperties) Debug.Assert(body IsNot Nothing) _lazyReturnType = CalculateReturnType(body) ' Can't do this until the return type has been computed. TypeParameterChecker.Check(Me, _allTypeParameters) Dim syntax As SyntaxNode = body.Syntax Dim statementsBuilder = ArrayBuilder(Of BoundStatement).GetInstance() statementsBuilder.Add(body) ' Insert an implicit return statement if necessary. If body.Kind <> BoundKind.ReturnStatement Then statementsBuilder.Add(New BoundReturnStatement(syntax, Nothing, Nothing, Nothing)) End If Dim originalLocalsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim originalLocalsSet = PooledHashSet(Of LocalSymbol).GetInstance() For Each local In LocalsForBinding Debug.Assert(Not originalLocalsSet.Contains(local)) originalLocalsBuilder.Add(local) originalLocalsSet.Add(local) Next For Each local In Me.Locals If originalLocalsSet.Add(local) Then originalLocalsBuilder.Add(local) End If Next originalLocalsSet.Free() Dim originalLocals = originalLocalsBuilder.ToImmutableAndFree() Dim newBody = New BoundBlock(syntax, Nothing, originalLocals, statementsBuilder.ToImmutableAndFree()) If diagnostics.HasAnyErrors() Then Return newBody End If DiagnosticsPass.IssueDiagnostics(newBody, diagnostics.DiagnosticBag, Me) If diagnostics.HasAnyErrors() Then Return newBody End If ' Check for use-site errors (e.g. missing types in the signature). Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Me.CalculateUseSiteInfo() If useSiteInfo.DiagnosticInfo IsNot Nothing Then diagnostics.Add(useSiteInfo, _locations(0)) Return newBody End If Debug.Assert(Not newBody.HasErrors) ' NOTE: In C#, EE rewriting happens AFTER local rewriting. However, that order would be difficult ' to accommodate in VB, so we reverse it. Try ' Rewrite local declaration statement. newBody = LocalDeclarationRewriter.Rewrite(_compilation, _container, newBody) ' Rewrite pseudo-variable references to helper method calls. newBody = DirectCast(PlaceholderLocalRewriter.Rewrite(_compilation, _container, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Create a map from original local to target local. Dim localMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() Dim targetLocals = newBody.Locals Debug.Assert(originalLocals.Length = targetLocals.Length) For i = 0 To originalLocals.Length - 1 Dim originalLocal = originalLocals(i) Dim targetLocal = targetLocals(i) Debug.Assert(TypeOf originalLocal IsNot EELocalSymbol OrElse DirectCast(originalLocal, EELocalSymbol).Ordinal = DirectCast(targetLocal, EELocalSymbol).Ordinal) localMap.Add(originalLocal, targetLocal) Next ' Variables may have been captured by lambdas in the original method ' or in the expression, and we need to preserve the existing values of ' those variables in the expression. This requires rewriting the variables ' in the expression based on the closure classes from both the original ' method and the expression, and generating a preamble that copies ' values into the expression closure classes. ' ' Consider the original method: ' Shared Sub M() ' Dim x, y, z as Integer ' ... ' F(Function() x + y) ' End Sub ' and the expression in the EE: "F(Function() x + z)". ' ' The expression is first rewritten using the closure class and local <1> ' from the original method: F(Function() <1>.x + z) ' Then lambda rewriting introduces a new closure class that includes ' the locals <1> and z, and a corresponding local <2>: F(Function() <2>.<1>.x + <2>.z) ' And a preamble is added to initialize the fields of <2>: ' <2> = New <>c__DisplayClass0() ' <2>.<1> = <1> ' <2>.z = z ' ' Note: The above behavior is actually implemented in the LambdaRewriter and ' is triggered by overriding PreserveOriginalLocals to return "True". ' Create a map from variable name to display class field. Dim displayClassVariables = SubstituteDisplayClassVariables(_displayClassVariables, localMap, Me, Me.TypeMap) ' Rewrite references to "Me" to refer to this method's "Me" parameter. ' Rewrite variables within body to reference existing display classes. newBody = DirectCast(CapturedVariableRewriter.Rewrite( If(Me.SubstitutedSourceMethod.IsShared, Nothing, Me.Parameters(0)), displayClassVariables, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Insert locals from the original method, followed by any new locals. Dim localBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each originalLocal In Me.Locals Dim targetLocal = localMap(originalLocal) Debug.Assert(TypeOf targetLocal IsNot EELocalSymbol OrElse DirectCast(targetLocal, EELocalSymbol).Ordinal = localBuilder.Count) localBuilder.Add(targetLocal) Next localMap.Free() newBody = newBody.Update(newBody.StatementListSyntax, localBuilder.ToImmutableAndFree(), newBody.Statements) TypeParameterChecker.Check(newBody, _allTypeParameters) Catch ex As BoundTreeVisitor.CancelledByStackGuardException ex.AddAnError(diagnostics) End Try Return newBody End Function Private Function CalculateReturnType(body As BoundStatement) As TypeSymbol Select Case body.Kind Case BoundKind.ReturnStatement Return DirectCast(body, BoundReturnStatement).ExpressionOpt.Type Case BoundKind.ExpressionStatement, BoundKind.RedimStatement Return _voidType Case Else Throw ExceptionUtilities.UnexpectedValue(body.Kind) End Select End Function Friend Overrides Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedReturnTypeAttributes(attributes) Dim returnType = Me.ReturnType If returnType.ContainsTupleNames() AndAlso DeclaringCompilation.HasTupleNamesAttributes() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(returnType)) End If End Sub Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Return localPosition End Function Friend Overrides ReadOnly Property PreserveOriginalLocals As Boolean Get Return True End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Reflection Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend Delegate Function GenerateMethodBody( method As EEMethodSymbol, diagnostics As DiagnosticBag, <Out> ByRef properties As ResultProperties) As BoundStatement Friend NotInheritable Class EEMethodSymbol Inherits MethodSymbol Friend ReadOnly TypeMap As TypeSubstitution Friend ReadOnly SubstitutedSourceMethod As MethodSymbol Friend ReadOnly Locals As ImmutableArray(Of LocalSymbol) Friend ReadOnly LocalsForBinding As ImmutableArray(Of LocalSymbol) Private ReadOnly _compilation As VisualBasicCompilation Private ReadOnly _container As EENamedTypeSymbol Private ReadOnly _name As String Private ReadOnly _locations As ImmutableArray(Of Location) Private ReadOnly _typeParameters As ImmutableArray(Of TypeParameterSymbol) Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Private ReadOnly _meParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _voidType As NamedTypeSymbol ''' <summary> ''' Invoked at most once to generate the method body. ''' (If the compilation has no errors, it will be invoked ''' exactly once, otherwise it may be skipped.) ''' </summary> Private ReadOnly _generateMethodBody As GenerateMethodBody Private _lazyReturnType As TypeSymbol Private _lazyResultProperties As ResultProperties ' NOTE: This is only used for asserts, so it could be conditional on DEBUG. Private ReadOnly _allTypeParameters As ImmutableArray(Of TypeParameterSymbol) Friend Sub New( compilation As VisualBasicCompilation, container As EENamedTypeSymbol, name As String, location As Location, sourceMethod As MethodSymbol, sourceLocals As ImmutableArray(Of LocalSymbol), sourceLocalsForBinding As ImmutableArray(Of LocalSymbol), sourceDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), voidType As NamedTypeSymbol, generateMethodBody As GenerateMethodBody) Debug.Assert(sourceMethod.IsDefinition) Debug.Assert(TypeSymbol.Equals(sourceMethod.ContainingType, container.SubstitutedSourceType.OriginalDefinition, TypeCompareKind.ConsiderEverything)) Debug.Assert(sourceLocals.All(Function(l) l.ContainingSymbol = sourceMethod)) _compilation = compilation _container = container _name = name _locations = ImmutableArray.Create(location) _voidType = voidType ' What we want is to map all original type parameters to the corresponding new type parameters ' (since the old ones have the wrong owners). Unfortunately, we have a circular dependency: ' 1) Each new type parameter requires the entire map in order to be able to construct its constraint list. ' 2) The map cannot be constructed until all new type parameters exist. ' Our solution is to pass each new type parameter a lazy reference to the type map. We then ' initialize the map as soon as the new type parameters are available - and before they are ' handed out - so that there is never a period where they can require the type map and find ' it uninitialized. Dim sourceMethodTypeParameters = sourceMethod.TypeParameters Dim allSourceTypeParameters = container.SourceTypeParameters.Concat(sourceMethodTypeParameters) Dim getTypeMap As New Func(Of TypeSubstitution)(Function() TypeMap) _typeParameters = sourceMethodTypeParameters.SelectAsArray( Function(tp As TypeParameterSymbol, i As Integer, arg As Object) DirectCast(New EETypeParameterSymbol(Me, tp, i, getTypeMap), TypeParameterSymbol), DirectCast(Nothing, Object)) _allTypeParameters = container.TypeParameters.Concat(_typeParameters) Me.TypeMap = TypeSubstitution.Create(sourceMethod, allSourceTypeParameters, ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_allTypeParameters)) EENamedTypeSymbol.VerifyTypeParameters(Me, _typeParameters) Dim substitutedSourceType = container.SubstitutedSourceType Me.SubstitutedSourceMethod = sourceMethod.AsMember(substitutedSourceType) If _typeParameters.Any() Then Me.SubstitutedSourceMethod = Me.SubstitutedSourceMethod.Construct(_typeParameters.As(Of TypeSymbol)()) End If TypeParameterChecker.Check(Me.SubstitutedSourceMethod, _allTypeParameters) ' Create a map from original parameter to target parameter. Dim parameterBuilder = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim substitutedSourceMeParameter = Me.SubstitutedSourceMethod.MeParameter Dim substitutedSourceHasMeParameter = substitutedSourceMeParameter IsNot Nothing If substitutedSourceHasMeParameter Then _meParameter = MakeParameterSymbol(0, GeneratedNames.MakeStateMachineCapturedMeName(), substitutedSourceMeParameter) ' NOTE: Name doesn't actually matter. Debug.Assert(TypeSymbol.Equals(_meParameter.Type, Me.SubstitutedSourceMethod.ContainingType, TypeCompareKind.ConsiderEverything)) parameterBuilder.Add(_meParameter) End If Dim ordinalOffset = If(substitutedSourceHasMeParameter, 1, 0) For Each substitutedSourceParameter In Me.SubstitutedSourceMethod.Parameters Dim ordinal = substitutedSourceParameter.Ordinal + ordinalOffset Debug.Assert(ordinal = parameterBuilder.Count) Dim parameter = MakeParameterSymbol(ordinal, substitutedSourceParameter.Name, substitutedSourceParameter) parameterBuilder.Add(parameter) Next _parameters = parameterBuilder.ToImmutableAndFree() Dim localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim localsMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() For Each sourceLocal In sourceLocals Dim local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) localsBuilder.Add(local) Next Me.Locals = localsBuilder.ToImmutableAndFree() localsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each sourceLocal In sourceLocalsForBinding Dim local As LocalSymbol = Nothing If Not localsMap.TryGetValue(sourceLocal, local) Then local = sourceLocal.ToOtherMethod(Me, Me.TypeMap) localsMap.Add(sourceLocal, local) End If localsBuilder.Add(local) Next Me.LocalsForBinding = localsBuilder.ToImmutableAndFree() ' Create a map from variable name to display class field. _displayClassVariables = SubstituteDisplayClassVariables(sourceDisplayClassVariables, localsMap, Me, Me.TypeMap) localsMap.Free() _generateMethodBody = generateMethodBody End Sub Private Shared Function SubstituteDisplayClassVariables( oldDisplayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), localsMap As Dictionary(Of LocalSymbol, LocalSymbol), otherMethod As MethodSymbol, typeMap As TypeSubstitution) As ImmutableDictionary(Of String, DisplayClassVariable) ' Create a map from variable name to display class field. Dim newDisplayClassVariables = PooledDictionary(Of String, DisplayClassVariable).GetInstance() For Each pair In oldDisplayClassVariables Dim variable = pair.Value Dim oldDisplayClassInstance = variable.DisplayClassInstance ' Note: we don't call ToOtherMethod in the local case because doing so would produce ' a new LocalSymbol that would not be ReferenceEquals to the one in this.LocalsForBinding. Dim oldDisplayClassInstanceFromLocal = TryCast(oldDisplayClassInstance, DisplayClassInstanceFromLocal) Dim newDisplayClassInstance = If(oldDisplayClassInstanceFromLocal Is Nothing, oldDisplayClassInstance.ToOtherMethod(otherMethod, typeMap), New DisplayClassInstanceFromLocal(DirectCast(localsMap(oldDisplayClassInstanceFromLocal.Local), EELocalSymbol))) variable = variable.SubstituteFields(newDisplayClassInstance, typeMap) newDisplayClassVariables.Add(pair.Key, variable) Next Dim result = newDisplayClassVariables.ToImmutableDictionary() newDisplayClassVariables.Free() Return result End Function Private Function MakeParameterSymbol(ordinal As Integer, name As String, sourceParameter As ParameterSymbol) As ParameterSymbol Return SynthesizedParameterSymbol.Create( Me, sourceParameter.Type, ordinal, sourceParameter.IsByRef, name, sourceParameter.CustomModifiers, sourceParameter.RefCustomModifiers) End Function Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return _typeParameters.Length End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As MethodImplAttributes Get Return Nothing End Get End Property Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean meParameter = Nothing Return True End Function Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return ReturnType.SpecialType = SpecialType.System_Void End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get If _lazyReturnType Is Nothing Then Throw New InvalidOperationException() End If Return _lazyReturnType End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArrayExtensions.Cast(Of TypeParameterSymbol, TypeSymbol)(_typeParameters) End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return _typeParameters End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property CallingConvention As Cci.CallingConvention Get Debug.Assert(Me.IsShared) Dim cc = Cci.CallingConvention.Default If Me.IsVararg Then cc = cc Or Cci.CallingConvention.ExtraArguments End If If Me.IsGenericMethod Then cc = cc Or Cci.CallingConvention.Generic End If Return cc End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _container End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Throw ExceptionUtilities.Unreachable End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Internal End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Throw ExceptionUtilities.Unreachable End Get End Property Friend Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Friend ReadOnly Property ResultProperties As ResultProperties Get Return _lazyResultProperties End Get End Property #Disable Warning CA1200 ' Avoid using cref tags with a prefix ''' <remarks> ''' The corresponding C# method, ''' <see cref="M:Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.EEMethodSymbol.GenerateMethodBody(Microsoft.CodeAnalysis.CSharp.TypeCompilationState,Microsoft.CodeAnalysis.DiagnosticBag)"/>, ''' invokes the <see cref="LocalRewriter"/> and the <see cref="LambdaRewriter"/> explicitly. ''' In VB, the caller (of this method) does that. ''' </remarks> #Enable Warning CA1200 ' Avoid using cref tags with a prefix Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, <Out> ByRef Optional methodBodyBinder As Binder = Nothing) As BoundBlock Debug.Assert(diagnostics.DiagnosticBag IsNot Nothing) Dim body = _generateMethodBody(Me, diagnostics.DiagnosticBag, _lazyResultProperties) Debug.Assert(body IsNot Nothing) _lazyReturnType = CalculateReturnType(body) ' Can't do this until the return type has been computed. TypeParameterChecker.Check(Me, _allTypeParameters) Dim syntax As SyntaxNode = body.Syntax Dim statementsBuilder = ArrayBuilder(Of BoundStatement).GetInstance() statementsBuilder.Add(body) ' Insert an implicit return statement if necessary. If body.Kind <> BoundKind.ReturnStatement Then statementsBuilder.Add(New BoundReturnStatement(syntax, Nothing, Nothing, Nothing)) End If Dim originalLocalsBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() Dim originalLocalsSet = PooledHashSet(Of LocalSymbol).GetInstance() For Each local In LocalsForBinding Debug.Assert(Not originalLocalsSet.Contains(local)) originalLocalsBuilder.Add(local) originalLocalsSet.Add(local) Next For Each local In Me.Locals If originalLocalsSet.Add(local) Then originalLocalsBuilder.Add(local) End If Next originalLocalsSet.Free() Dim originalLocals = originalLocalsBuilder.ToImmutableAndFree() Dim newBody = New BoundBlock(syntax, Nothing, originalLocals, statementsBuilder.ToImmutableAndFree()) If diagnostics.HasAnyErrors() Then Return newBody End If DiagnosticsPass.IssueDiagnostics(newBody, diagnostics.DiagnosticBag, Me) If diagnostics.HasAnyErrors() Then Return newBody End If ' Check for use-site errors (e.g. missing types in the signature). Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = Me.CalculateUseSiteInfo() If useSiteInfo.DiagnosticInfo IsNot Nothing Then diagnostics.Add(useSiteInfo, _locations(0)) Return newBody End If Debug.Assert(Not newBody.HasErrors) ' NOTE: In C#, EE rewriting happens AFTER local rewriting. However, that order would be difficult ' to accommodate in VB, so we reverse it. Try ' Rewrite local declaration statement. newBody = LocalDeclarationRewriter.Rewrite(_compilation, _container, newBody) ' Rewrite pseudo-variable references to helper method calls. newBody = DirectCast(PlaceholderLocalRewriter.Rewrite(_compilation, _container, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Create a map from original local to target local. Dim localMap = PooledDictionary(Of LocalSymbol, LocalSymbol).GetInstance() Dim targetLocals = newBody.Locals Debug.Assert(originalLocals.Length = targetLocals.Length) For i = 0 To originalLocals.Length - 1 Dim originalLocal = originalLocals(i) Dim targetLocal = targetLocals(i) Debug.Assert(TypeOf originalLocal IsNot EELocalSymbol OrElse DirectCast(originalLocal, EELocalSymbol).Ordinal = DirectCast(targetLocal, EELocalSymbol).Ordinal) localMap.Add(originalLocal, targetLocal) Next ' Variables may have been captured by lambdas in the original method ' or in the expression, and we need to preserve the existing values of ' those variables in the expression. This requires rewriting the variables ' in the expression based on the closure classes from both the original ' method and the expression, and generating a preamble that copies ' values into the expression closure classes. ' ' Consider the original method: ' Shared Sub M() ' Dim x, y, z as Integer ' ... ' F(Function() x + y) ' End Sub ' and the expression in the EE: "F(Function() x + z)". ' ' The expression is first rewritten using the closure class and local <1> ' from the original method: F(Function() <1>.x + z) ' Then lambda rewriting introduces a new closure class that includes ' the locals <1> and z, and a corresponding local <2>: F(Function() <2>.<1>.x + <2>.z) ' And a preamble is added to initialize the fields of <2>: ' <2> = New <>c__DisplayClass0() ' <2>.<1> = <1> ' <2>.z = z ' ' Note: The above behavior is actually implemented in the LambdaRewriter and ' is triggered by overriding PreserveOriginalLocals to return "True". ' Create a map from variable name to display class field. Dim displayClassVariables = SubstituteDisplayClassVariables(_displayClassVariables, localMap, Me, Me.TypeMap) ' Rewrite references to "Me" to refer to this method's "Me" parameter. ' Rewrite variables within body to reference existing display classes. newBody = DirectCast(CapturedVariableRewriter.Rewrite( If(Me.SubstitutedSourceMethod.IsShared, Nothing, Me.Parameters(0)), displayClassVariables, newBody, diagnostics.DiagnosticBag), BoundBlock) If diagnostics.HasAnyErrors() Then Return newBody End If ' Insert locals from the original method, followed by any new locals. Dim localBuilder = ArrayBuilder(Of LocalSymbol).GetInstance() For Each originalLocal In Me.Locals Dim targetLocal = localMap(originalLocal) Debug.Assert(TypeOf targetLocal IsNot EELocalSymbol OrElse DirectCast(targetLocal, EELocalSymbol).Ordinal = localBuilder.Count) localBuilder.Add(targetLocal) Next localMap.Free() newBody = newBody.Update(newBody.StatementListSyntax, localBuilder.ToImmutableAndFree(), newBody.Statements) TypeParameterChecker.Check(newBody, _allTypeParameters) Catch ex As BoundTreeVisitor.CancelledByStackGuardException ex.AddAnError(diagnostics) End Try Return newBody End Function Private Function CalculateReturnType(body As BoundStatement) As TypeSymbol Select Case body.Kind Case BoundKind.ReturnStatement Return DirectCast(body, BoundReturnStatement).ExpressionOpt.Type Case BoundKind.ExpressionStatement, BoundKind.RedimStatement Return _voidType Case Else Throw ExceptionUtilities.UnexpectedValue(body.Kind) End Select End Function Friend Overrides Sub AddSynthesizedReturnTypeAttributes(ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedReturnTypeAttributes(attributes) Dim returnType = Me.ReturnType If returnType.ContainsTupleNames() AndAlso DeclaringCompilation.HasTupleNamesAttributes() Then AddSynthesizedAttribute(attributes, DeclaringCompilation.SynthesizeTupleNamesAttribute(returnType)) End If End Sub Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Return localPosition End Function Friend Overrides ReadOnly Property PreserveOriginalLocals As Boolean Get Return True End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsHierarchyEvents.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsHierarchyEvents { private uint _hierarchyEventsCookie; private void ConnectHierarchyEvents() { Debug.Assert(!this.AreHierarchyEventsConnected, "IVsHierarchyEvents are already connected!"); if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie))) { Debug.Fail("Failed to connect IVsHierarchyEvents"); _hierarchyEventsCookie = 0; } } private void DisconnectHierarchyEvents() { if (this.AreHierarchyEventsConnected) { Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie); _hierarchyEventsCookie = 0; } } private bool AreHierarchyEventsConnected { get { return _hierarchyEventsCookie != 0; } } int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if ((propid == (int)__VSHPROPID.VSHPROPID_Caption || propid == (int)__VSHPROPID.VSHPROPID_Name) && itemid == (uint)VSConstants.VSITEMID.Root) { var filePath = Hierarchy.TryGetProjectFilePath(); if (filePath != null && File.Exists(filePath)) { VisualStudioProject.FilePath = filePath; } if (Hierarchy.TryGetName(out var name)) { VisualStudioProject.DisplayName = name; } } return VSConstants.S_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsHierarchyEvents { private uint _hierarchyEventsCookie; private void ConnectHierarchyEvents() { Debug.Assert(!this.AreHierarchyEventsConnected, "IVsHierarchyEvents are already connected!"); if (ErrorHandler.Failed(Hierarchy.AdviseHierarchyEvents(this, out _hierarchyEventsCookie))) { Debug.Fail("Failed to connect IVsHierarchyEvents"); _hierarchyEventsCookie = 0; } } private void DisconnectHierarchyEvents() { if (this.AreHierarchyEventsConnected) { Hierarchy.UnadviseHierarchyEvents(_hierarchyEventsCookie); _hierarchyEventsCookie = 0; } } private bool AreHierarchyEventsConnected { get { return _hierarchyEventsCookie != 0; } } int IVsHierarchyEvents.OnInvalidateIcon(IntPtr hicon) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnInvalidateItems(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemDeleted(uint itemid) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnItemsAppended(uint itemidParent) => VSConstants.E_NOTIMPL; int IVsHierarchyEvents.OnPropertyChanged(uint itemid, int propid, uint flags) { if ((propid == (int)__VSHPROPID.VSHPROPID_Caption || propid == (int)__VSHPROPID.VSHPROPID_Name) && itemid == (uint)VSConstants.VSITEMID.Root) { var filePath = Hierarchy.TryGetProjectFilePath(); if (filePath != null && File.Exists(filePath)) { VisualStudioProject.FilePath = filePath; } if (Hierarchy.TryGetName(out var name)) { VisualStudioProject.DisplayName = name; } } return VSConstants.S_OK; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/Core/MSBuild/MSBuild/Constants/PropertyNames.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.MSBuild { internal static class PropertyNames { public const string AllowUnsafeBlocks = nameof(AllowUnsafeBlocks); public const string AppConfigForCompiler = nameof(AppConfigForCompiler); public const string BaseAddress = nameof(BaseAddress); public const string BuildProjectReferences = nameof(BuildProjectReferences); public const string BuildingInsideVisualStudio = nameof(BuildingInsideVisualStudio); public const string BuildingProject = nameof(BuildingProject); public const string CheckForOverflowUnderflow = nameof(CheckForOverflowUnderflow); public const string CodePage = nameof(CodePage); public const string ContinueOnError = nameof(ContinueOnError); public const string DebugSymbols = nameof(DebugSymbols); public const string DebugType = nameof(DebugType); public const string DefineConstants = nameof(DefineConstants); public const string DelaySign = nameof(DelaySign); public const string DesignTimeBuild = nameof(DesignTimeBuild); public const string DocFileItem = nameof(DocFileItem); public const string ErrorReport = nameof(ErrorReport); public const string Features = nameof(Features); public const string FileAlignment = nameof(FileAlignment); public const string FinalDefineConstants = nameof(FinalDefineConstants); public const string FrameworkPathOverride = nameof(FrameworkPathOverride); public const string GenerateDocumentation = nameof(GenerateDocumentation); public const string GenerateFullPaths = nameof(GenerateFullPaths); public const string HighEntropyVA = nameof(HighEntropyVA); public const string IntermediateAssembly = nameof(IntermediateAssembly); public const string KeyContainerName = nameof(KeyContainerName); public const string KeyOriginatorFile = nameof(KeyOriginatorFile); public const string LangVersion = nameof(LangVersion); public const string ModuleAssemblyName = nameof(ModuleAssemblyName); public const string NoCompilerStandardLib = nameof(NoCompilerStandardLib); public const string NonExistentFile = nameof(NonExistentFile); public const string NoWarn = nameof(NoWarn); public const string _NoWarnings = nameof(_NoWarnings); public const string Optimize = nameof(Optimize); public const string OptionCompare = nameof(OptionCompare); public const string OptionExplicit = nameof(OptionExplicit); public const string OptionInfer = nameof(OptionInfer); public const string OptionStrict = nameof(OptionStrict); public const string OptionStrictType = nameof(OptionStrictType); public const string OutputType = nameof(OutputType); public const string PdbFile = nameof(PdbFile); public const string PlatformTarget = nameof(PlatformTarget); public const string Prefer32Bit = nameof(Prefer32Bit); public const string ProvideCommandLineArgs = nameof(ProvideCommandLineArgs); public const string RemoveIntegerChecks = nameof(RemoveIntegerChecks); public const string ResolvedCodeAnalysisRuleSet = nameof(ResolvedCodeAnalysisRuleSet); public const string RootNamespace = nameof(RootNamespace); public const string ShouldUnsetParentConfigurationAndPlatform = nameof(ShouldUnsetParentConfigurationAndPlatform); public const string SignAssembly = nameof(SignAssembly); public const string SkipCompilerExecution = nameof(SkipCompilerExecution); public const string StartupObject = nameof(StartupObject); public const string SubsystemVersion = nameof(SubsystemVersion); public const string TargetCompactFramework = nameof(TargetCompactFramework); public const string TargetFramework = nameof(TargetFramework); public const string TargetFrameworks = nameof(TargetFrameworks); public const string TargetPath = nameof(TargetPath); public const string TargetRefPath = nameof(TargetRefPath); public const string TreatWarningsAsErrors = nameof(TreatWarningsAsErrors); public const string VbRuntime = nameof(VbRuntime); public const string WarningLevel = nameof(WarningLevel); public const string WarningsAsErrors = nameof(WarningsAsErrors); public const string WarningsNotAsErrors = nameof(WarningsNotAsErrors); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.MSBuild { internal static class PropertyNames { public const string AllowUnsafeBlocks = nameof(AllowUnsafeBlocks); public const string AppConfigForCompiler = nameof(AppConfigForCompiler); public const string BaseAddress = nameof(BaseAddress); public const string BuildProjectReferences = nameof(BuildProjectReferences); public const string BuildingInsideVisualStudio = nameof(BuildingInsideVisualStudio); public const string BuildingProject = nameof(BuildingProject); public const string CheckForOverflowUnderflow = nameof(CheckForOverflowUnderflow); public const string CodePage = nameof(CodePage); public const string ContinueOnError = nameof(ContinueOnError); public const string DebugSymbols = nameof(DebugSymbols); public const string DebugType = nameof(DebugType); public const string DefineConstants = nameof(DefineConstants); public const string DelaySign = nameof(DelaySign); public const string DesignTimeBuild = nameof(DesignTimeBuild); public const string DocFileItem = nameof(DocFileItem); public const string ErrorReport = nameof(ErrorReport); public const string Features = nameof(Features); public const string FileAlignment = nameof(FileAlignment); public const string FinalDefineConstants = nameof(FinalDefineConstants); public const string FrameworkPathOverride = nameof(FrameworkPathOverride); public const string GenerateDocumentation = nameof(GenerateDocumentation); public const string GenerateFullPaths = nameof(GenerateFullPaths); public const string HighEntropyVA = nameof(HighEntropyVA); public const string IntermediateAssembly = nameof(IntermediateAssembly); public const string KeyContainerName = nameof(KeyContainerName); public const string KeyOriginatorFile = nameof(KeyOriginatorFile); public const string LangVersion = nameof(LangVersion); public const string ModuleAssemblyName = nameof(ModuleAssemblyName); public const string NoCompilerStandardLib = nameof(NoCompilerStandardLib); public const string NonExistentFile = nameof(NonExistentFile); public const string NoWarn = nameof(NoWarn); public const string _NoWarnings = nameof(_NoWarnings); public const string Optimize = nameof(Optimize); public const string OptionCompare = nameof(OptionCompare); public const string OptionExplicit = nameof(OptionExplicit); public const string OptionInfer = nameof(OptionInfer); public const string OptionStrict = nameof(OptionStrict); public const string OptionStrictType = nameof(OptionStrictType); public const string OutputType = nameof(OutputType); public const string PdbFile = nameof(PdbFile); public const string PlatformTarget = nameof(PlatformTarget); public const string Prefer32Bit = nameof(Prefer32Bit); public const string ProvideCommandLineArgs = nameof(ProvideCommandLineArgs); public const string RemoveIntegerChecks = nameof(RemoveIntegerChecks); public const string ResolvedCodeAnalysisRuleSet = nameof(ResolvedCodeAnalysisRuleSet); public const string RootNamespace = nameof(RootNamespace); public const string ShouldUnsetParentConfigurationAndPlatform = nameof(ShouldUnsetParentConfigurationAndPlatform); public const string SignAssembly = nameof(SignAssembly); public const string SkipCompilerExecution = nameof(SkipCompilerExecution); public const string StartupObject = nameof(StartupObject); public const string SubsystemVersion = nameof(SubsystemVersion); public const string TargetCompactFramework = nameof(TargetCompactFramework); public const string TargetFramework = nameof(TargetFramework); public const string TargetFrameworks = nameof(TargetFrameworks); public const string TargetPath = nameof(TargetPath); public const string TargetRefPath = nameof(TargetRefPath); public const string TreatWarningsAsErrors = nameof(TreatWarningsAsErrors); public const string VbRuntime = nameof(VbRuntime); public const string WarningLevel = nameof(WarningLevel); public const string WarningsAsErrors = nameof(WarningsAsErrors); public const string WarningsNotAsErrors = nameof(WarningsNotAsErrors); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/ChangeSignature/Parameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ChangeSignature { /// <summary> /// Base type for Parameter information, whether the parameter /// is preexisting or new. /// </summary> internal abstract class Parameter { public abstract bool HasDefaultValue { get; } public abstract string Name { get; } } internal sealed class ExistingParameter : Parameter { public IParameterSymbol Symbol { get; } public ExistingParameter(IParameterSymbol param) { Symbol = param; } public override bool HasDefaultValue => Symbol.HasExplicitDefaultValue; public override string Name => Symbol.Name; } internal sealed class AddedParameter : Parameter { public AddedParameter( ITypeSymbol type, string typeName, string name, CallSiteKind callSiteKind, string callSiteValue = "", bool isRequired = true, string defaultValue = "", bool typeBinds = true) { Type = type; TypeBinds = typeBinds; TypeName = typeName; Name = name; CallSiteValue = callSiteValue; IsRequired = isRequired; DefaultValue = defaultValue; CallSiteKind = callSiteKind; // Populate the call site text for the UI switch (CallSiteKind) { case CallSiteKind.Value: case CallSiteKind.ValueWithName: CallSiteValue = callSiteValue; break; case CallSiteKind.Todo: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterIntroduceTODOVariable; break; case CallSiteKind.Omitted: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterOmitValue; break; case CallSiteKind.Inferred: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterInferValue; break; default: throw ExceptionUtilities.Unreachable; } } public override string Name { get; } public override bool HasDefaultValue => !string.IsNullOrWhiteSpace(DefaultValue); public ITypeSymbol Type { get; } public string TypeName { get; } public bool TypeBinds { get; } public CallSiteKind CallSiteKind { get; } /// <summary> /// Display string for the Call Site column in the Change Signature dialog. /// </summary> public string CallSiteValue { get; } /// <summary> /// True if required, false if optional with a default value. /// </summary> public bool IsRequired { get; } /// <summary> /// Value to use in the declaration of an optional parameter. /// E.g. the "3" in M(int x = 3); /// </summary> public string DefaultValue { get; } // For test purposes: to display assert failure details in tests. public override string ToString() => $"{Type.ToDisplayString(new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))} {Name} ({CallSiteValue})"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ChangeSignature { /// <summary> /// Base type for Parameter information, whether the parameter /// is preexisting or new. /// </summary> internal abstract class Parameter { public abstract bool HasDefaultValue { get; } public abstract string Name { get; } } internal sealed class ExistingParameter : Parameter { public IParameterSymbol Symbol { get; } public ExistingParameter(IParameterSymbol param) { Symbol = param; } public override bool HasDefaultValue => Symbol.HasExplicitDefaultValue; public override string Name => Symbol.Name; } internal sealed class AddedParameter : Parameter { public AddedParameter( ITypeSymbol type, string typeName, string name, CallSiteKind callSiteKind, string callSiteValue = "", bool isRequired = true, string defaultValue = "", bool typeBinds = true) { Type = type; TypeBinds = typeBinds; TypeName = typeName; Name = name; CallSiteValue = callSiteValue; IsRequired = isRequired; DefaultValue = defaultValue; CallSiteKind = callSiteKind; // Populate the call site text for the UI switch (CallSiteKind) { case CallSiteKind.Value: case CallSiteKind.ValueWithName: CallSiteValue = callSiteValue; break; case CallSiteKind.Todo: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterIntroduceTODOVariable; break; case CallSiteKind.Omitted: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterOmitValue; break; case CallSiteKind.Inferred: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterInferValue; break; default: throw ExceptionUtilities.Unreachable; } } public override string Name { get; } public override bool HasDefaultValue => !string.IsNullOrWhiteSpace(DefaultValue); public ITypeSymbol Type { get; } public string TypeName { get; } public bool TypeBinds { get; } public CallSiteKind CallSiteKind { get; } /// <summary> /// Display string for the Call Site column in the Change Signature dialog. /// </summary> public string CallSiteValue { get; } /// <summary> /// True if required, false if optional with a default value. /// </summary> public bool IsRequired { get; } /// <summary> /// Value to use in the declaration of an optional parameter. /// E.g. the "3" in M(int x = 3); /// </summary> public string DefaultValue { get; } // For test purposes: to display assert failure details in tests. public override string ToString() => $"{Type.ToDisplayString(new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))} {Name} ({CallSiteValue})"; } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Core/ExternalAccess/IntelliCode/IntentProcessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.IntelliCode.Api; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.IntelliCode { [Export(typeof(IIntentSourceProvider)), Shared] internal class IntentSourceProvider : IIntentSourceProvider { private readonly ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> _lazyIntentProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IntentSourceProvider([ImportMany] IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { _lazyIntentProviders = CreateProviderMap(lazyIntentProviders); } private static ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> CreateProviderMap( IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { return lazyIntentProviders.ToImmutableDictionary( provider => (provider.Metadata.LanguageName, provider.Metadata.IntentName), provider => provider); } public async Task<ImmutableArray<IntentSource>> ComputeIntentsAsync(IntentRequestContext intentRequestContext, CancellationToken cancellationToken) { var currentDocument = intentRequestContext.CurrentSnapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (currentDocument == null) { throw new ArgumentException("could not retrieve document for request snapshot"); } var languageName = currentDocument.Project.Language; if (!_lazyIntentProviders.TryGetValue((LanguageName: languageName, IntentName: intentRequestContext.IntentName), out var provider)) { Logger.Log(FunctionId.Intellicode_UnknownIntent, KeyValueLogMessage.Create(LogType.UserAction, m => { m["intent"] = intentRequestContext.IntentName; m["language"] = languageName; })); return ImmutableArray<IntentSource>.Empty; } var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var originalDocument = currentDocument.WithText(currentText.WithChanges(intentRequestContext.PriorTextEdits)); var selectionTextSpan = intentRequestContext.PriorSelection; var results = await provider.Value.ComputeIntentAsync( originalDocument, selectionTextSpan, currentDocument, intentRequestContext.IntentData, cancellationToken).ConfigureAwait(false); if (results.IsDefaultOrEmpty) { return ImmutableArray<IntentSource>.Empty; } using var _ = ArrayBuilder<IntentSource>.GetInstance(out var convertedResults); foreach (var result in results) { var convertedIntent = await ConvertToIntelliCodeResultAsync(result, originalDocument, currentDocument, cancellationToken).ConfigureAwait(false); convertedResults.AddIfNotNull(convertedIntent); } return convertedResults.ToImmutable(); } private static async Task<IntentSource?> ConvertToIntelliCodeResultAsync( IntentProcessorResult processorResult, Document originalDocument, Document currentDocument, CancellationToken cancellationToken) { var newSolution = processorResult.Solution; // Merge linked file changes so all linked files have the same text changes. newSolution = await newSolution.WithMergedLinkedFileChangesAsync(originalDocument.Project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); // For now we only support changes to the current document. Everything else is dropped. var changedDocument = newSolution.GetRequiredDocument(currentDocument.Id); var textDiffService = newSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); // Compute changes against the current version of the document. var textDiffs = await textDiffService.GetTextChangesAsync(currentDocument, changedDocument, cancellationToken).ConfigureAwait(false); if (textDiffs.IsEmpty) { return null; } return new IntentSource(processorResult.Title, textDiffs, processorResult.ActionName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ExternalAccess.IntelliCode.Api; using Microsoft.CodeAnalysis.Features.Intents; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.IntelliCode { [Export(typeof(IIntentSourceProvider)), Shared] internal class IntentSourceProvider : IIntentSourceProvider { private readonly ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> _lazyIntentProviders; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public IntentSourceProvider([ImportMany] IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { _lazyIntentProviders = CreateProviderMap(lazyIntentProviders); } private static ImmutableDictionary<(string LanguageName, string IntentName), Lazy<IIntentProvider, IIntentProviderMetadata>> CreateProviderMap( IEnumerable<Lazy<IIntentProvider, IIntentProviderMetadata>> lazyIntentProviders) { return lazyIntentProviders.ToImmutableDictionary( provider => (provider.Metadata.LanguageName, provider.Metadata.IntentName), provider => provider); } public async Task<ImmutableArray<IntentSource>> ComputeIntentsAsync(IntentRequestContext intentRequestContext, CancellationToken cancellationToken) { var currentDocument = intentRequestContext.CurrentSnapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (currentDocument == null) { throw new ArgumentException("could not retrieve document for request snapshot"); } var languageName = currentDocument.Project.Language; if (!_lazyIntentProviders.TryGetValue((LanguageName: languageName, IntentName: intentRequestContext.IntentName), out var provider)) { Logger.Log(FunctionId.Intellicode_UnknownIntent, KeyValueLogMessage.Create(LogType.UserAction, m => { m["intent"] = intentRequestContext.IntentName; m["language"] = languageName; })); return ImmutableArray<IntentSource>.Empty; } var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var originalDocument = currentDocument.WithText(currentText.WithChanges(intentRequestContext.PriorTextEdits)); var selectionTextSpan = intentRequestContext.PriorSelection; var results = await provider.Value.ComputeIntentAsync( originalDocument, selectionTextSpan, currentDocument, intentRequestContext.IntentData, cancellationToken).ConfigureAwait(false); if (results.IsDefaultOrEmpty) { return ImmutableArray<IntentSource>.Empty; } using var _ = ArrayBuilder<IntentSource>.GetInstance(out var convertedResults); foreach (var result in results) { var convertedIntent = await ConvertToIntelliCodeResultAsync(result, originalDocument, currentDocument, cancellationToken).ConfigureAwait(false); convertedResults.AddIfNotNull(convertedIntent); } return convertedResults.ToImmutable(); } private static async Task<IntentSource?> ConvertToIntelliCodeResultAsync( IntentProcessorResult processorResult, Document originalDocument, Document currentDocument, CancellationToken cancellationToken) { var newSolution = processorResult.Solution; // Merge linked file changes so all linked files have the same text changes. newSolution = await newSolution.WithMergedLinkedFileChangesAsync(originalDocument.Project.Solution, cancellationToken: cancellationToken).ConfigureAwait(false); // For now we only support changes to the current document. Everything else is dropped. var changedDocument = newSolution.GetRequiredDocument(currentDocument.Id); var textDiffService = newSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>(); // Compute changes against the current version of the document. var textDiffs = await textDiffService.GetTextChangesAsync(currentDocument, changedDocument, cancellationToken).ConfigureAwait(false); if (textDiffs.IsEmpty) { return null; } return new IntentSource(processorResult.Title, textDiffs, processorResult.ActionName); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Conversion.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Dim result = DirectCast(Visit(node.Operand), BoundExpression) If node.ExplicitCastInCode AndAlso IsFloatingPointExpressionOfUnknownPrecision(result) Then ' To force a value of a floating point type to the exact precision of its type, an explicit cast can be used. ' It means that explicit casts to CDbl() or CSng() should be preserved on the node. ' If original conversion has become something else with unknown precision, add an explicit identity cast. result = node.Update( result, ConversionKind.Identity, checked:=False, explicitCastInCode:=True, constantValueOpt:=node.ConstantValueOpt, extendedInfoOpt:=node.ExtendedInfoOpt, type:=node.Type) End If Return result End If If node.Operand.Kind = BoundKind.UserDefinedConversion Then If _inExpressionLambda Then Return node.Update(DirectCast(Visit(node.Operand), BoundExpression), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, node.Type) End If If (node.ConversionKind And ConversionKind.Nullable) <> 0 Then Return RewriteNullableUserDefinedConversion(DirectCast(node.Operand, BoundUserDefinedConversion)) End If Return Visit(DirectCast(node.Operand, BoundUserDefinedConversion).UnderlyingExpression) End If ' not all nullable conversions have Nullable flag ' For example Nothing --> Boolean? has conversionkind = WideningNothingLiteral If (node.Type IsNot Nothing AndAlso node.Type.IsNullableType OrElse node.Operand.Type IsNot Nothing AndAlso node.Operand.Type.IsNullableType) AndAlso Not _inExpressionLambda Then Return RewriteNullableConversion(node) End If ' Rewrite Anonymous Delegate conversion into a delegate creation If (node.ConversionKind And ConversionKind.AnonymousDelegate) <> 0 Then Return RewriteAnonymousDelegateConversion(node) End If ' Handle other conversions. Debug.Assert(TryCast(node.ExtendedInfoOpt, BoundRelaxationLambda)?.ReceiverPlaceholderOpt Is Nothing) ' Optimization for object comparisons that are operands of a conversion to boolean. ' Must be done before the object comparison is visited. If Not node.HasErrors AndAlso node.Type.IsBooleanType() AndAlso node.Operand.Type.IsObjectType() Then Dim operand As BoundNode = node.Operand ' Skip parens. While operand.Kind = BoundKind.Parenthesized operand = DirectCast(operand, BoundParenthesized).Expression End While If operand.Kind = BoundKind.BinaryOperator Then Dim binary = DirectCast(operand, BoundBinaryOperator) Select Case binary.OperatorKind And BinaryOperatorKind.OpMask Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThan, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.GreaterThanOrEqual ' Attempt to optimize the coercion. ' The result of the comparison is known to be boolean, so force it to be. ' Rewrite of the operator will do the right thing. Debug.Assert(binary.Type.IsObjectType()) Return Visit(binary.Update(binary.OperatorKind, binary.Left, binary.Right, binary.Checked, binary.ConstantValueOpt, node.Type)) End Select End If End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.ExtendedInfoOpt IsNot Nothing AndAlso node.ExtendedInfoOpt.Kind = BoundKind.RelaxationLambda Then returnValue = RewriteLambdaRelaxationConversion(node) ElseIf (node.ConversionKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString Then returnValue = RewriteInterpolatedStringConversion(node) ElseIf (node.ConversionKind And (ConversionKind.Tuple Or ConversionKind.Nullable)) = ConversionKind.Tuple Then returnValue = RewriteTupleConversion(node) Else returnValue = MyBase.VisitConversion(node) If returnValue.Kind = BoundKind.Conversion Then returnValue = TransformRewrittenConversion(DirectCast(returnValue, BoundConversion)) End If End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function Private Shared Function IsFloatingPointExpressionOfUnknownPrecision(rewrittenNode As BoundExpression) As Boolean If rewrittenNode Is Nothing Then Return False End If ' Note: no special handling for node having a constant value because it cannot reach here Dim specialType = rewrittenNode.Type.SpecialType If specialType <> SpecialType.System_Double AndAlso specialType <> SpecialType.System_Single Then Return False End If Select Case rewrittenNode.Kind ' ECMA-335 I.12.1.3 Handling of floating-point data types. ' ... the value might be retained in the internal representation ' for future use, if it is reloaded from the storage location without having been modified ... ' ' Unfortunately, the above means that precision is not guaranteed even when loading from storage. ' ' Case BoundKind.FieldAccess ' Case BoundKind.ArrayAccess ' Return True Case BoundKind.Sequence Dim sequence = DirectCast(rewrittenNode, BoundSequence) Return IsFloatingPointExpressionOfUnknownPrecision(sequence.ValueOpt) Case BoundKind.Conversion ' lowered conversions have definite precision unless they are implicit identity casts Dim conversion = DirectCast(rewrittenNode, BoundConversion) Return conversion.ConversionKind = ConversionKind.Identity AndAlso Not conversion.ExplicitCastInCode End Select ' it is a float/double expression and we have no idea ... Return True End Function Private Function RewriteTupleConversion(node As BoundConversion) As BoundExpression Dim syntax = node.Syntax Dim rewrittenOperand = VisitExpression(node.Operand) Dim rewrittenType = DirectCast(VisitType(node.Type), NamedTypeSymbol) Return MakeTupleConversion(syntax, rewrittenOperand, rewrittenType, DirectCast(node.ExtendedInfoOpt, BoundConvertedTupleElements)) End Function Private Function MakeTupleConversion(syntax As SyntaxNode, rewrittenOperand As BoundExpression, destinationType As TypeSymbol, convertedElements As BoundConvertedTupleElements) As BoundExpression If destinationType.IsSameTypeIgnoringAll(rewrittenOperand.Type) Then 'binder keeps some tuple conversions just for the purpose of semantic model 'otherwise they are as good as identity conversions Return rewrittenOperand End If Dim destElementTypes = destinationType.GetElementTypesOfTupleOrCompatible() Dim numElements = destElementTypes.Length Dim srcType As TypeSymbol = rewrittenOperand.Type Dim tupleTypeSymbol As TupleTypeSymbol If srcType.IsTupleType Then tupleTypeSymbol = DirectCast(srcType, TupleTypeSymbol) Else ' The following codepath should be very uncommon (if reachable at all) ' we should generally not see tuple compatible types in bound trees and ' see actual tuple types instead. Debug.Assert(srcType.IsTupleCompatible()) ' PERF: if allocations here become nuisance, consider caching the TupleTypeSymbol ' in the type symbols that can actually be tuple compatible tupleTypeSymbol = TupleTypeSymbol.Create(DirectCast(srcType, NamedTypeSymbol)) End If Dim srcElementFields = tupleTypeSymbol.TupleElements Dim fieldAccessorsBuilder = ArrayBuilder(Of BoundExpression).GetInstance(numElements) Dim assignmentToTemp As BoundExpression = Nothing Dim tupleTemp As SynthesizedLocal = Nothing Dim savedTuple As BoundExpression = CaptureOperand(rewrittenOperand, tupleTemp, assignmentToTemp) Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, syntax, _compilationState, _diagnostics) For i As Integer = 0 To numElements - 1 Dim field = srcElementFields(i) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = field.CalculateUseSiteInfo() ReportUseSite(rewrittenOperand, useSiteInfo, _diagnostics) Dim fieldAccess = MakeTupleFieldAccess(syntax, field, savedTuple, constantValueOpt:=Nothing, isLValue:=False) ' lower the conversion AddPlaceholderReplacement(convertedElements.ElementPlaceholders(i), fieldAccess) fieldAccessorsBuilder.Add(VisitExpression(convertedElements.ConvertedElements(i))) RemovePlaceholderReplacement(convertedElements.ElementPlaceholders(i)) Next Dim result = MakeTupleCreationExpression(syntax, DirectCast(destinationType, NamedTypeSymbol), fieldAccessorsBuilder.ToImmutableAndFree()) Return factory.Sequence(tupleTemp, assignmentToTemp, result) End Function Private Function RewriteLambdaRelaxationConversion(node As BoundConversion) As BoundNode Dim returnValue As BoundNode Dim relaxationLambda As BoundLambda = DirectCast(node.ExtendedInfoOpt, BoundRelaxationLambda).Lambda If _inExpressionLambda AndAlso NoParameterRelaxation(node.Operand, relaxationLambda.LambdaSymbol) Then ' COMPAT: skip relaxation in this case. ET can drop the return value of the inner lambda. returnValue = MyBase.VisitConversion( node.Update(node.Operand, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, extendedInfoOpt:=Nothing, type:=node.Type)) returnValue = TransformRewrittenConversion(DirectCast(returnValue, BoundConversion)) Else returnValue = node.Update(VisitExpressionNode(relaxationLambda), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, extendedInfoOpt:=Nothing, type:=node.Type) End If Return returnValue End Function Private Function RewriteLambdaRelaxationConversion(node As BoundDirectCast) As BoundNode Dim returnValue As BoundNode If _inExpressionLambda AndAlso NoParameterRelaxation(node.Operand, node.RelaxationLambdaOpt.LambdaSymbol) Then ' COMPAT: skip relaxation in this case. ET can drop the return value of the inner lambda. returnValue = MyBase.VisitDirectCast( node.Update(node.Operand, node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type)) Else returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type) End If Return returnValue End Function Private Function RewriteLambdaRelaxationConversion(node As BoundTryCast) As BoundNode Dim returnValue As BoundNode If _inExpressionLambda AndAlso NoParameterRelaxation(node.Operand, node.RelaxationLambdaOpt.LambdaSymbol) Then ' COMPAT: skip relaxation in this case. ET can drop the return value of the inner lambda. returnValue = MyBase.VisitTryCast( node.Update(node.Operand, node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type)) Else returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type) End If Return returnValue End Function Private Shared Function NoParameterRelaxation(from As BoundExpression, toLambda As LambdaSymbol) As Boolean Dim fromLambda As LambdaSymbol = TryCast(from, BoundLambda)?.LambdaSymbol ' are we are relaxing for the purpose of dropping return? Return fromLambda IsNot Nothing AndAlso Not fromLambda.IsSub AndAlso toLambda.IsSub AndAlso MethodSignatureComparer.HaveSameParameterTypes(fromLambda.Parameters, Nothing, toLambda.Parameters, Nothing, considerByRef:=True, considerCustomModifiers:=False, considerTupleNames:=False) End Function ' Rewrite Anonymous Delegate conversion into a delegate creation Private Function RewriteAnonymousDelegateConversion(node As BoundConversion) As BoundNode Debug.Assert(Not Conversions.IsIdentityConversion(node.ConversionKind)) Debug.Assert(node.Operand.Type.IsDelegateType() AndAlso DirectCast(node.Operand.Type, NamedTypeSymbol).IsAnonymousType AndAlso node.Type.IsDelegateType() AndAlso node.Type.SpecialType <> SpecialType.System_MulticastDelegate) Dim F As New SyntheticBoundNodeFactory(Me._topMethod, Me._currentMethodOrLambda, node.Syntax, Me._compilationState, Me._diagnostics) If (node.Operand.IsDefaultValueConstant) Then Return F.Null(node.Type) Else Dim lambdaOpt As BoundLambda Dim receiverPlaceholderOpt As BoundRValuePlaceholder If node.ExtendedInfoOpt IsNot Nothing Then Dim relaxationLambda = DirectCast(node.ExtendedInfoOpt, BoundRelaxationLambda) lambdaOpt = relaxationLambda.Lambda receiverPlaceholderOpt = relaxationLambda.ReceiverPlaceholderOpt Else lambdaOpt = Nothing receiverPlaceholderOpt = Nothing End If If (Not Me._inExpressionLambda AndAlso CouldPossiblyBeNothing(F, node.Operand)) Then Dim savedOriginalValue = F.SynthesizedLocal(node.Operand.Type) Dim checkIfNothing = F.ReferenceIsNothing(F.Local(savedOriginalValue, False)) Dim conversionIfNothing = F.Null(node.Type) Dim convertedValue = New BoundDelegateCreationExpression(node.Syntax, F.Local(savedOriginalValue, False), DirectCast(node.Operand.Type, NamedTypeSymbol).DelegateInvokeMethod, lambdaOpt, receiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=node.Type) Dim conditionalResult As BoundExpression = F.TernaryConditionalExpression(condition:=checkIfNothing, ifTrue:=conversionIfNothing, ifFalse:=convertedValue) Return F.Sequence(savedOriginalValue, F.AssignmentExpression(F.Local(savedOriginalValue, True), VisitExpression(node.Operand)), VisitExpression(conditionalResult)) Else Dim convertedValue = New BoundDelegateCreationExpression(node.Syntax, node.Operand, DirectCast(node.Operand.Type, NamedTypeSymbol).DelegateInvokeMethod, lambdaOpt, receiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=node.Type) Return VisitExpression(convertedValue) End If End If End Function Private Function CouldPossiblyBeNothing(F As SyntheticBoundNodeFactory, node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.TernaryConditionalExpression Dim t = DirectCast(node, BoundTernaryConditionalExpression) Return CouldPossiblyBeNothing(F, t.WhenTrue) OrElse CouldPossiblyBeNothing(F, t.WhenFalse) Case BoundKind.Conversion Dim t = DirectCast(node, BoundConversion) Return CouldPossiblyBeNothing(F, t.Operand) Case BoundKind.Lambda Return False Case BoundKind.Call Dim t = DirectCast(node, BoundCall) Return Not (t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Delegate__CreateDelegate, True) OrElse t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Delegate__CreateDelegate4, True) OrElse t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Reflection_MethodInfo__CreateDelegate, True)) Case Else Return True End Select End Function Private Function RewriteNullableConversion(node As BoundConversion) As BoundExpression Debug.Assert(Not _inExpressionLambda) Dim rewrittenOperand = DirectCast(Me.Visit(node.Operand), BoundExpression) If Conversions.IsIdentityConversion(node.ConversionKind) Then Debug.Assert(rewrittenOperand.Type.IsSameTypeIgnoringAll(node.Type)) Return rewrittenOperand End If Return RewriteNullableConversion(node, rewrittenOperand) End Function Private Function RewriteNullableConversion(node As BoundConversion, rewrittenOperand As BoundExpression) As BoundExpression Dim resultType = node.Type Dim operandType = rewrittenOperand.Type Debug.Assert(resultType.IsNullableType OrElse (operandType IsNot Nothing AndAlso operandType.IsNullableType), "operand or operator must be nullable") ' Nothing --> T? ==> new T? If rewrittenOperand.ConstantValueOpt Is ConstantValue.Nothing Then Return NullableNull(rewrittenOperand.Syntax, resultType) End If ' Conversions between reference types and nullables do not need further rewriting. ' Lifting will be done as part of box/unbox operation. If operandType.IsReferenceType OrElse resultType.IsReferenceType Then If resultType.IsStringType Then ' conversion to string is an intrinsic conversion and can be lifted. ' T? --> string ==> T.Value -- string ' note that nullable null does not convert to string, i.e. this conversion ' is not null-propagating rewrittenOperand = NullableValue(rewrittenOperand) ElseIf operandType.IsStringType Then ' CType(string, T?) ---> new T?(CType(string, T)) Dim innerTargetType = resultType.GetNullableUnderlyingType Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyConversion(rewrittenOperand.Type, innerTargetType, useSiteInfo).Key Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return WrapInNullable( TransformRewrittenConversion( node.Update(rewrittenOperand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType.GetNullableUnderlyingType)), resultType) ElseIf operandType.IsNullableType Then If HasNoValue(rewrittenOperand) Then ' DirectCast(Nothing, operatorType) Return New BoundDirectCast(node.Syntax, MakeNullLiteral(rewrittenOperand.Syntax, resultType), ConversionKind.WideningNothingLiteral, resultType) End If If HasValue(rewrittenOperand) Then ' DirectCast(operand.GetValueOrDefault, operatorType) Dim unwrappedOperand = NullableValueOrDefault(rewrittenOperand) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(unwrappedOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return New BoundDirectCast(node.Syntax, unwrappedOperand, convKind, resultType) End If End If Return TransformRewrittenConversion( node.Update(rewrittenOperand, node.ConversionKind And (Not ConversionKind.Nullable), node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType)) End If Debug.Assert(Not resultType.IsSameTypeIgnoringAll(operandType), "converting to same type") Dim result As BoundExpression = rewrittenOperand ' unwrap operand if needed and propagate HasValue if needed. ' If need to propagate HasValue, may also need to hoist the operand value into a temp Dim operandHasValue As BoundExpression = Nothing Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing If operandType.IsNullableType Then If resultType.IsNullableType Then If HasValue(rewrittenOperand) Then ' just get the value result = NullableValueOrDefault(rewrittenOperand) ElseIf HasNoValue(rewrittenOperand) Then ' converting null Return NullableNull(result.Syntax, resultType) Else Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(rewrittenOperand, whenNotNull, whenNull) Then If HasValue(whenNotNull) AndAlso HasNoValue(whenNull) Then Return UpdateConditionalAccess(rewrittenOperand, FinishRewriteNullableConversion(node, resultType, NullableValueOrDefault(whenNotNull), Nothing, Nothing, Nothing), NullableNull(result.Syntax, resultType)) End If End If ' uncaptured locals are safe here because we are dealing with a single operand result = ProcessNullableOperand(rewrittenOperand, operandHasValue, temps, inits, doNotCaptureLocals:=True) End If Else ' no propagation. result = NullableValue(rewrittenOperand) End If End If Return FinishRewriteNullableConversion(node, resultType, result, operandHasValue, temps, inits) End Function Private Function GetNewCompoundUseSiteInfo() As CompoundUseSiteInfo(Of AssemblySymbol) Return New CompoundUseSiteInfo(Of AssemblySymbol)(_diagnostics, Me.Compilation.Assembly) End Function Private Function FinishRewriteNullableConversion( node As BoundConversion, resultType As TypeSymbol, operand As BoundExpression, operandHasValue As BoundExpression, temps As ArrayBuilder(Of LocalSymbol), inits As ArrayBuilder(Of BoundExpression) ) As BoundExpression Debug.Assert(resultType Is node.Type) Dim unwrappedResultType = resultType.GetNullableUnderlyingTypeOrSelf ' apply unlifted conversion If Not operand.Type.IsSameTypeIgnoringAll(unwrappedResultType) Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyConversion(operand.Type, unwrappedResultType, useSiteInfo).Key Debug.Assert(Conversions.ConversionExists(convKind)) Debug.Assert((convKind And ConversionKind.Tuple) = (node.ConversionKind And ConversionKind.Tuple)) ' Check for potential constant folding Dim integerOverflow As Boolean = False Dim constantResult = Conversions.TryFoldConstantConversion(operand, unwrappedResultType, integerOverflow) Debug.Assert(constantResult Is Nothing OrElse Not constantResult.IsBad) If constantResult IsNot Nothing AndAlso Not constantResult.IsBad Then ' Overflow should have been detected at classification time during binding. Debug.Assert(Not integerOverflow OrElse Not node.Checked) operand = RewriteConstant(New BoundLiteral(node.Syntax, constantResult, unwrappedResultType), constantResult) Else _diagnostics.Add(node, useSiteInfo) If (convKind And ConversionKind.Tuple) <> 0 Then operand = MakeTupleConversion(node.Syntax, operand, unwrappedResultType, DirectCast(node.ExtendedInfoOpt, BoundConvertedTupleElements)) Else operand = TransformRewrittenConversion(New BoundConversion(node.Syntax, operand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, unwrappedResultType)) End If End If End If ' wrap if needed If resultType.IsNullableType Then operand = WrapInNullable(operand, resultType) ' propagate null from the operand If operandHasValue IsNot Nothing Then operand = MakeTernaryConditionalExpression(node.Syntax, operandHasValue, operand, NullableNull(operand.Syntax, resultType)) ' if used temps, arrange a sequence for temps and inits. If temps IsNot Nothing Then operand = New BoundSequence(operand.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, operand, operand.Type) End If End If End If Return operand End Function Private Function RewriteNullableReferenceConversion(node As BoundConversion, rewrittenOperand As BoundExpression) As BoundExpression Dim resultType = node.Type Dim operandType = rewrittenOperand.Type If operandType.IsStringType Then ' CType(string, T?) ---> new T?(CType(string, T)) Dim innerTargetType = resultType.GetNullableUnderlyingType Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyConversion(operandType, innerTargetType, useSiteInfo).Key Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return WrapInNullable( TransformRewrittenConversion( node.Update(rewrittenOperand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType.GetNullableUnderlyingType)), resultType) End If If resultType.IsStringType Then ' conversion to string is an intrinsic conversion and can be lifted. ' T? --> string ==> T.Value -- string ' note that nullable null does not convert to string null, i.e. this conversion ' is not null-propagating rewrittenOperand = NullableValue(rewrittenOperand) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return TransformRewrittenConversion( node.Update(rewrittenOperand, node.ConversionKind And (Not ConversionKind.Nullable), node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType)) End If If operandType.IsNullableType Then ' T? --> RefType, this is a boxing conversion (DirectCast) If HasNoValue(rewrittenOperand) Then ' DirectCast(Nothing, operatorType) Return New BoundDirectCast(node.Syntax, MakeNullLiteral(rewrittenOperand.Syntax, resultType), ConversionKind.WideningNothingLiteral, resultType) End If If HasValue(rewrittenOperand) Then ' DirectCast(operand.GetValueOrDefault, operatorType) Dim unwrappedOperand = NullableValueOrDefault(rewrittenOperand) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(unwrappedOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return New BoundDirectCast(node.Syntax, unwrappedOperand, convKind, resultType) End If End If If resultType.IsNullableType Then ' RefType --> T? , this is just an unboxing conversion. Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return New BoundDirectCast(node.Syntax, rewrittenOperand, convKind, resultType) End If Throw ExceptionUtilities.Unreachable End Function Private Function RewriteNullableUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode ' User defined conversions rewrite as: ' Sequence(operandCapture, If(operandCapture.HasValue, Conversion(operandCapture), Null) ' ' The structure of the nullable BoundUserDefinedConversion looks like this: ' [OPERAND] -> [IN-CONVERSION] -> [CALL] -> [OUT-CONVERSION] ' ' In-conversion also does unwrapping. ' Out-conversion also does wrapping. ' ' operand ' the thing that we will be converting. Must be nullable. We will be checking HasValue on it and will return null if it does not. Dim operand = node.Operand Debug.Assert(operand.Type.IsNullableType) ' inner conversion Dim inConversion = node.InConversionOpt Debug.Assert(inConversion IsNot Nothing, "There is always an inner conversion.") ' operator Dim operatorCall As BoundCall = node.Call ' outer conversion Dim outConversion As BoundConversion = node.OutConversionOpt Debug.Assert(outConversion IsNot Nothing, "There is always an outer conversion.") ' result type ' type that we need to return from the conversion. It must be a nullable type. Dim resultType As TypeSymbol = outConversion.Type Debug.Assert(resultType.IsNullableType, "lifted operator must have nullable type") ' === START REWRITE Dim rewrittenOperand = Me.VisitExpressionNode(operand) ' this is what we return when operand has no value Dim whenHasNoValue As BoundExpression = NullableNull(node.Syntax, resultType) '== TRIVIAL CASE If HasNoValue(rewrittenOperand) Then Return whenHasNoValue End If ' Do we know statically that operand has value? Dim operandHasValue As Boolean = HasValue(rewrittenOperand) ' This is what we will pass to the operator method if operand has value Dim inputToOperatorMethod As BoundExpression Dim condition As BoundExpression = Nothing Dim temp As SynthesizedLocal = Nothing If operandHasValue Then ' just pass the operand, no need to capture inputToOperatorMethod = rewrittenOperand Else ' operator input would be captured operand Dim tempInit As BoundExpression = Nothing ' no need to capture locals since we will not ' evaluate anything between HasValue and ValueOrDefault Dim capturedleft As BoundExpression = CaptureNullableIfNeeded(rewrittenOperand, temp, tempInit, doNotCaptureLocals:=True) condition = NullableHasValue(If(tempInit, capturedleft)) ' Note that we will be doing the conversion only when ' we know that we have a value, so we will pass to the conversion wrapped NullableValueOrDefault. ' so that it could use NullableValueOrDefault instead of Value. inputToOperatorMethod = WrapInNullable(NullableValueOrDefault(capturedleft), capturedleft.Type) End If ' inConversion is always a nullable conversion. We need to rewrite it. inputToOperatorMethod = RewriteNullableConversion(inConversion, inputToOperatorMethod) ' result of the conversion when operand has value. (replace the arg) Dim whenHasValue As BoundExpression = operatorCall.Update(operatorCall.Method, Nothing, operatorCall.ReceiverOpt, ImmutableArray.Create(inputToOperatorMethod), Nothing, operatorCall.ConstantValueOpt, isLValue:=operatorCall.IsLValue, suppressObjectClone:=operatorCall.SuppressObjectClone, type:=operatorCall.Type) ' outConversion is a nullable conversion. need to rewrite it. whenHasValue = RewriteNullableConversion(outConversion, whenHasValue) ' Now we have whenHasValue, whenHasNoValue and condition. The rest is easy. If operandHasValue Then Return whenHasValue Else ' == rewrite operand as ternary expression Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, whenHasValue, whenHasNoValue) ' if we used a temp, arrange a sequence for it If temp IsNot Nothing Then result = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If Return result End If End Function #Region "Post-rewrite conversion" Private Function TransformRewrittenConversion(rewrittenConversion As BoundConversion) As BoundExpression If rewrittenConversion.HasErrors OrElse _inExpressionLambda Then Return rewrittenConversion End If Dim result As BoundExpression = rewrittenConversion Dim underlyingTypeTo = rewrittenConversion.Type.GetEnumUnderlyingTypeOrSelf() Dim operand = rewrittenConversion.Operand If operand.IsNothingLiteral() Then Debug.Assert(rewrittenConversion.ConversionKind = ConversionKind.WideningNothingLiteral OrElse (Conversions.IsIdentityConversion(rewrittenConversion.ConversionKind) AndAlso Not underlyingTypeTo.IsTypeParameter() AndAlso underlyingTypeTo.IsReferenceType) OrElse (rewrittenConversion.ConversionKind And (ConversionKind.Reference Or ConversionKind.Array)) <> 0) If underlyingTypeTo.IsTypeParameter() OrElse underlyingTypeTo.IsReferenceType Then result = RewriteAsDirectCast(rewrittenConversion) Else Debug.Assert(underlyingTypeTo.IsValueType) End If ElseIf operand.Kind = BoundKind.Lambda Then Return rewrittenConversion Else Dim underlyingTypeFrom = operand.Type.GetEnumUnderlyingTypeOrSelf() If underlyingTypeFrom.IsFloatingType() AndAlso underlyingTypeTo.IsIntegralType() Then result = RewriteFloatingToIntegralConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsDecimalType() AndAlso (underlyingTypeTo.IsBooleanType() OrElse underlyingTypeTo.IsIntegralType() OrElse underlyingTypeTo.IsFloatingType) Then result = RewriteDecimalToNumericOrBooleanConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsDecimalType() AndAlso (underlyingTypeFrom.IsBooleanType() OrElse underlyingTypeFrom.IsIntegralType() OrElse underlyingTypeFrom.IsFloatingType) Then result = RewriteNumericOrBooleanToDecimalConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsNullableType OrElse underlyingTypeTo.IsNullableType Then ' conversions between nullable and reference types are not directcasts, they are boxing/unboxing conversions. ' CodeGen will handle this. ElseIf underlyingTypeFrom.IsObjectType() AndAlso (underlyingTypeTo.IsTypeParameter() OrElse underlyingTypeTo.IsIntrinsicType()) Then result = RewriteFromObjectConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsTypeParameter() Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeTo.IsTypeParameter() Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeFrom.IsStringType() AndAlso (underlyingTypeTo.IsCharSZArray() OrElse underlyingTypeTo.IsIntrinsicValueType()) Then result = RewriteFromStringConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsStringType() AndAlso (underlyingTypeFrom.IsCharSZArray() OrElse underlyingTypeFrom.IsIntrinsicValueType()) Then result = RewriteToStringConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsReferenceType AndAlso underlyingTypeTo.IsCharSZArray() Then result = RewriteReferenceTypeToCharArrayRankOneConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsReferenceType Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeFrom.IsReferenceType AndAlso underlyingTypeTo.IsIntrinsicValueType() Then result = RewriteFromObjectConversion(rewrittenConversion, Compilation.GetSpecialType(SpecialType.System_Object), underlyingTypeTo) Else Debug.Assert(underlyingTypeTo.IsValueType) End If End If Return result End Function Private Function RewriteReferenceTypeToCharArrayRankOneConversion(node As BoundConversion, typeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsReferenceType AndAlso typeTo.IsCharSZArray()) Dim result As BoundExpression = node Const member As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.Parameters(0).Type.IsObjectType()) If Not operand.Type.IsObjectType() Then Dim objectType As TypeSymbol = memberSymbol.Parameters(0).Type Dim useSiteInfo = GetNewCompoundUseSiteInfo() operand = New BoundDirectCast(operand.Syntax, operand, Conversions.ClassifyDirectCastConversion(operand.Type, objectType, useSiteInfo), objectType) _diagnostics.Add(node, useSiteInfo) End If result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringAll(node.Type)) End If Return result End Function Private Shared Function RewriteAsDirectCast(node As BoundConversion) As BoundExpression Debug.Assert(node.Operand.IsNothingLiteral() OrElse (node.ConversionKind And (Not ConversionKind.DelegateRelaxationLevelMask)) = Conversions.ClassifyDirectCastConversion(node.Operand.Type, node.Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) ' TODO: A chain of widening reference conversions that starts from NOTHING literal can be collapsed to a single node. ' Semantics::Convert does this in Dev10. ' It looks like we already achieve the same result due to folding of NOTHING conversions. Return New BoundDirectCast(node.Syntax, node.Operand, node.ConversionKind, node.Type, Nothing) End Function Private Function RewriteFromObjectConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsObjectType()) Dim result As BoundExpression = node Dim member As WellKnownMember = WellKnownMember.Count Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject Case SpecialType.System_SByte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject Case SpecialType.System_Int16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject Case SpecialType.System_UInt16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject Case SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject Case SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject Case SpecialType.System_String : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject Case Else If underlyingTypeTo.IsTypeParameter() Then member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object End If End Select If member <> WellKnownMember.Count Then Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then If member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object Then memberSymbol = memberSymbol.Construct(underlyingTypeTo) End If Dim operand = node.Operand If Not operand.Type.IsObjectType() Then Debug.Assert(typeFrom.IsObjectType()) Debug.Assert(operand.Type.IsReferenceType) Debug.Assert(underlyingTypeTo.IsIntrinsicValueType()) Dim useSiteInfo = GetNewCompoundUseSiteInfo() operand = New BoundDirectCast(operand.Syntax, operand, Conversions.ClassifyDirectCastConversion(operand.Type, typeFrom, useSiteInfo), typeFrom) _diagnostics.Add(node, useSiteInfo) End If Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringAll(underlyingTypeTo)) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If Not targetResultType.IsSameTypeIgnoringAll(memberSymbol.ReturnType) Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If End If Return result End Function Private Function RewriteToStringConversion(node As BoundConversion, underlyingTypeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeTo.IsStringType()) Dim result As BoundExpression = node Dim memberSymbol As MethodSymbol = Nothing If underlyingTypeFrom.IsCharSZArray() Then Const memberId As SpecialMember = SpecialMember.System_String__CtorSZArrayChar memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then memberSymbol = Nothing End If Else Dim member As WellKnownMember = WellKnownMember.Count ' Note, conversion from Object is handled by RewriteFromObjectConversion. Select Case underlyingTypeFrom.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean Case SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte Case SpecialType.System_UInt16, SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar End Select If member <> WellKnownMember.Count Then memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then memberSymbol = Nothing End If End If End If If memberSymbol IsNot Nothing Then Dim operand = node.Operand Dim operandType = operand.Type If Not operandType.IsSameTypeIgnoringAll(memberSymbol.Parameters(0).Type) Then Dim conv As ConversionKind If operandType.IsEnumType() Then conv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions Else conv = ConversionKind.WideningNumeric End If Debug.Assert(conv = Conversions.ClassifyConversion(operandType, memberSymbol.Parameters(0).Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) operand = New BoundConversion(node.Syntax, operand, conv, node.Checked, node.ExplicitCastInCode, memberSymbol.Parameters(0).Type, Nothing) End If If memberSymbol.MethodKind = MethodKind.Constructor Then Debug.Assert(memberSymbol.ContainingType Is typeTo) result = New BoundObjectCreationExpression( node.Syntax, memberSymbol, ImmutableArray.Create(operand), Nothing, typeTo) Else Debug.Assert(memberSymbol.ReturnType Is typeTo) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteFromStringConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsStringType()) Dim result As BoundExpression = node Dim member As WellKnownMember = WellKnownMember.Count Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString Case SpecialType.System_SByte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString Case SpecialType.System_Int16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString Case SpecialType.System_UInt16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString Case SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString Case SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString Case Else If underlyingTypeTo.IsCharSZArray() Then member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString End If End Select If member <> WellKnownMember.Count Then Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringAll(underlyingTypeTo)) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If Not targetResultType.IsSameTypeIgnoringAll(memberSymbol.ReturnType) Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If End If Return result End Function Private Function RewriteNumericOrBooleanToDecimalConversion(node As BoundConversion, underlyingTypeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeTo.IsDecimalType() AndAlso (underlyingTypeFrom.IsBooleanType() OrElse underlyingTypeFrom.IsIntegralType() OrElse underlyingTypeFrom.IsFloatingType)) Dim result As BoundExpression = node Dim memberSymbol As MethodSymbol If underlyingTypeFrom.IsBooleanType() Then Const memberId As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then memberSymbol = Nothing End If Else Dim member As SpecialMember Select Case underlyingTypeFrom.SpecialType Case SpecialType.System_SByte, SpecialType.System_Byte, SpecialType.System_Int16, SpecialType.System_UInt16, SpecialType.System_Int32 : member = SpecialMember.System_Decimal__CtorInt32 Case SpecialType.System_UInt32 : member = SpecialMember.System_Decimal__CtorUInt32 Case SpecialType.System_Int64 : member = SpecialMember.System_Decimal__CtorInt64 Case SpecialType.System_UInt64 : member = SpecialMember.System_Decimal__CtorUInt64 Case SpecialType.System_Single : member = SpecialMember.System_Decimal__CtorSingle Case SpecialType.System_Double : member = SpecialMember.System_Decimal__CtorDouble Case Else 'cannot get here Return result End Select memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(member), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then memberSymbol = Nothing End If End If ' Call the method. If memberSymbol IsNot Nothing Then Dim operand = node.Operand Dim operandType = operand.Type If operandType IsNot memberSymbol.Parameters(0).Type Then Dim conv As ConversionKind If operandType.IsEnumType() Then conv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions Else conv = ConversionKind.WideningNumeric End If Debug.Assert(conv = Conversions.ClassifyConversion(operandType, memberSymbol.Parameters(0).Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) operand = New BoundConversion(node.Syntax, operand, conv, node.Checked, node.ExplicitCastInCode, memberSymbol.Parameters(0).Type, Nothing) End If If memberSymbol.MethodKind = MethodKind.Constructor Then Debug.Assert(memberSymbol.ContainingType Is typeTo) result = New BoundObjectCreationExpression( node.Syntax, memberSymbol, ImmutableArray.Create(operand), Nothing, typeTo) Else Debug.Assert(memberSymbol.ReturnType Is typeTo) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteDecimalToNumericOrBooleanConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsDecimalType() AndAlso (underlyingTypeTo.IsBooleanType() OrElse underlyingTypeTo.IsIntegralType() OrElse underlyingTypeTo.IsFloatingType)) Dim result As BoundExpression = node Dim member As WellKnownMember Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.System_Convert__ToBooleanDecimal Case SpecialType.System_SByte : member = WellKnownMember.System_Convert__ToSByteDecimal Case SpecialType.System_Byte : member = WellKnownMember.System_Convert__ToByteDecimal Case SpecialType.System_Int16 : member = WellKnownMember.System_Convert__ToInt16Decimal Case SpecialType.System_UInt16 : member = WellKnownMember.System_Convert__ToUInt16Decimal Case SpecialType.System_Int32 : member = WellKnownMember.System_Convert__ToInt32Decimal Case SpecialType.System_UInt32 : member = WellKnownMember.System_Convert__ToUInt32Decimal Case SpecialType.System_Int64 : member = WellKnownMember.System_Convert__ToInt64Decimal Case SpecialType.System_UInt64 : member = WellKnownMember.System_Convert__ToUInt64Decimal Case SpecialType.System_Single : member = WellKnownMember.System_Convert__ToSingleDecimal Case SpecialType.System_Double : member = WellKnownMember.System_Convert__ToDoubleDecimal Case Else 'cannot get here Return result End Select Dim memberSymbol As MethodSymbol ' Call the method. memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.ReturnType Is underlyingTypeTo) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If targetResultType IsNot memberSymbol.ReturnType Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If Return result End Function Private Function RewriteFloatingToIntegralConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsFloatingType() AndAlso underlyingTypeTo.IsIntegralType()) Debug.Assert(Not _inExpressionLambda) Dim result As BoundExpression = node Dim operand = node.Operand If operand.Kind = BoundKind.Call Then Dim callOperand = DirectCast(operand, BoundCall) If IsFloatingTruncation(callOperand) Then ' CInt(Fix(number)) and the like can be simplified to just truncate the number to the integral type Return New BoundConversion(node.Syntax, callOperand.Arguments(0), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.Type) ElseIf ReturnsWholeNumberDouble(callOperand) Then ' CInt(Math.Floor(number)) and the like can omit rounding the result of Floor, which is already a whole number Return node End If End If ' Call Math.Round method to enforce VB style rounding. Const memberId As WellKnownMember = WellKnownMember.System_Math__RoundDouble Dim mathRound As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, mathRound) Then ' If we got here and passed badness check, it should be safe to assume that we have ' a "good" symbol for Double type If typeFrom IsNot mathRound.Parameters(0).Type Then ' Converting from Single Debug.Assert(ConversionKind.WideningNumeric = Conversions.ClassifyConversion(typeFrom, mathRound.Parameters(0).Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) operand = New BoundConversion(node.Syntax, operand, ConversionKind.WideningNumeric, node.Checked, node.ExplicitCastInCode, mathRound.Parameters(0).Type, Nothing) End If Dim callMathRound = New BoundCall(node.Syntax, mathRound, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, mathRound.ReturnType) Debug.Assert(node.ConversionKind = Conversions.ClassifyConversion(mathRound.ReturnType, node.Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, callMathRound, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.Type, Nothing) End If Return result End Function ''' <summary> ''' Is this a floating-point operation that results in a whole number, rendering a following rounding operation redundant? ''' </summary> Private Function ReturnsWholeNumberDouble(node As BoundCall) As Boolean Dim methodName As String = node.Method.Name If "Ceiling".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__CeilingDouble) ElseIf "Floor".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__FloorDouble) ElseIf "Round".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__RoundDouble) ElseIf "Int".Equals(methodName) Then Select Case node.Type.SpecialType Case SpecialType.System_Single Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__IntSingle) Case SpecialType.System_Double Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__IntDouble) Case Else Return False End Select End If Return False End Function ''' <summary> ''' Is this a floating-point truncation operation that would be redundant if followed by a truncation to an integral type? ''' </summary> Private Function IsFloatingTruncation(node As BoundCall) As Boolean Dim methodName As String = node.Method.Name If "Fix".Equals(methodName) Then Select Case node.Type.SpecialType Case SpecialType.System_Single Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__FixSingle) Case SpecialType.System_Double Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__FixDouble) Case Else Return False End Select ElseIf "Truncate".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__TruncateDouble) End If Return False End Function #End Region #Region "DirectCast" Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return VisitExpressionNode(node.Operand) End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt Is Nothing Then returnValue = MyBase.VisitDirectCast(node) Else returnValue = RewriteLambdaRelaxationConversion(node) End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function #End Region #Region "TryCast" Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return Visit(node.Operand) End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt Is Nothing Then returnValue = Nothing If Conversions.IsWideningConversion(node.ConversionKind) AndAlso Not Conversions.IsIdentityConversion(node.ConversionKind) Then Dim operand As BoundExpression = node.Operand If operand.Kind <> BoundKind.Lambda Then Dim typeFrom As TypeSymbol = operand.Type Dim typeTo As TypeSymbol = node.Type If (Not typeTo.IsTypeParameter()) AndAlso typeTo.IsReferenceType AndAlso (Not typeFrom.IsTypeParameter()) AndAlso typeFrom.IsReferenceType Then Debug.Assert(node.ConversionKind = Conversions.ClassifyDirectCastConversion(operand.Type, node.Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) returnValue = New BoundDirectCast(node.Syntax, DirectCast(Visit(operand), BoundExpression), node.ConversionKind, typeTo, Nothing) End If End If End If If returnValue Is Nothing Then returnValue = MyBase.VisitTryCast(node) End If Else returnValue = RewriteLambdaRelaxationConversion(node) End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend NotInheritable Class LocalRewriter Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Dim result = DirectCast(Visit(node.Operand), BoundExpression) If node.ExplicitCastInCode AndAlso IsFloatingPointExpressionOfUnknownPrecision(result) Then ' To force a value of a floating point type to the exact precision of its type, an explicit cast can be used. ' It means that explicit casts to CDbl() or CSng() should be preserved on the node. ' If original conversion has become something else with unknown precision, add an explicit identity cast. result = node.Update( result, ConversionKind.Identity, checked:=False, explicitCastInCode:=True, constantValueOpt:=node.ConstantValueOpt, extendedInfoOpt:=node.ExtendedInfoOpt, type:=node.Type) End If Return result End If If node.Operand.Kind = BoundKind.UserDefinedConversion Then If _inExpressionLambda Then Return node.Update(DirectCast(Visit(node.Operand), BoundExpression), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, node.Type) End If If (node.ConversionKind And ConversionKind.Nullable) <> 0 Then Return RewriteNullableUserDefinedConversion(DirectCast(node.Operand, BoundUserDefinedConversion)) End If Return Visit(DirectCast(node.Operand, BoundUserDefinedConversion).UnderlyingExpression) End If ' not all nullable conversions have Nullable flag ' For example Nothing --> Boolean? has conversionkind = WideningNothingLiteral If (node.Type IsNot Nothing AndAlso node.Type.IsNullableType OrElse node.Operand.Type IsNot Nothing AndAlso node.Operand.Type.IsNullableType) AndAlso Not _inExpressionLambda Then Return RewriteNullableConversion(node) End If ' Rewrite Anonymous Delegate conversion into a delegate creation If (node.ConversionKind And ConversionKind.AnonymousDelegate) <> 0 Then Return RewriteAnonymousDelegateConversion(node) End If ' Handle other conversions. Debug.Assert(TryCast(node.ExtendedInfoOpt, BoundRelaxationLambda)?.ReceiverPlaceholderOpt Is Nothing) ' Optimization for object comparisons that are operands of a conversion to boolean. ' Must be done before the object comparison is visited. If Not node.HasErrors AndAlso node.Type.IsBooleanType() AndAlso node.Operand.Type.IsObjectType() Then Dim operand As BoundNode = node.Operand ' Skip parens. While operand.Kind = BoundKind.Parenthesized operand = DirectCast(operand, BoundParenthesized).Expression End While If operand.Kind = BoundKind.BinaryOperator Then Dim binary = DirectCast(operand, BoundBinaryOperator) Select Case binary.OperatorKind And BinaryOperatorKind.OpMask Case BinaryOperatorKind.Equals, BinaryOperatorKind.NotEquals, BinaryOperatorKind.LessThan, BinaryOperatorKind.LessThanOrEqual, BinaryOperatorKind.GreaterThan, BinaryOperatorKind.GreaterThanOrEqual ' Attempt to optimize the coercion. ' The result of the comparison is known to be boolean, so force it to be. ' Rewrite of the operator will do the right thing. Debug.Assert(binary.Type.IsObjectType()) Return Visit(binary.Update(binary.OperatorKind, binary.Left, binary.Right, binary.Checked, binary.ConstantValueOpt, node.Type)) End Select End If End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.ExtendedInfoOpt IsNot Nothing AndAlso node.ExtendedInfoOpt.Kind = BoundKind.RelaxationLambda Then returnValue = RewriteLambdaRelaxationConversion(node) ElseIf (node.ConversionKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString Then returnValue = RewriteInterpolatedStringConversion(node) ElseIf (node.ConversionKind And (ConversionKind.Tuple Or ConversionKind.Nullable)) = ConversionKind.Tuple Then returnValue = RewriteTupleConversion(node) Else returnValue = MyBase.VisitConversion(node) If returnValue.Kind = BoundKind.Conversion Then returnValue = TransformRewrittenConversion(DirectCast(returnValue, BoundConversion)) End If End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function Private Shared Function IsFloatingPointExpressionOfUnknownPrecision(rewrittenNode As BoundExpression) As Boolean If rewrittenNode Is Nothing Then Return False End If ' Note: no special handling for node having a constant value because it cannot reach here Dim specialType = rewrittenNode.Type.SpecialType If specialType <> SpecialType.System_Double AndAlso specialType <> SpecialType.System_Single Then Return False End If Select Case rewrittenNode.Kind ' ECMA-335 I.12.1.3 Handling of floating-point data types. ' ... the value might be retained in the internal representation ' for future use, if it is reloaded from the storage location without having been modified ... ' ' Unfortunately, the above means that precision is not guaranteed even when loading from storage. ' ' Case BoundKind.FieldAccess ' Case BoundKind.ArrayAccess ' Return True Case BoundKind.Sequence Dim sequence = DirectCast(rewrittenNode, BoundSequence) Return IsFloatingPointExpressionOfUnknownPrecision(sequence.ValueOpt) Case BoundKind.Conversion ' lowered conversions have definite precision unless they are implicit identity casts Dim conversion = DirectCast(rewrittenNode, BoundConversion) Return conversion.ConversionKind = ConversionKind.Identity AndAlso Not conversion.ExplicitCastInCode End Select ' it is a float/double expression and we have no idea ... Return True End Function Private Function RewriteTupleConversion(node As BoundConversion) As BoundExpression Dim syntax = node.Syntax Dim rewrittenOperand = VisitExpression(node.Operand) Dim rewrittenType = DirectCast(VisitType(node.Type), NamedTypeSymbol) Return MakeTupleConversion(syntax, rewrittenOperand, rewrittenType, DirectCast(node.ExtendedInfoOpt, BoundConvertedTupleElements)) End Function Private Function MakeTupleConversion(syntax As SyntaxNode, rewrittenOperand As BoundExpression, destinationType As TypeSymbol, convertedElements As BoundConvertedTupleElements) As BoundExpression If destinationType.IsSameTypeIgnoringAll(rewrittenOperand.Type) Then 'binder keeps some tuple conversions just for the purpose of semantic model 'otherwise they are as good as identity conversions Return rewrittenOperand End If Dim destElementTypes = destinationType.GetElementTypesOfTupleOrCompatible() Dim numElements = destElementTypes.Length Dim srcType As TypeSymbol = rewrittenOperand.Type Dim tupleTypeSymbol As TupleTypeSymbol If srcType.IsTupleType Then tupleTypeSymbol = DirectCast(srcType, TupleTypeSymbol) Else ' The following codepath should be very uncommon (if reachable at all) ' we should generally not see tuple compatible types in bound trees and ' see actual tuple types instead. Debug.Assert(srcType.IsTupleCompatible()) ' PERF: if allocations here become nuisance, consider caching the TupleTypeSymbol ' in the type symbols that can actually be tuple compatible tupleTypeSymbol = TupleTypeSymbol.Create(DirectCast(srcType, NamedTypeSymbol)) End If Dim srcElementFields = tupleTypeSymbol.TupleElements Dim fieldAccessorsBuilder = ArrayBuilder(Of BoundExpression).GetInstance(numElements) Dim assignmentToTemp As BoundExpression = Nothing Dim tupleTemp As SynthesizedLocal = Nothing Dim savedTuple As BoundExpression = CaptureOperand(rewrittenOperand, tupleTemp, assignmentToTemp) Dim factory As New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, syntax, _compilationState, _diagnostics) For i As Integer = 0 To numElements - 1 Dim field = srcElementFields(i) Dim useSiteInfo As UseSiteInfo(Of AssemblySymbol) = field.CalculateUseSiteInfo() ReportUseSite(rewrittenOperand, useSiteInfo, _diagnostics) Dim fieldAccess = MakeTupleFieldAccess(syntax, field, savedTuple, constantValueOpt:=Nothing, isLValue:=False) ' lower the conversion AddPlaceholderReplacement(convertedElements.ElementPlaceholders(i), fieldAccess) fieldAccessorsBuilder.Add(VisitExpression(convertedElements.ConvertedElements(i))) RemovePlaceholderReplacement(convertedElements.ElementPlaceholders(i)) Next Dim result = MakeTupleCreationExpression(syntax, DirectCast(destinationType, NamedTypeSymbol), fieldAccessorsBuilder.ToImmutableAndFree()) Return factory.Sequence(tupleTemp, assignmentToTemp, result) End Function Private Function RewriteLambdaRelaxationConversion(node As BoundConversion) As BoundNode Dim returnValue As BoundNode Dim relaxationLambda As BoundLambda = DirectCast(node.ExtendedInfoOpt, BoundRelaxationLambda).Lambda If _inExpressionLambda AndAlso NoParameterRelaxation(node.Operand, relaxationLambda.LambdaSymbol) Then ' COMPAT: skip relaxation in this case. ET can drop the return value of the inner lambda. returnValue = MyBase.VisitConversion( node.Update(node.Operand, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, extendedInfoOpt:=Nothing, type:=node.Type)) returnValue = TransformRewrittenConversion(DirectCast(returnValue, BoundConversion)) Else returnValue = node.Update(VisitExpressionNode(relaxationLambda), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, extendedInfoOpt:=Nothing, type:=node.Type) End If Return returnValue End Function Private Function RewriteLambdaRelaxationConversion(node As BoundDirectCast) As BoundNode Dim returnValue As BoundNode If _inExpressionLambda AndAlso NoParameterRelaxation(node.Operand, node.RelaxationLambdaOpt.LambdaSymbol) Then ' COMPAT: skip relaxation in this case. ET can drop the return value of the inner lambda. returnValue = MyBase.VisitDirectCast( node.Update(node.Operand, node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type)) Else returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.SuppressVirtualCalls, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type) End If Return returnValue End Function Private Function RewriteLambdaRelaxationConversion(node As BoundTryCast) As BoundNode Dim returnValue As BoundNode If _inExpressionLambda AndAlso NoParameterRelaxation(node.Operand, node.RelaxationLambdaOpt.LambdaSymbol) Then ' COMPAT: skip relaxation in this case. ET can drop the return value of the inner lambda. returnValue = MyBase.VisitTryCast( node.Update(node.Operand, node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type)) Else returnValue = node.Update(VisitExpressionNode(node.RelaxationLambdaOpt), node.ConversionKind, node.ConstantValueOpt, relaxationLambdaOpt:=Nothing, type:=node.Type) End If Return returnValue End Function Private Shared Function NoParameterRelaxation(from As BoundExpression, toLambda As LambdaSymbol) As Boolean Dim fromLambda As LambdaSymbol = TryCast(from, BoundLambda)?.LambdaSymbol ' are we are relaxing for the purpose of dropping return? Return fromLambda IsNot Nothing AndAlso Not fromLambda.IsSub AndAlso toLambda.IsSub AndAlso MethodSignatureComparer.HaveSameParameterTypes(fromLambda.Parameters, Nothing, toLambda.Parameters, Nothing, considerByRef:=True, considerCustomModifiers:=False, considerTupleNames:=False) End Function ' Rewrite Anonymous Delegate conversion into a delegate creation Private Function RewriteAnonymousDelegateConversion(node As BoundConversion) As BoundNode Debug.Assert(Not Conversions.IsIdentityConversion(node.ConversionKind)) Debug.Assert(node.Operand.Type.IsDelegateType() AndAlso DirectCast(node.Operand.Type, NamedTypeSymbol).IsAnonymousType AndAlso node.Type.IsDelegateType() AndAlso node.Type.SpecialType <> SpecialType.System_MulticastDelegate) Dim F As New SyntheticBoundNodeFactory(Me._topMethod, Me._currentMethodOrLambda, node.Syntax, Me._compilationState, Me._diagnostics) If (node.Operand.IsDefaultValueConstant) Then Return F.Null(node.Type) Else Dim lambdaOpt As BoundLambda Dim receiverPlaceholderOpt As BoundRValuePlaceholder If node.ExtendedInfoOpt IsNot Nothing Then Dim relaxationLambda = DirectCast(node.ExtendedInfoOpt, BoundRelaxationLambda) lambdaOpt = relaxationLambda.Lambda receiverPlaceholderOpt = relaxationLambda.ReceiverPlaceholderOpt Else lambdaOpt = Nothing receiverPlaceholderOpt = Nothing End If If (Not Me._inExpressionLambda AndAlso CouldPossiblyBeNothing(F, node.Operand)) Then Dim savedOriginalValue = F.SynthesizedLocal(node.Operand.Type) Dim checkIfNothing = F.ReferenceIsNothing(F.Local(savedOriginalValue, False)) Dim conversionIfNothing = F.Null(node.Type) Dim convertedValue = New BoundDelegateCreationExpression(node.Syntax, F.Local(savedOriginalValue, False), DirectCast(node.Operand.Type, NamedTypeSymbol).DelegateInvokeMethod, lambdaOpt, receiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=node.Type) Dim conditionalResult As BoundExpression = F.TernaryConditionalExpression(condition:=checkIfNothing, ifTrue:=conversionIfNothing, ifFalse:=convertedValue) Return F.Sequence(savedOriginalValue, F.AssignmentExpression(F.Local(savedOriginalValue, True), VisitExpression(node.Operand)), VisitExpression(conditionalResult)) Else Dim convertedValue = New BoundDelegateCreationExpression(node.Syntax, node.Operand, DirectCast(node.Operand.Type, NamedTypeSymbol).DelegateInvokeMethod, lambdaOpt, receiverPlaceholderOpt, methodGroupOpt:=Nothing, type:=node.Type) Return VisitExpression(convertedValue) End If End If End Function Private Function CouldPossiblyBeNothing(F As SyntheticBoundNodeFactory, node As BoundExpression) As Boolean Select Case node.Kind Case BoundKind.TernaryConditionalExpression Dim t = DirectCast(node, BoundTernaryConditionalExpression) Return CouldPossiblyBeNothing(F, t.WhenTrue) OrElse CouldPossiblyBeNothing(F, t.WhenFalse) Case BoundKind.Conversion Dim t = DirectCast(node, BoundConversion) Return CouldPossiblyBeNothing(F, t.Operand) Case BoundKind.Lambda Return False Case BoundKind.Call Dim t = DirectCast(node, BoundCall) Return Not (t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Delegate__CreateDelegate, True) OrElse t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Delegate__CreateDelegate4, True) OrElse t.Method = F.WellKnownMember(Of MethodSymbol)(WellKnownMember.System_Reflection_MethodInfo__CreateDelegate, True)) Case Else Return True End Select End Function Private Function RewriteNullableConversion(node As BoundConversion) As BoundExpression Debug.Assert(Not _inExpressionLambda) Dim rewrittenOperand = DirectCast(Me.Visit(node.Operand), BoundExpression) If Conversions.IsIdentityConversion(node.ConversionKind) Then Debug.Assert(rewrittenOperand.Type.IsSameTypeIgnoringAll(node.Type)) Return rewrittenOperand End If Return RewriteNullableConversion(node, rewrittenOperand) End Function Private Function RewriteNullableConversion(node As BoundConversion, rewrittenOperand As BoundExpression) As BoundExpression Dim resultType = node.Type Dim operandType = rewrittenOperand.Type Debug.Assert(resultType.IsNullableType OrElse (operandType IsNot Nothing AndAlso operandType.IsNullableType), "operand or operator must be nullable") ' Nothing --> T? ==> new T? If rewrittenOperand.ConstantValueOpt Is ConstantValue.Nothing Then Return NullableNull(rewrittenOperand.Syntax, resultType) End If ' Conversions between reference types and nullables do not need further rewriting. ' Lifting will be done as part of box/unbox operation. If operandType.IsReferenceType OrElse resultType.IsReferenceType Then If resultType.IsStringType Then ' conversion to string is an intrinsic conversion and can be lifted. ' T? --> string ==> T.Value -- string ' note that nullable null does not convert to string, i.e. this conversion ' is not null-propagating rewrittenOperand = NullableValue(rewrittenOperand) ElseIf operandType.IsStringType Then ' CType(string, T?) ---> new T?(CType(string, T)) Dim innerTargetType = resultType.GetNullableUnderlyingType Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyConversion(rewrittenOperand.Type, innerTargetType, useSiteInfo).Key Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return WrapInNullable( TransformRewrittenConversion( node.Update(rewrittenOperand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType.GetNullableUnderlyingType)), resultType) ElseIf operandType.IsNullableType Then If HasNoValue(rewrittenOperand) Then ' DirectCast(Nothing, operatorType) Return New BoundDirectCast(node.Syntax, MakeNullLiteral(rewrittenOperand.Syntax, resultType), ConversionKind.WideningNothingLiteral, resultType) End If If HasValue(rewrittenOperand) Then ' DirectCast(operand.GetValueOrDefault, operatorType) Dim unwrappedOperand = NullableValueOrDefault(rewrittenOperand) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(unwrappedOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return New BoundDirectCast(node.Syntax, unwrappedOperand, convKind, resultType) End If End If Return TransformRewrittenConversion( node.Update(rewrittenOperand, node.ConversionKind And (Not ConversionKind.Nullable), node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType)) End If Debug.Assert(Not resultType.IsSameTypeIgnoringAll(operandType), "converting to same type") Dim result As BoundExpression = rewrittenOperand ' unwrap operand if needed and propagate HasValue if needed. ' If need to propagate HasValue, may also need to hoist the operand value into a temp Dim operandHasValue As BoundExpression = Nothing Dim temps As ArrayBuilder(Of LocalSymbol) = Nothing Dim inits As ArrayBuilder(Of BoundExpression) = Nothing If operandType.IsNullableType Then If resultType.IsNullableType Then If HasValue(rewrittenOperand) Then ' just get the value result = NullableValueOrDefault(rewrittenOperand) ElseIf HasNoValue(rewrittenOperand) Then ' converting null Return NullableNull(result.Syntax, resultType) Else Dim whenNotNull As BoundExpression = Nothing Dim whenNull As BoundExpression = Nothing If IsConditionalAccess(rewrittenOperand, whenNotNull, whenNull) Then If HasValue(whenNotNull) AndAlso HasNoValue(whenNull) Then Return UpdateConditionalAccess(rewrittenOperand, FinishRewriteNullableConversion(node, resultType, NullableValueOrDefault(whenNotNull), Nothing, Nothing, Nothing), NullableNull(result.Syntax, resultType)) End If End If ' uncaptured locals are safe here because we are dealing with a single operand result = ProcessNullableOperand(rewrittenOperand, operandHasValue, temps, inits, doNotCaptureLocals:=True) End If Else ' no propagation. result = NullableValue(rewrittenOperand) End If End If Return FinishRewriteNullableConversion(node, resultType, result, operandHasValue, temps, inits) End Function Private Function GetNewCompoundUseSiteInfo() As CompoundUseSiteInfo(Of AssemblySymbol) Return New CompoundUseSiteInfo(Of AssemblySymbol)(_diagnostics, Me.Compilation.Assembly) End Function Private Function FinishRewriteNullableConversion( node As BoundConversion, resultType As TypeSymbol, operand As BoundExpression, operandHasValue As BoundExpression, temps As ArrayBuilder(Of LocalSymbol), inits As ArrayBuilder(Of BoundExpression) ) As BoundExpression Debug.Assert(resultType Is node.Type) Dim unwrappedResultType = resultType.GetNullableUnderlyingTypeOrSelf ' apply unlifted conversion If Not operand.Type.IsSameTypeIgnoringAll(unwrappedResultType) Then Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyConversion(operand.Type, unwrappedResultType, useSiteInfo).Key Debug.Assert(Conversions.ConversionExists(convKind)) Debug.Assert((convKind And ConversionKind.Tuple) = (node.ConversionKind And ConversionKind.Tuple)) ' Check for potential constant folding Dim integerOverflow As Boolean = False Dim constantResult = Conversions.TryFoldConstantConversion(operand, unwrappedResultType, integerOverflow) Debug.Assert(constantResult Is Nothing OrElse Not constantResult.IsBad) If constantResult IsNot Nothing AndAlso Not constantResult.IsBad Then ' Overflow should have been detected at classification time during binding. Debug.Assert(Not integerOverflow OrElse Not node.Checked) operand = RewriteConstant(New BoundLiteral(node.Syntax, constantResult, unwrappedResultType), constantResult) Else _diagnostics.Add(node, useSiteInfo) If (convKind And ConversionKind.Tuple) <> 0 Then operand = MakeTupleConversion(node.Syntax, operand, unwrappedResultType, DirectCast(node.ExtendedInfoOpt, BoundConvertedTupleElements)) Else operand = TransformRewrittenConversion(New BoundConversion(node.Syntax, operand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, unwrappedResultType)) End If End If End If ' wrap if needed If resultType.IsNullableType Then operand = WrapInNullable(operand, resultType) ' propagate null from the operand If operandHasValue IsNot Nothing Then operand = MakeTernaryConditionalExpression(node.Syntax, operandHasValue, operand, NullableNull(operand.Syntax, resultType)) ' if used temps, arrange a sequence for temps and inits. If temps IsNot Nothing Then operand = New BoundSequence(operand.Syntax, temps.ToImmutableAndFree, inits.ToImmutableAndFree, operand, operand.Type) End If End If End If Return operand End Function Private Function RewriteNullableReferenceConversion(node As BoundConversion, rewrittenOperand As BoundExpression) As BoundExpression Dim resultType = node.Type Dim operandType = rewrittenOperand.Type If operandType.IsStringType Then ' CType(string, T?) ---> new T?(CType(string, T)) Dim innerTargetType = resultType.GetNullableUnderlyingType Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyConversion(operandType, innerTargetType, useSiteInfo).Key Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return WrapInNullable( TransformRewrittenConversion( node.Update(rewrittenOperand, convKind, node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType.GetNullableUnderlyingType)), resultType) End If If resultType.IsStringType Then ' conversion to string is an intrinsic conversion and can be lifted. ' T? --> string ==> T.Value -- string ' note that nullable null does not convert to string null, i.e. this conversion ' is not null-propagating rewrittenOperand = NullableValue(rewrittenOperand) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return TransformRewrittenConversion( node.Update(rewrittenOperand, node.ConversionKind And (Not ConversionKind.Nullable), node.Checked, node.ExplicitCastInCode, node.ConstantValueOpt, node.ExtendedInfoOpt, resultType)) End If If operandType.IsNullableType Then ' T? --> RefType, this is a boxing conversion (DirectCast) If HasNoValue(rewrittenOperand) Then ' DirectCast(Nothing, operatorType) Return New BoundDirectCast(node.Syntax, MakeNullLiteral(rewrittenOperand.Syntax, resultType), ConversionKind.WideningNothingLiteral, resultType) End If If HasValue(rewrittenOperand) Then ' DirectCast(operand.GetValueOrDefault, operatorType) Dim unwrappedOperand = NullableValueOrDefault(rewrittenOperand) Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(unwrappedOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return New BoundDirectCast(node.Syntax, unwrappedOperand, convKind, resultType) End If End If If resultType.IsNullableType Then ' RefType --> T? , this is just an unboxing conversion. Dim useSiteInfo = GetNewCompoundUseSiteInfo() Dim convKind = Conversions.ClassifyDirectCastConversion(rewrittenOperand.Type, resultType, useSiteInfo) Debug.Assert(Conversions.ConversionExists(convKind)) _diagnostics.Add(node, useSiteInfo) Return New BoundDirectCast(node.Syntax, rewrittenOperand, convKind, resultType) End If Throw ExceptionUtilities.Unreachable End Function Private Function RewriteNullableUserDefinedConversion(node As BoundUserDefinedConversion) As BoundNode ' User defined conversions rewrite as: ' Sequence(operandCapture, If(operandCapture.HasValue, Conversion(operandCapture), Null) ' ' The structure of the nullable BoundUserDefinedConversion looks like this: ' [OPERAND] -> [IN-CONVERSION] -> [CALL] -> [OUT-CONVERSION] ' ' In-conversion also does unwrapping. ' Out-conversion also does wrapping. ' ' operand ' the thing that we will be converting. Must be nullable. We will be checking HasValue on it and will return null if it does not. Dim operand = node.Operand Debug.Assert(operand.Type.IsNullableType) ' inner conversion Dim inConversion = node.InConversionOpt Debug.Assert(inConversion IsNot Nothing, "There is always an inner conversion.") ' operator Dim operatorCall As BoundCall = node.Call ' outer conversion Dim outConversion As BoundConversion = node.OutConversionOpt Debug.Assert(outConversion IsNot Nothing, "There is always an outer conversion.") ' result type ' type that we need to return from the conversion. It must be a nullable type. Dim resultType As TypeSymbol = outConversion.Type Debug.Assert(resultType.IsNullableType, "lifted operator must have nullable type") ' === START REWRITE Dim rewrittenOperand = Me.VisitExpressionNode(operand) ' this is what we return when operand has no value Dim whenHasNoValue As BoundExpression = NullableNull(node.Syntax, resultType) '== TRIVIAL CASE If HasNoValue(rewrittenOperand) Then Return whenHasNoValue End If ' Do we know statically that operand has value? Dim operandHasValue As Boolean = HasValue(rewrittenOperand) ' This is what we will pass to the operator method if operand has value Dim inputToOperatorMethod As BoundExpression Dim condition As BoundExpression = Nothing Dim temp As SynthesizedLocal = Nothing If operandHasValue Then ' just pass the operand, no need to capture inputToOperatorMethod = rewrittenOperand Else ' operator input would be captured operand Dim tempInit As BoundExpression = Nothing ' no need to capture locals since we will not ' evaluate anything between HasValue and ValueOrDefault Dim capturedleft As BoundExpression = CaptureNullableIfNeeded(rewrittenOperand, temp, tempInit, doNotCaptureLocals:=True) condition = NullableHasValue(If(tempInit, capturedleft)) ' Note that we will be doing the conversion only when ' we know that we have a value, so we will pass to the conversion wrapped NullableValueOrDefault. ' so that it could use NullableValueOrDefault instead of Value. inputToOperatorMethod = WrapInNullable(NullableValueOrDefault(capturedleft), capturedleft.Type) End If ' inConversion is always a nullable conversion. We need to rewrite it. inputToOperatorMethod = RewriteNullableConversion(inConversion, inputToOperatorMethod) ' result of the conversion when operand has value. (replace the arg) Dim whenHasValue As BoundExpression = operatorCall.Update(operatorCall.Method, Nothing, operatorCall.ReceiverOpt, ImmutableArray.Create(inputToOperatorMethod), Nothing, operatorCall.ConstantValueOpt, isLValue:=operatorCall.IsLValue, suppressObjectClone:=operatorCall.SuppressObjectClone, type:=operatorCall.Type) ' outConversion is a nullable conversion. need to rewrite it. whenHasValue = RewriteNullableConversion(outConversion, whenHasValue) ' Now we have whenHasValue, whenHasNoValue and condition. The rest is easy. If operandHasValue Then Return whenHasValue Else ' == rewrite operand as ternary expression Dim result As BoundExpression = MakeTernaryConditionalExpression(node.Syntax, condition, whenHasValue, whenHasNoValue) ' if we used a temp, arrange a sequence for it If temp IsNot Nothing Then result = New BoundSequence(node.Syntax, ImmutableArray.Create(Of LocalSymbol)(temp), ImmutableArray(Of BoundExpression).Empty, result, result.Type) End If Return result End If End Function #Region "Post-rewrite conversion" Private Function TransformRewrittenConversion(rewrittenConversion As BoundConversion) As BoundExpression If rewrittenConversion.HasErrors OrElse _inExpressionLambda Then Return rewrittenConversion End If Dim result As BoundExpression = rewrittenConversion Dim underlyingTypeTo = rewrittenConversion.Type.GetEnumUnderlyingTypeOrSelf() Dim operand = rewrittenConversion.Operand If operand.IsNothingLiteral() Then Debug.Assert(rewrittenConversion.ConversionKind = ConversionKind.WideningNothingLiteral OrElse (Conversions.IsIdentityConversion(rewrittenConversion.ConversionKind) AndAlso Not underlyingTypeTo.IsTypeParameter() AndAlso underlyingTypeTo.IsReferenceType) OrElse (rewrittenConversion.ConversionKind And (ConversionKind.Reference Or ConversionKind.Array)) <> 0) If underlyingTypeTo.IsTypeParameter() OrElse underlyingTypeTo.IsReferenceType Then result = RewriteAsDirectCast(rewrittenConversion) Else Debug.Assert(underlyingTypeTo.IsValueType) End If ElseIf operand.Kind = BoundKind.Lambda Then Return rewrittenConversion Else Dim underlyingTypeFrom = operand.Type.GetEnumUnderlyingTypeOrSelf() If underlyingTypeFrom.IsFloatingType() AndAlso underlyingTypeTo.IsIntegralType() Then result = RewriteFloatingToIntegralConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsDecimalType() AndAlso (underlyingTypeTo.IsBooleanType() OrElse underlyingTypeTo.IsIntegralType() OrElse underlyingTypeTo.IsFloatingType) Then result = RewriteDecimalToNumericOrBooleanConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsDecimalType() AndAlso (underlyingTypeFrom.IsBooleanType() OrElse underlyingTypeFrom.IsIntegralType() OrElse underlyingTypeFrom.IsFloatingType) Then result = RewriteNumericOrBooleanToDecimalConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsNullableType OrElse underlyingTypeTo.IsNullableType Then ' conversions between nullable and reference types are not directcasts, they are boxing/unboxing conversions. ' CodeGen will handle this. ElseIf underlyingTypeFrom.IsObjectType() AndAlso (underlyingTypeTo.IsTypeParameter() OrElse underlyingTypeTo.IsIntrinsicType()) Then result = RewriteFromObjectConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsTypeParameter() Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeTo.IsTypeParameter() Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeFrom.IsStringType() AndAlso (underlyingTypeTo.IsCharSZArray() OrElse underlyingTypeTo.IsIntrinsicValueType()) Then result = RewriteFromStringConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsStringType() AndAlso (underlyingTypeFrom.IsCharSZArray() OrElse underlyingTypeFrom.IsIntrinsicValueType()) Then result = RewriteToStringConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeFrom.IsReferenceType AndAlso underlyingTypeTo.IsCharSZArray() Then result = RewriteReferenceTypeToCharArrayRankOneConversion(rewrittenConversion, underlyingTypeFrom, underlyingTypeTo) ElseIf underlyingTypeTo.IsReferenceType Then result = RewriteAsDirectCast(rewrittenConversion) ElseIf underlyingTypeFrom.IsReferenceType AndAlso underlyingTypeTo.IsIntrinsicValueType() Then result = RewriteFromObjectConversion(rewrittenConversion, Compilation.GetSpecialType(SpecialType.System_Object), underlyingTypeTo) Else Debug.Assert(underlyingTypeTo.IsValueType) End If End If Return result End Function Private Function RewriteReferenceTypeToCharArrayRankOneConversion(node As BoundConversion, typeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsReferenceType AndAlso typeTo.IsCharSZArray()) Dim result As BoundExpression = node Const member As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneObject Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.Parameters(0).Type.IsObjectType()) If Not operand.Type.IsObjectType() Then Dim objectType As TypeSymbol = memberSymbol.Parameters(0).Type Dim useSiteInfo = GetNewCompoundUseSiteInfo() operand = New BoundDirectCast(operand.Syntax, operand, Conversions.ClassifyDirectCastConversion(operand.Type, objectType, useSiteInfo), objectType) _diagnostics.Add(node, useSiteInfo) End If result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringAll(node.Type)) End If Return result End Function Private Shared Function RewriteAsDirectCast(node As BoundConversion) As BoundExpression Debug.Assert(node.Operand.IsNothingLiteral() OrElse (node.ConversionKind And (Not ConversionKind.DelegateRelaxationLevelMask)) = Conversions.ClassifyDirectCastConversion(node.Operand.Type, node.Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) ' TODO: A chain of widening reference conversions that starts from NOTHING literal can be collapsed to a single node. ' Semantics::Convert does this in Dev10. ' It looks like we already achieve the same result due to folding of NOTHING conversions. Return New BoundDirectCast(node.Syntax, node.Operand, node.ConversionKind, node.Type, Nothing) End Function Private Function RewriteFromObjectConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsObjectType()) Dim result As BoundExpression = node Dim member As WellKnownMember = WellKnownMember.Count Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanObject Case SpecialType.System_SByte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteObject Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToByteObject Case SpecialType.System_Int16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToShortObject Case SpecialType.System_UInt16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortObject Case SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerObject Case SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerObject Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToLongObject Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToULongObject Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleObject Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleObject Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalObject Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDateObject Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharObject Case SpecialType.System_String : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringObject Case Else If underlyingTypeTo.IsTypeParameter() Then member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object End If End Select If member <> WellKnownMember.Count Then Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then If member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToGenericParameter_T_Object Then memberSymbol = memberSymbol.Construct(underlyingTypeTo) End If Dim operand = node.Operand If Not operand.Type.IsObjectType() Then Debug.Assert(typeFrom.IsObjectType()) Debug.Assert(operand.Type.IsReferenceType) Debug.Assert(underlyingTypeTo.IsIntrinsicValueType()) Dim useSiteInfo = GetNewCompoundUseSiteInfo() operand = New BoundDirectCast(operand.Syntax, operand, Conversions.ClassifyDirectCastConversion(operand.Type, typeFrom, useSiteInfo), typeFrom) _diagnostics.Add(node, useSiteInfo) End If Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringAll(underlyingTypeTo)) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If Not targetResultType.IsSameTypeIgnoringAll(memberSymbol.ReturnType) Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If End If Return result End Function Private Function RewriteToStringConversion(node As BoundConversion, underlyingTypeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeTo.IsStringType()) Dim result As BoundExpression = node Dim memberSymbol As MethodSymbol = Nothing If underlyingTypeFrom.IsCharSZArray() Then Const memberId As SpecialMember = SpecialMember.System_String__CtorSZArrayChar memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(memberId), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then memberSymbol = Nothing End If Else Dim member As WellKnownMember = WellKnownMember.Count ' Note, conversion from Object is handled by RewriteFromObjectConversion. Select Case underlyingTypeFrom.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringBoolean Case SpecialType.System_SByte, SpecialType.System_Int16, SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt32 Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringByte Case SpecialType.System_UInt16, SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt32 Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringInt64 Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringUInt64 Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringSingle Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDouble Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDecimal Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringDateTime Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToStringChar End Select If member <> WellKnownMember.Count Then memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then memberSymbol = Nothing End If End If End If If memberSymbol IsNot Nothing Then Dim operand = node.Operand Dim operandType = operand.Type If Not operandType.IsSameTypeIgnoringAll(memberSymbol.Parameters(0).Type) Then Dim conv As ConversionKind If operandType.IsEnumType() Then conv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions Else conv = ConversionKind.WideningNumeric End If Debug.Assert(conv = Conversions.ClassifyConversion(operandType, memberSymbol.Parameters(0).Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) operand = New BoundConversion(node.Syntax, operand, conv, node.Checked, node.ExplicitCastInCode, memberSymbol.Parameters(0).Type, Nothing) End If If memberSymbol.MethodKind = MethodKind.Constructor Then Debug.Assert(memberSymbol.ContainingType Is typeTo) result = New BoundObjectCreationExpression( node.Syntax, memberSymbol, ImmutableArray.Create(operand), Nothing, typeTo) Else Debug.Assert(memberSymbol.ReturnType Is typeTo) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteFromStringConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsStringType()) Dim result As BoundExpression = node Dim member As WellKnownMember = WellKnownMember.Count Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToBooleanString Case SpecialType.System_SByte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSByteString Case SpecialType.System_Byte : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToByteString Case SpecialType.System_Int16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToShortString Case SpecialType.System_UInt16 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUShortString Case SpecialType.System_Int32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToIntegerString Case SpecialType.System_UInt32 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToUIntegerString Case SpecialType.System_Int64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToLongString Case SpecialType.System_UInt64 : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToULongString Case SpecialType.System_Single : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToSingleString Case SpecialType.System_Double : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDoubleString Case SpecialType.System_Decimal : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalString Case SpecialType.System_DateTime : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDateString Case SpecialType.System_Char : member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharString Case Else If underlyingTypeTo.IsCharSZArray() Then member = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToCharArrayRankOneString End If End Select If member <> WellKnownMember.Count Then Dim memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.ReturnType.IsSameTypeIgnoringAll(underlyingTypeTo)) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If Not targetResultType.IsSameTypeIgnoringAll(memberSymbol.ReturnType) Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If End If Return result End Function Private Function RewriteNumericOrBooleanToDecimalConversion(node As BoundConversion, underlyingTypeFrom As TypeSymbol, typeTo As TypeSymbol) As BoundExpression Debug.Assert(typeTo.IsDecimalType() AndAlso (underlyingTypeFrom.IsBooleanType() OrElse underlyingTypeFrom.IsIntegralType() OrElse underlyingTypeFrom.IsFloatingType)) Dim result As BoundExpression = node Dim memberSymbol As MethodSymbol If underlyingTypeFrom.IsBooleanType() Then Const memberId As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_Conversions__ToDecimalBoolean memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, memberId, memberSymbol) Then memberSymbol = Nothing End If Else Dim member As SpecialMember Select Case underlyingTypeFrom.SpecialType Case SpecialType.System_SByte, SpecialType.System_Byte, SpecialType.System_Int16, SpecialType.System_UInt16, SpecialType.System_Int32 : member = SpecialMember.System_Decimal__CtorInt32 Case SpecialType.System_UInt32 : member = SpecialMember.System_Decimal__CtorUInt32 Case SpecialType.System_Int64 : member = SpecialMember.System_Decimal__CtorInt64 Case SpecialType.System_UInt64 : member = SpecialMember.System_Decimal__CtorUInt64 Case SpecialType.System_Single : member = SpecialMember.System_Decimal__CtorSingle Case SpecialType.System_Double : member = SpecialMember.System_Decimal__CtorDouble Case Else 'cannot get here Return result End Select memberSymbol = DirectCast(ContainingAssembly.GetSpecialTypeMember(member), MethodSymbol) If ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then memberSymbol = Nothing End If End If ' Call the method. If memberSymbol IsNot Nothing Then Dim operand = node.Operand Dim operandType = operand.Type If operandType IsNot memberSymbol.Parameters(0).Type Then Dim conv As ConversionKind If operandType.IsEnumType() Then conv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions Else conv = ConversionKind.WideningNumeric End If Debug.Assert(conv = Conversions.ClassifyConversion(operandType, memberSymbol.Parameters(0).Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) operand = New BoundConversion(node.Syntax, operand, conv, node.Checked, node.ExplicitCastInCode, memberSymbol.Parameters(0).Type, Nothing) End If If memberSymbol.MethodKind = MethodKind.Constructor Then Debug.Assert(memberSymbol.ContainingType Is typeTo) result = New BoundObjectCreationExpression( node.Syntax, memberSymbol, ImmutableArray.Create(operand), Nothing, typeTo) Else Debug.Assert(memberSymbol.ReturnType Is typeTo) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) End If End If Return result End Function Private Function RewriteDecimalToNumericOrBooleanConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsDecimalType() AndAlso (underlyingTypeTo.IsBooleanType() OrElse underlyingTypeTo.IsIntegralType() OrElse underlyingTypeTo.IsFloatingType)) Dim result As BoundExpression = node Dim member As WellKnownMember Select Case underlyingTypeTo.SpecialType Case SpecialType.System_Boolean : member = WellKnownMember.System_Convert__ToBooleanDecimal Case SpecialType.System_SByte : member = WellKnownMember.System_Convert__ToSByteDecimal Case SpecialType.System_Byte : member = WellKnownMember.System_Convert__ToByteDecimal Case SpecialType.System_Int16 : member = WellKnownMember.System_Convert__ToInt16Decimal Case SpecialType.System_UInt16 : member = WellKnownMember.System_Convert__ToUInt16Decimal Case SpecialType.System_Int32 : member = WellKnownMember.System_Convert__ToInt32Decimal Case SpecialType.System_UInt32 : member = WellKnownMember.System_Convert__ToUInt32Decimal Case SpecialType.System_Int64 : member = WellKnownMember.System_Convert__ToInt64Decimal Case SpecialType.System_UInt64 : member = WellKnownMember.System_Convert__ToUInt64Decimal Case SpecialType.System_Single : member = WellKnownMember.System_Convert__ToSingleDecimal Case SpecialType.System_Double : member = WellKnownMember.System_Convert__ToDoubleDecimal Case Else 'cannot get here Return result End Select Dim memberSymbol As MethodSymbol ' Call the method. memberSymbol = DirectCast(Compilation.GetWellKnownTypeMember(member), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, member, memberSymbol) Then Dim operand = node.Operand Debug.Assert(memberSymbol.ReturnType Is underlyingTypeTo) Debug.Assert(memberSymbol.Parameters(0).Type Is typeFrom) result = New BoundCall(node.Syntax, memberSymbol, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, memberSymbol.ReturnType) Dim targetResultType = node.Type If targetResultType IsNot memberSymbol.ReturnType Then ' Must be conversion to an enum Debug.Assert(targetResultType.IsEnumType()) Dim conv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions Debug.Assert(conv = Conversions.ClassifyConversion(memberSymbol.ReturnType, targetResultType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, DirectCast(result, BoundExpression), conv, node.Checked, node.ExplicitCastInCode, targetResultType, Nothing) End If End If Return result End Function Private Function RewriteFloatingToIntegralConversion(node As BoundConversion, typeFrom As TypeSymbol, underlyingTypeTo As TypeSymbol) As BoundExpression Debug.Assert(typeFrom.IsFloatingType() AndAlso underlyingTypeTo.IsIntegralType()) Debug.Assert(Not _inExpressionLambda) Dim result As BoundExpression = node Dim operand = node.Operand If operand.Kind = BoundKind.Call Then Dim callOperand = DirectCast(operand, BoundCall) If IsFloatingTruncation(callOperand) Then ' CInt(Fix(number)) and the like can be simplified to just truncate the number to the integral type Return New BoundConversion(node.Syntax, callOperand.Arguments(0), node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.Type) ElseIf ReturnsWholeNumberDouble(callOperand) Then ' CInt(Math.Floor(number)) and the like can omit rounding the result of Floor, which is already a whole number Return node End If End If ' Call Math.Round method to enforce VB style rounding. Const memberId As WellKnownMember = WellKnownMember.System_Math__RoundDouble Dim mathRound As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember(memberId), MethodSymbol) If Not ReportMissingOrBadRuntimeHelper(node, memberId, mathRound) Then ' If we got here and passed badness check, it should be safe to assume that we have ' a "good" symbol for Double type If typeFrom IsNot mathRound.Parameters(0).Type Then ' Converting from Single Debug.Assert(ConversionKind.WideningNumeric = Conversions.ClassifyConversion(typeFrom, mathRound.Parameters(0).Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) operand = New BoundConversion(node.Syntax, operand, ConversionKind.WideningNumeric, node.Checked, node.ExplicitCastInCode, mathRound.Parameters(0).Type, Nothing) End If Dim callMathRound = New BoundCall(node.Syntax, mathRound, Nothing, Nothing, ImmutableArray.Create(operand), Nothing, mathRound.ReturnType) Debug.Assert(node.ConversionKind = Conversions.ClassifyConversion(mathRound.ReturnType, node.Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded).Key) result = New BoundConversion(node.Syntax, callMathRound, node.ConversionKind, node.Checked, node.ExplicitCastInCode, node.Type, Nothing) End If Return result End Function ''' <summary> ''' Is this a floating-point operation that results in a whole number, rendering a following rounding operation redundant? ''' </summary> Private Function ReturnsWholeNumberDouble(node As BoundCall) As Boolean Dim methodName As String = node.Method.Name If "Ceiling".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__CeilingDouble) ElseIf "Floor".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__FloorDouble) ElseIf "Round".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__RoundDouble) ElseIf "Int".Equals(methodName) Then Select Case node.Type.SpecialType Case SpecialType.System_Single Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__IntSingle) Case SpecialType.System_Double Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__IntDouble) Case Else Return False End Select End If Return False End Function ''' <summary> ''' Is this a floating-point truncation operation that would be redundant if followed by a truncation to an integral type? ''' </summary> Private Function IsFloatingTruncation(node As BoundCall) As Boolean Dim methodName As String = node.Method.Name If "Fix".Equals(methodName) Then Select Case node.Type.SpecialType Case SpecialType.System_Single Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__FixSingle) Case SpecialType.System_Double Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Conversion__FixDouble) Case Else Return False End Select ElseIf "Truncate".Equals(methodName) Then Return node.Method = Me.Compilation.GetWellKnownTypeMember(WellKnownMember.System_Math__TruncateDouble) End If Return False End Function #End Region #Region "DirectCast" Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return VisitExpressionNode(node.Operand) End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt Is Nothing Then returnValue = MyBase.VisitDirectCast(node) Else returnValue = RewriteLambdaRelaxationConversion(node) End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function #End Region #Region "TryCast" Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode If Not _inExpressionLambda AndAlso Conversions.IsIdentityConversion(node.ConversionKind) Then Return Visit(node.Operand) End If ' Set "inExpressionLambda" if we're converting lambda to expression tree. Dim returnValue As BoundNode Dim wasInExpressionlambda As Boolean = _inExpressionLambda If (node.ConversionKind And (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree)) = (ConversionKind.Lambda Or ConversionKind.ConvertedToExpressionTree) Then _inExpressionLambda = True End If If node.RelaxationLambdaOpt Is Nothing Then returnValue = Nothing If Conversions.IsWideningConversion(node.ConversionKind) AndAlso Not Conversions.IsIdentityConversion(node.ConversionKind) Then Dim operand As BoundExpression = node.Operand If operand.Kind <> BoundKind.Lambda Then Dim typeFrom As TypeSymbol = operand.Type Dim typeTo As TypeSymbol = node.Type If (Not typeTo.IsTypeParameter()) AndAlso typeTo.IsReferenceType AndAlso (Not typeFrom.IsTypeParameter()) AndAlso typeFrom.IsReferenceType Then Debug.Assert(node.ConversionKind = Conversions.ClassifyDirectCastConversion(operand.Type, node.Type, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) returnValue = New BoundDirectCast(node.Syntax, DirectCast(Visit(operand), BoundExpression), node.ConversionKind, typeTo, Nothing) End If End If End If If returnValue Is Nothing Then returnValue = MyBase.VisitTryCast(node) End If Else returnValue = RewriteLambdaRelaxationConversion(node) End If _inExpressionLambda = wasInExpressionlambda Return returnValue End Function #End Region End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Test/Syntax/Parsing/StatementParsingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StatementParsingTests : ParsingTests { public StatementParsingTests(ITestOutputHelper output) : base(output) { } private StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions options = null) { return SyntaxFactory.ParseStatement(text, offset, options); } [Fact] [WorkItem(17458, "https://github.com/dotnet/roslyn/issues/17458")] public void ParsePrivate() { UsingStatement("private", // (1,1): error CS1073: Unexpected token 'private' // private Diagnostic(ErrorCode.ERR_UnexpectedToken, "").WithArguments("private").WithLocation(1, 1), // (1,1): error CS1525: Invalid expression term 'private' // private Diagnostic(ErrorCode.ERR_InvalidExprTerm, "private").WithArguments("private").WithLocation(1, 1), // (1,1): error CS1002: ; expected // private Diagnostic(ErrorCode.ERR_SemicolonExpected, "private").WithLocation(1, 1) ); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TestName() { var text = "a();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.IdentifierName, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestDottedName() { var text = "a.b();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a.b()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestGenericName() { var text = "a<b>();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.GenericName, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a<b>()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestGenericDotName() { var text = "a<b>.c();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a<b>.c()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestDotGenericName() { var text = "a.b<c>();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a.b<c>()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } private void TestPostfixUnaryOperator(SyntaxKind kind, ParseOptions options = null) { var text = "a" + SyntaxFacts.GetText(kind) + ";"; var statement = this.ParseStatement(text, options: options); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); var opKind = SyntaxFacts.GetPostfixUnaryExpression(kind); Assert.Equal(opKind, es.Expression.Kind()); var us = (PostfixUnaryExpressionSyntax)es.Expression; Assert.Equal("a", us.Operand.ToString()); Assert.Equal(kind, us.OperatorToken.Kind()); } [Fact] public void TestPostfixUnaryOperators() { TestPostfixUnaryOperator(SyntaxKind.PlusPlusToken); TestPostfixUnaryOperator(SyntaxKind.MinusMinusToken); TestPostfixUnaryOperator(SyntaxKind.ExclamationToken, TestOptions.Regular8); } [Fact] public void TestLocalDeclarationStatement() { var text = "T a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithVar() { // note: semantically this would require an initializer, but we don't know // about var being special until we bind. var text = "var a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("var", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, ds.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)ds.Declaration.Type).Identifier.Kind()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithTuple() { var text = "(int, int) a;"; var statement = this.ParseStatement(text, options: TestOptions.Regular); (text).ToString(); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("(int, int)", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.TupleType, ds.Declaration.Type.Kind()); var tt = (TupleTypeSyntax)ds.Declaration.Type; Assert.Equal(SyntaxKind.PredefinedType, tt.Elements[0].Type.Kind()); Assert.Equal(SyntaxKind.None, tt.Elements[1].Identifier.Kind()); Assert.Equal(2, tt.Elements.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithNamedTuple() { var text = "(T x, (U k, V l, W m) y) a;"; var statement = this.ParseStatement(text); (text).ToString(); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("(T x, (U k, V l, W m) y)", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.TupleType, ds.Declaration.Type.Kind()); var tt = (TupleTypeSyntax)ds.Declaration.Type; Assert.Equal(SyntaxKind.IdentifierName, tt.Elements[0].Type.Kind()); Assert.Equal("y", tt.Elements[1].Identifier.ToString()); Assert.Equal(2, tt.Elements.Count); tt = (TupleTypeSyntax)tt.Elements[1].Type; Assert.Equal("(U k, V l, W m)", tt.ToString()); Assert.Equal(SyntaxKind.IdentifierName, tt.Elements[0].Type.Kind()); Assert.Equal("l", tt.Elements[1].Identifier.ToString()); Assert.Equal(3, tt.Elements.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithDynamic() { // note: semantically this would require an initializer, but we don't know // about dynamic being special until we bind. var text = "dynamic a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("dynamic", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, ds.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)ds.Declaration.Type).Identifier.Kind()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithGenericType() { var text = "T<a> b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T<a>", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("b", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithDottedType() { var text = "T.X.Y a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T.X.Y", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithMixedType() { var text = "T<t>.X<x>.Y<y> a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T<t>.X<x>.Y<y>", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithArrayType() { var text = "T[][,][,,] a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T[][,][,,]", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithPointerType() { var text = "T* a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T*", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithNullableType() { var text = "T? a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T?", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithMultipleVariables() { var text = "T a, b, c;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(3, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[1].Identifier); Assert.Equal("b", ds.Declaration.Variables[1].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[1].ArgumentList); Assert.Null(ds.Declaration.Variables[1].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[2].Identifier); Assert.Equal("c", ds.Declaration.Variables[2].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[2].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithInitializer() { var text = "T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithMultipleVariablesAndInitializers() { var text = "T a = va, b = vb, c = vc;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(3, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("va", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.Declaration.Variables[1].Identifier); Assert.Equal("b", ds.Declaration.Variables[1].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[1].ArgumentList); Assert.NotEqual(default, ds.Declaration.Variables[1].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[1].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[1].Initializer.Value); Assert.Equal("vb", ds.Declaration.Variables[1].Initializer.Value.ToString()); Assert.NotEqual(default, ds.Declaration.Variables[2].Identifier); Assert.Equal("c", ds.Declaration.Variables[2].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[2].ArgumentList); Assert.NotEqual(default, ds.Declaration.Variables[2].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[2].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[2].Initializer.Value); Assert.Equal("vc", ds.Declaration.Variables[2].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithArrayInitializer() { var text = "T a = {b, c};"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ArrayInitializerExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal("{b, c}", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestConstLocalDeclarationStatement() { var text = "const T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.ConstKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestStaticLocalDeclarationStatement() { var text = "static T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestReadOnlyLocalDeclarationStatement() { var text = "readonly T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestVolatileLocalDeclarationStatement() { var text = "volatile T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.VolatileKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestRefLocalDeclarationStatement() { var text = "ref T a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("ref T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestRefLocalDeclarationStatementWithInitializer() { var text = "ref T a = ref b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("ref T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); var initializer = ds.Declaration.Variables[0].Initializer as EqualsValueClauseSyntax; Assert.NotNull(initializer); Assert.NotEqual(default, initializer.EqualsToken); Assert.False(initializer.EqualsToken.IsMissing); Assert.Equal(SyntaxKind.RefExpression, initializer.Value.Kind()); Assert.Equal("ref b", initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestRefLocalDeclarationStatementWithMultipleInitializers() { var text = "ref T a = ref b, c = ref d;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("ref T", ds.Declaration.Type.ToString()); Assert.Equal(2, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); var initializer = ds.Declaration.Variables[0].Initializer as EqualsValueClauseSyntax; Assert.NotNull(initializer); Assert.NotEqual(default, initializer.EqualsToken); Assert.False(initializer.EqualsToken.IsMissing); Assert.Equal(SyntaxKind.RefExpression, initializer.Value.Kind()); Assert.Equal("ref b", initializer.Value.ToString()); Assert.NotEqual(default, ds.Declaration.Variables[1].Identifier); Assert.Equal("c", ds.Declaration.Variables[1].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[1].ArgumentList); initializer = ds.Declaration.Variables[1].Initializer as EqualsValueClauseSyntax; Assert.NotNull(initializer); Assert.NotEqual(default, initializer.EqualsToken); Assert.False(initializer.EqualsToken.IsMissing); Assert.Equal(SyntaxKind.RefExpression, initializer.Value.Kind()); Assert.Equal("ref d", initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestFixedStatement() { var text = "fixed(T a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.FixedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (FixedStatementSyntax)statement; Assert.NotEqual(default, fs.FixedKeyword); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotEqual(default, fs.OpenParenToken); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotNull(fs.Declaration); Assert.Equal(SyntaxKind.VariableDeclaration, fs.Declaration.Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.Equal("a = b", fs.Declaration.Variables[0].ToString()); Assert.NotNull(fs.Statement); Assert.Equal(SyntaxKind.Block, fs.Statement.Kind()); Assert.Equal("{ }", fs.Statement.ToString()); } [Fact] public void TestFixedVarStatement() { var text = "fixed(var a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.FixedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (FixedStatementSyntax)statement; Assert.NotEqual(default, fs.FixedKeyword); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotEqual(default, fs.OpenParenToken); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotNull(fs.Declaration); Assert.Equal(SyntaxKind.VariableDeclaration, fs.Declaration.Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("var", fs.Declaration.Type.ToString()); Assert.True(fs.Declaration.Type.IsVar); Assert.Equal(SyntaxKind.IdentifierName, fs.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)fs.Declaration.Type).Identifier.Kind()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.Equal("a = b", fs.Declaration.Variables[0].ToString()); Assert.NotNull(fs.Statement); Assert.Equal(SyntaxKind.Block, fs.Statement.Kind()); Assert.Equal("{ }", fs.Statement.ToString()); } [Fact] public void TestFixedStatementWithMultipleVariables() { var text = "fixed(T a = b, c = d) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.FixedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (FixedStatementSyntax)statement; Assert.NotEqual(default, fs.FixedKeyword); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotEqual(default, fs.OpenParenToken); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotNull(fs.Declaration); Assert.Equal(SyntaxKind.VariableDeclaration, fs.Declaration.Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(2, fs.Declaration.Variables.Count); Assert.Equal("a = b", fs.Declaration.Variables[0].ToString()); Assert.Equal("c = d", fs.Declaration.Variables[1].ToString()); Assert.NotNull(fs.Statement); Assert.Equal(SyntaxKind.Block, fs.Statement.Kind()); Assert.Equal("{ }", fs.Statement.ToString()); } [Fact] public void TestEmptyStatement() { var text = ";"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (EmptyStatementSyntax)statement; Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestLabeledStatement() { var text = "label: ;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LabeledStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ls = (LabeledStatementSyntax)statement; Assert.NotEqual(default, ls.Identifier); Assert.Equal("label", ls.Identifier.ToString()); Assert.NotEqual(default, ls.ColonToken); Assert.Equal(SyntaxKind.ColonToken, ls.ColonToken.Kind()); Assert.NotNull(ls.Statement); Assert.Equal(SyntaxKind.EmptyStatement, ls.Statement.Kind()); Assert.Equal(";", ls.Statement.ToString()); } [Fact] public void TestBreakStatement() { var text = "break;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.BreakStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var b = (BreakStatementSyntax)statement; Assert.NotEqual(default, b.BreakKeyword); Assert.False(b.BreakKeyword.IsMissing); Assert.Equal(SyntaxKind.BreakKeyword, b.BreakKeyword.Kind()); Assert.NotEqual(default, b.SemicolonToken); Assert.False(b.SemicolonToken.IsMissing); } [Fact] public void TestContinueStatement() { var text = "continue;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ContinueStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var cs = (ContinueStatementSyntax)statement; Assert.NotEqual(default, cs.ContinueKeyword); Assert.False(cs.ContinueKeyword.IsMissing); Assert.Equal(SyntaxKind.ContinueKeyword, cs.ContinueKeyword.Kind()); Assert.NotEqual(default, cs.SemicolonToken); Assert.False(cs.SemicolonToken.IsMissing); } [Fact] public void TestGotoStatement() { var text = "goto label;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.GotoStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var gs = (GotoStatementSyntax)statement; Assert.NotEqual(default, gs.GotoKeyword); Assert.False(gs.GotoKeyword.IsMissing); Assert.Equal(SyntaxKind.GotoKeyword, gs.GotoKeyword.Kind()); Assert.Equal(SyntaxKind.None, gs.CaseOrDefaultKeyword.Kind()); Assert.NotNull(gs.Expression); Assert.Equal("label", gs.Expression.ToString()); Assert.NotEqual(default, gs.SemicolonToken); Assert.False(gs.SemicolonToken.IsMissing); } [Fact] public void TestGotoCaseStatement() { var text = "goto case label;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.GotoCaseStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var gs = (GotoStatementSyntax)statement; Assert.NotEqual(default, gs.GotoKeyword); Assert.False(gs.GotoKeyword.IsMissing); Assert.Equal(SyntaxKind.GotoKeyword, gs.GotoKeyword.Kind()); Assert.NotEqual(default, gs.CaseOrDefaultKeyword); Assert.False(gs.CaseOrDefaultKeyword.IsMissing); Assert.Equal(SyntaxKind.CaseKeyword, gs.CaseOrDefaultKeyword.Kind()); Assert.NotNull(gs.Expression); Assert.Equal("label", gs.Expression.ToString()); Assert.NotEqual(default, gs.SemicolonToken); Assert.False(gs.SemicolonToken.IsMissing); } [Fact] public void TestGotoDefault() { var text = "goto default;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.GotoDefaultStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var gs = (GotoStatementSyntax)statement; Assert.NotEqual(default, gs.GotoKeyword); Assert.False(gs.GotoKeyword.IsMissing); Assert.Equal(SyntaxKind.GotoKeyword, gs.GotoKeyword.Kind()); Assert.NotEqual(default, gs.CaseOrDefaultKeyword); Assert.False(gs.CaseOrDefaultKeyword.IsMissing); Assert.Equal(SyntaxKind.DefaultKeyword, gs.CaseOrDefaultKeyword.Kind()); Assert.Null(gs.Expression); Assert.NotEqual(default, gs.SemicolonToken); Assert.False(gs.SemicolonToken.IsMissing); } [Fact] public void TestReturn() { var text = "return;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ReturnStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var rs = (ReturnStatementSyntax)statement; Assert.NotEqual(default, rs.ReturnKeyword); Assert.False(rs.ReturnKeyword.IsMissing); Assert.Equal(SyntaxKind.ReturnKeyword, rs.ReturnKeyword.Kind()); Assert.Null(rs.Expression); Assert.NotEqual(default, rs.SemicolonToken); Assert.False(rs.SemicolonToken.IsMissing); } [Fact] public void TestReturnExpression() { var text = "return a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ReturnStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var rs = (ReturnStatementSyntax)statement; Assert.NotEqual(default, rs.ReturnKeyword); Assert.False(rs.ReturnKeyword.IsMissing); Assert.Equal(SyntaxKind.ReturnKeyword, rs.ReturnKeyword.Kind()); Assert.NotNull(rs.Expression); Assert.Equal("a", rs.Expression.ToString()); Assert.NotEqual(default, rs.SemicolonToken); Assert.False(rs.SemicolonToken.IsMissing); } [Fact] public void TestYieldReturnExpression() { var text = "yield return a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.YieldReturnStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ys = (YieldStatementSyntax)statement; Assert.NotEqual(default, ys.YieldKeyword); Assert.False(ys.YieldKeyword.IsMissing); Assert.Equal(SyntaxKind.YieldKeyword, ys.YieldKeyword.Kind()); Assert.NotEqual(default, ys.ReturnOrBreakKeyword); Assert.False(ys.ReturnOrBreakKeyword.IsMissing); Assert.Equal(SyntaxKind.ReturnKeyword, ys.ReturnOrBreakKeyword.Kind()); Assert.NotNull(ys.Expression); Assert.Equal("a", ys.Expression.ToString()); Assert.NotEqual(default, ys.SemicolonToken); Assert.False(ys.SemicolonToken.IsMissing); } [Fact] public void TestYieldBreakExpression() { var text = "yield break;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.YieldBreakStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ys = (YieldStatementSyntax)statement; Assert.NotEqual(default, ys.YieldKeyword); Assert.False(ys.YieldKeyword.IsMissing); Assert.Equal(SyntaxKind.YieldKeyword, ys.YieldKeyword.Kind()); Assert.NotEqual(default, ys.ReturnOrBreakKeyword); Assert.False(ys.ReturnOrBreakKeyword.IsMissing); Assert.Equal(SyntaxKind.BreakKeyword, ys.ReturnOrBreakKeyword.Kind()); Assert.Null(ys.Expression); Assert.NotEqual(default, ys.SemicolonToken); Assert.False(ys.SemicolonToken.IsMissing); } [Fact] public void TestThrow() { var text = "throw;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ThrowStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (ThrowStatementSyntax)statement; Assert.NotEqual(default, ts.ThrowKeyword); Assert.False(ts.ThrowKeyword.IsMissing); Assert.Equal(SyntaxKind.ThrowKeyword, ts.ThrowKeyword.ContextualKind()); Assert.Null(ts.Expression); Assert.NotEqual(default, ts.SemicolonToken); Assert.False(ts.SemicolonToken.IsMissing); } [Fact] public void TestThrowExpression() { var text = "throw a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ThrowStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (ThrowStatementSyntax)statement; Assert.NotEqual(default, ts.ThrowKeyword); Assert.False(ts.ThrowKeyword.IsMissing); Assert.Equal(SyntaxKind.ThrowKeyword, ts.ThrowKeyword.ContextualKind()); Assert.NotNull(ts.Expression); Assert.Equal("a", ts.Expression.ToString()); Assert.NotEqual(default, ts.SemicolonToken); Assert.False(ts.SemicolonToken.IsMissing); } [Fact] public void TestTryCatch() { var text = "try { } catch(T e) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(1, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.Identifier); Assert.Equal("e", ts.Catches[0].Declaration.Identifier.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryCatchWithNoExceptionName() { var text = "try { } catch(T) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(1, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.Equal(SyntaxKind.None, ts.Catches[0].Declaration.Identifier.Kind()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryCatchWithNoExceptionDeclaration() { var text = "try { } catch { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(1, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.Null(ts.Catches[0].Declaration); Assert.NotNull(ts.Catches[0].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryCatchWithMultipleCatches() { var text = "try { } catch(T e) { } catch(T2) { } catch { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(3, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.Identifier); Assert.Equal("e", ts.Catches[0].Declaration.Identifier.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.NotEqual(default, ts.Catches[1].CatchKeyword); Assert.NotNull(ts.Catches[1].Declaration); Assert.NotEqual(default, ts.Catches[1].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[1].Declaration.Type); Assert.Equal("T2", ts.Catches[1].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[1].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[1].Block); Assert.NotEqual(default, ts.Catches[2].CatchKeyword); Assert.Null(ts.Catches[2].Declaration); Assert.NotNull(ts.Catches[2].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryFinally() { var text = "try { } finally { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(0, ts.Catches.Count); Assert.NotNull(ts.Finally); Assert.NotEqual(default, ts.Finally.FinallyKeyword); Assert.NotNull(ts.Finally.Block); } [Fact] public void TestTryCatchWithMultipleCatchesAndFinally() { var text = "try { } catch(T e) { } catch(T2) { } catch { } finally { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(3, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.Identifier); Assert.Equal("e", ts.Catches[0].Declaration.Identifier.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.NotEqual(default, ts.Catches[1].CatchKeyword); Assert.NotNull(ts.Catches[1].Declaration); Assert.NotEqual(default, ts.Catches[1].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[1].Declaration.Type); Assert.Equal("T2", ts.Catches[1].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[1].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[1].Block); Assert.NotEqual(default, ts.Catches[2].CatchKeyword); Assert.Null(ts.Catches[2].Declaration); Assert.NotNull(ts.Catches[2].Block); Assert.NotNull(ts.Finally); Assert.NotEqual(default, ts.Finally.FinallyKeyword); Assert.NotNull(ts.Finally.Block); } [Fact] public void TestChecked() { var text = "checked { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.CheckedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var cs = (CheckedStatementSyntax)statement; Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.CheckedKeyword, cs.Keyword.Kind()); Assert.NotNull(cs.Block); } [Fact] public void TestUnchecked() { var text = "unchecked { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UncheckedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var cs = (CheckedStatementSyntax)statement; Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.UncheckedKeyword, cs.Keyword.Kind()); Assert.NotNull(cs.Block); } [Fact] public void TestUnsafe() { var text = "unsafe { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UnsafeStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UnsafeStatementSyntax)statement; Assert.NotEqual(default, us.UnsafeKeyword); Assert.Equal(SyntaxKind.UnsafeKeyword, us.UnsafeKeyword.Kind()); Assert.NotNull(us.Block); } [Fact] public void TestWhile() { var text = "while(a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.WhileStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ws = (WhileStatementSyntax)statement; Assert.NotEqual(default, ws.WhileKeyword); Assert.Equal(SyntaxKind.WhileKeyword, ws.WhileKeyword.Kind()); Assert.NotEqual(default, ws.OpenParenToken); Assert.NotNull(ws.Condition); Assert.NotEqual(default, ws.CloseParenToken); Assert.Equal("a", ws.Condition.ToString()); Assert.NotNull(ws.Statement); Assert.Equal(SyntaxKind.Block, ws.Statement.Kind()); } [Fact] public void TestDoWhile() { var text = "do { } while (a);"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.DoStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (DoStatementSyntax)statement; Assert.NotEqual(default, ds.DoKeyword); Assert.Equal(SyntaxKind.DoKeyword, ds.DoKeyword.Kind()); Assert.NotNull(ds.Statement); Assert.NotEqual(default, ds.WhileKeyword); Assert.Equal(SyntaxKind.WhileKeyword, ds.WhileKeyword.Kind()); Assert.Equal(SyntaxKind.Block, ds.Statement.Kind()); Assert.NotEqual(default, ds.OpenParenToken); Assert.NotNull(ds.Condition); Assert.NotEqual(default, ds.CloseParenToken); Assert.Equal("a", ds.Condition.ToString()); Assert.NotEqual(default, ds.SemicolonToken); } [Fact] public void TestFor() { var text = "for(;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithVariableDeclaration() { var text = "for(T a = 0;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithVarDeclaration() { var text = "for(var a = 0;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("var", fs.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, fs.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)fs.Declaration.Type).Identifier.Kind()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithMultipleVariableDeclarations() { var text = "for(T a = 0, b = 1;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(2, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("b", fs.Declaration.Variables[1].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[1].Initializer.Value); Assert.Equal("1", fs.Declaration.Variables[1].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)] public void TestForWithRefVariableDeclaration() { var text = "for(ref T a = ref b, c = ref d;;) { }"; var statement = this.ParseStatement(text); UsingNode(statement); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } [Fact] public void TestForWithVariableInitializer() { var text = "for(a = 0;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(1, fs.Initializers.Count); Assert.Equal("a = 0", fs.Initializers[0].ToString()); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithMultipleVariableInitializers() { var text = "for(a = 0, b = 1;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(2, fs.Initializers.Count); Assert.Equal("a = 0", fs.Initializers[0].ToString()); Assert.Equal("b = 1", fs.Initializers[1].ToString()); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithCondition() { var text = "for(; a;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.NotNull(fs.Condition); Assert.Equal("a", fs.Condition.ToString()); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithIncrementor() { var text = "for(; ; a++) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(1, fs.Incrementors.Count); Assert.Equal("a++", fs.Incrementors[0].ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithMultipleIncrementors() { var text = "for(; ; a++, b++) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(2, fs.Incrementors.Count); Assert.Equal("a++", fs.Incrementors[0].ToString()); Assert.Equal("b++", fs.Incrementors[1].ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithDeclarationConditionAndIncrementor() { var text = "for(T a = 0; a < 10; a++) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.NotNull(fs.Condition); Assert.Equal("a < 10", fs.Condition.ToString()); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(1, fs.Incrementors.Count); Assert.Equal("a++", fs.Incrementors[0].ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForEach() { var text = "foreach(T a in b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("T", fs.Type.ToString()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForAsForEach() { var text = "for(T a in b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.True(fs.ForEachKeyword.IsMissing); Assert.Equal(1, fs.ForEachKeyword.TrailingTrivia.Count); Assert.Equal(SyntaxKind.SkippedTokensTrivia, fs.ForEachKeyword.TrailingTrivia[0].Kind()); Assert.Equal("for", fs.ForEachKeyword.TrailingTrivia[0].ToString()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("T", fs.Type.ToString()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForEachWithVar() { var text = "foreach(var a in b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("var", fs.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, fs.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)fs.Type).Identifier.Kind()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestIf() { var text = "if (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (IfStatementSyntax)statement; Assert.NotEqual(default, ss.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, ss.IfKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Condition); Assert.Equal("a", ss.Condition.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotNull(ss.Statement); Assert.Null(ss.Else); } [Fact] public void TestIfElse() { var text = "if (a) { } else { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (IfStatementSyntax)statement; Assert.NotEqual(default, ss.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, ss.IfKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Condition); Assert.Equal("a", ss.Condition.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotNull(ss.Statement); Assert.NotNull(ss.Else); Assert.NotEqual(default, ss.Else.ElseKeyword); Assert.Equal(SyntaxKind.ElseKeyword, ss.Else.ElseKeyword.Kind()); Assert.NotNull(ss.Else.Statement); } [Fact] public void TestIfElseIf() { var text = "if (a) { } else if (b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (IfStatementSyntax)statement; Assert.NotEqual(default, ss.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, ss.IfKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Condition); Assert.Equal("a", ss.Condition.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotNull(ss.Statement); Assert.NotNull(ss.Else); Assert.NotEqual(default, ss.Else.ElseKeyword); Assert.Equal(SyntaxKind.ElseKeyword, ss.Else.ElseKeyword.Kind()); Assert.NotNull(ss.Else.Statement); var subIf = (IfStatementSyntax)ss.Else.Statement; Assert.NotEqual(default, subIf.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, subIf.IfKeyword.Kind()); Assert.NotNull(subIf.Condition); Assert.Equal("b", subIf.Condition.ToString()); Assert.NotEqual(default, subIf.CloseParenToken); Assert.NotNull(subIf.Statement); } [Fact] public void TestLock() { var text = "lock (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LockStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ls = (LockStatementSyntax)statement; Assert.NotEqual(default, ls.LockKeyword); Assert.Equal(SyntaxKind.LockKeyword, ls.LockKeyword.Kind()); Assert.NotEqual(default, ls.OpenParenToken); Assert.NotNull(ls.Expression); Assert.Equal("a", ls.Expression.ToString()); Assert.NotEqual(default, ls.CloseParenToken); Assert.NotNull(ls.Statement); } [Fact] public void TestSwitch() { var text = "switch (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var diags = statement.ErrorsAndWarnings(); Assert.Equal(0, diags.Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(0, ss.Sections.Count); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithCase() { var text = "switch (a) { case b:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.NotEqual(default, caseLabelSyntax.ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithMultipleCases() { var text = "switch (a) { case b:; case c:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(2, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.NotEqual(default, caseLabelSyntax.ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.Equal(1, ss.Sections[1].Labels.Count); Assert.NotEqual(default, ss.Sections[1].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[1].Labels[0].Keyword.Kind()); var caseLabelSyntax2 = ss.Sections[1].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax2); Assert.NotNull(caseLabelSyntax2.Value); Assert.Equal("c", caseLabelSyntax2.Value.ToString()); Assert.NotEqual(default, caseLabelSyntax2.ColonToken); Assert.Equal(1, ss.Sections[1].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithDefaultCase() { var text = "switch (a) { default:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.DefaultKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); Assert.Equal(SyntaxKind.DefaultSwitchLabel, ss.Sections[0].Labels[0].Kind()); Assert.NotEqual(default, ss.Sections[0].Labels[0].ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithMultipleLabelsOnOneCase() { var text = "switch (a) { case b: case c:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(2, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.NotEqual(default, ss.Sections[0].Labels[1].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[1].Keyword.Kind()); var caseLabelSyntax2 = ss.Sections[0].Labels[1] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax2); Assert.NotNull(caseLabelSyntax2.Value); Assert.Equal("c", caseLabelSyntax2.Value.ToString()); Assert.NotEqual(default, ss.Sections[0].Labels[0].ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithMultipleStatementsOnOneCase() { var text = "switch (a) { case b: s1(); s2(); }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.Equal(2, ss.Sections[0].Statements.Count); Assert.Equal("s1();", ss.Sections[0].Statements[0].ToString()); Assert.Equal("s2();", ss.Sections[0].Statements[1].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestUsingWithExpression() { var text = "using (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.Null(us.Declaration); Assert.NotNull(us.Expression); Assert.Equal("a", us.Expression.ToString()); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingWithDeclaration() { var text = "using (T a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarWithDeclaration() { var text = "using T a = b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, us.SemicolonToken); } [Fact] public void TestUsingVarWithDeclarationTree() { UsingStatement(@"using T a = b;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "T"); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingWithVarDeclaration() { var text = "using (var a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarWithVarDeclaration() { var text = "using var a = b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); } [Fact] [WorkItem(36413, "https://github.com/dotnet/roslyn/issues/36413")] public void TestUsingVarWithInvalidDeclaration() { var text = "using public readonly var a = b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(2, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); Assert.Equal("public", statement.Errors()[0].Arguments[0]); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[1].Code); Assert.Equal("readonly", statement.Errors()[1].Arguments[0]); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(2, us.Modifiers.Count); Assert.Equal("public", us.Modifiers[0].ToString()); Assert.Equal("readonly", us.Modifiers[1].ToString()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); } [Fact] public void TestUsingVarWithVarDeclarationTree() { UsingStatement(@"using var a = b;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestAwaitUsingVarWithDeclarationTree() { UsingStatement(@"await using T a = b;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "T"); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestAwaitUsingWithVarDeclaration() { var text = "await using var a = b;"; var statement = this.ParseStatement(text, 0, TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.AwaitKeyword); Assert.Equal(SyntaxKind.AwaitKeyword, us.AwaitKeyword.ContextualKind()); Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); } [Fact] public void TestAwaitUsingVarWithVarDeclarationTree() { UsingStatement(@"await using var a = b;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact, WorkItem(30565, "https://github.com/dotnet/roslyn/issues/30565")] public void AwaitUsingVarWithVarDecl_Reversed() { UsingTree(@" class C { async void M() { using await var x = null; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "await"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "var"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestAwaitUsingVarWithVarAndNoUsingDeclarationTree() { UsingStatement(@"await var a = b;", TestOptions.Regular8, // (1,1): error CS1073: Unexpected token 'a' // await var a = b; Diagnostic(ErrorCode.ERR_UnexpectedToken, "await var ").WithArguments("a").WithLocation(1, 1), // (1,11): error CS1002: ; expected // await var a = b; Diagnostic(ErrorCode.ERR_SemicolonExpected, "a").WithLocation(1, 11)); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AwaitExpression); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } M(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TestUsingWithDeclarationWithMultipleVariables() { var text = "using (T a = b, c = d) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(2, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, us.Declaration.Variables[1].Identifier); Assert.Equal("c", us.Declaration.Variables[1].Identifier.ToString()); Assert.Null(us.Declaration.Variables[1].ArgumentList); Assert.NotNull(us.Declaration.Variables[1].Initializer); Assert.NotEqual(default, us.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[1].Initializer.Value); Assert.Equal("d", us.Declaration.Variables[1].Initializer.Value.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarWithDeclarationWithMultipleVariables() { var text = "using T a = b, c = d;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(2, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, us.Declaration.Variables[1].Identifier); Assert.Equal("c", us.Declaration.Variables[1].Identifier.ToString()); Assert.Null(us.Declaration.Variables[1].ArgumentList); Assert.NotNull(us.Declaration.Variables[1].Initializer); Assert.NotEqual(default, us.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[1].Initializer.Value); Assert.Equal("d", us.Declaration.Variables[1].Initializer.Value.ToString()); } [Fact] public void TestUsingVarWithDeclarationMultipleVariablesTree() { UsingStatement(@"using T a = b, c = d;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "T"); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "d"); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingSpecialCase1() { var text = "using (f ? x = a : x = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.Null(us.Declaration); Assert.NotNull(us.Expression); Assert.Equal("f ? x = a : x = b", us.Expression.ToString()); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarSpecialCase1() { var text = "using var x = f ? a : b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.Equal("var x = f ? a : b", us.Declaration.ToString()); } [Fact] public void TestUsingVarSpecialCase1Tree() { UsingStatement(@"using var x = f ? a : b;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName, "f"); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName, "a"); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingSpecialCase2() { var text = "using (f ? x = a) { }"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.Equal("f ? x = a", us.Declaration.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarSpecialCase2() { var text = "using f ? x = a;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.Equal("f ? x = a", us.Declaration.ToString()); } [Fact] public void TestUsingVarSpecialCase2Tree() { UsingStatement(@"using f ? x = a;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName, "f"); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "a"); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingSpecialCase3() { var text = "using (f ? x, y) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.Equal("f ? x, y", us.Declaration.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarSpecialCase3() { var text = "using f ? x, y;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.Equal("f ? x, y", us.Declaration.ToString()); } [Fact] public void TestUsingVarSpecialCase3Tree() { UsingStatement("using f? x, y;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName, "f"); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefTree() { UsingStatement("using ref int x = ref y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefReadonlyTree() { UsingStatement("using ref readonly int x = ref y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ReadOnlyKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefVarTree() { UsingStatement("using ref var x = ref y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefVarIsYTree() { UsingStatement("using ref var x = y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarReadonlyMultipleDeclarations() { UsingStatement("using readonly var x, y = ref z;", TestOptions.Regular8, // (1,7): error CS0106: The modifier 'readonly' is not valid for this item // using readonly var x, y = ref z; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(1, 7)); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.ReadOnlyKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "z"); { N(SyntaxKind.IdentifierToken, "z"); } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestContextualKeywordsAsLocalVariableTypes() { TestContextualKeywordAsLocalVariableType(SyntaxKind.PartialKeyword); TestContextualKeywordAsLocalVariableType(SyntaxKind.AsyncKeyword); TestContextualKeywordAsLocalVariableType(SyntaxKind.AwaitKeyword); } private void TestContextualKeywordAsLocalVariableType(SyntaxKind kind) { var keywordText = SyntaxFacts.GetText(kind); var text = keywordText + " o = null;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); var decl = (LocalDeclarationStatementSyntax)statement; Assert.Equal(keywordText, decl.Declaration.Type.ToString()); Assert.IsType<IdentifierNameSyntax>(decl.Declaration.Type); var name = (IdentifierNameSyntax)decl.Declaration.Type; Assert.Equal(kind, name.Identifier.ContextualKind()); Assert.Equal(SyntaxKind.IdentifierToken, name.Identifier.Kind()); } [Fact] public void Bug862649() { var text = @"static char[] delimiter;"; var tree = SyntaxFactory.ParseStatement(text); var toText = tree.ToFullString(); Assert.Equal(text, toText); } [Fact] public void TestForEachAfterOffset() { const string prefix = "GARBAGE"; var text = "foreach(T a in b) { }"; var statement = this.ParseStatement(prefix + text, offset: prefix.Length); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("T", fs.Type.ToString()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")] [Fact] public void Bug684860_SkippedTokens() { const int n = 100000; // 100000 instances of "0+" in: // #pragma warning disable 1 0+0+0+... var builder = new System.Text.StringBuilder(); builder.Append("#pragma warning disable 1 "); for (int i = 0; i < n; i++) { builder.Append("0+"); } builder.AppendLine(); var text = builder.ToString(); var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); var walker = new TokenAndTriviaWalker(); walker.Visit(root); Assert.True(walker.Tokens > n); var tokens1 = root.DescendantTokens(descendIntoTrivia: false).ToArray(); var tokens2 = root.DescendantTokens(descendIntoTrivia: true).ToArray(); Assert.True((tokens2.Length - tokens1.Length) > n); } [WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")] [Fact] public void Bug684860_XmlText() { const int n = 100000; // 100000 instances of "&lt;" in: // /// <x a="&lt;&lt;&lt;..."/> // class { } var builder = new System.Text.StringBuilder(); builder.Append("/// <x a=\""); for (int i = 0; i < n; i++) { builder.Append("&lt;"); } builder.AppendLine("\"/>"); builder.AppendLine("class C { }"); var text = builder.ToString(); var tree = SyntaxFactory.ParseSyntaxTree(text, options: new CSharpParseOptions(documentationMode: DocumentationMode.Parse)); var root = tree.GetRoot(); var walker = new TokenAndTriviaWalker(); walker.Visit(root); Assert.True(walker.Tokens > n); var tokens = root.DescendantTokens(descendIntoTrivia: true).ToArray(); Assert.True(tokens.Length > n); } [Fact] public void ExceptionFilter_IfKeyword() { const string source = @" class C { void M() { try { } catch (System.Exception e) if (true) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var root = tree.GetRoot(); tree.GetDiagnostics(root).Verify( // (7,36): error CS1003: Syntax error, 'when' expected // catch (System.Exception e) if (true) { } CSharpTestBase.Diagnostic(ErrorCode.ERR_SyntaxError, "if").WithArguments("when", "if").WithLocation(7, 36)); var filterClause = root.DescendantNodes().OfType<CatchFilterClauseSyntax>().Single(); Assert.Equal(SyntaxKind.WhenKeyword, filterClause.WhenKeyword.Kind()); Assert.True(filterClause.WhenKeyword.HasStructuredTrivia); } [Fact] public void Tuple001() { var source = @" class C1 { static void Test(int arg1, (byte, byte) arg2) { (int, int)? t1 = new(int, int)?(); (int, int)? t1a = new(int, int)?((1,1)); (int, int)? t1b = new(int, int)?[1]; (int, int)? t1c = new(int, int)?[] {(1,1)}; (int, int)? t2 = default((int a, int b)); (int, int) t3 = (a: (int)arg1, b: (int)arg1); (int, int) t4 = ((int a, int b))(arg1, arg1); (int, int) t5 = ((int, int))arg2; List<(int, int)> l = new List<(int, int)>() { (a: arg1, b: arg1), (arg1, arg1) }; Func<(int a, int b), (int a, int b)> f = ((int a, int b) t) => t; var x = from i in ""qq"" from j in ""ee"" select (i, j); foreach ((int, int) e in new (int, int)[10]) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); tree.GetDiagnostics().Verify(); } [Fact] [WorkItem(684860, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/266237")] public void DevDiv266237() { var source = @" class Program { static void Go() { using (var p = new P { } protected override void M() { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); tree.GetDiagnostics(tree.GetRoot()).Verify( // (9,10): error CS1026: ) expected // } CSharpTestBase.Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(9, 10), // (9,10): error CS1002: ; expected // } CSharpTestBase.Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(9, 10), // (9,10): error CS1513: } expected // } CSharpTestBase.Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(9, 10)); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedStatementNotFollowedBySemicolon() { var text = @"if (true) System.Console.WriteLine(true)"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, statement.Errors()[0].Code); } [WorkItem(266237, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=266237")] [Fact] public void NullExceptionInLabeledStatement() { UsingStatement(@"{ label: public", // (1,1): error CS1073: Unexpected token 'public' // { label: public Diagnostic(ErrorCode.ERR_UnexpectedToken, "{ label: ").WithArguments("public").WithLocation(1, 1), // (1,10): error CS1002: ; expected // { label: public Diagnostic(ErrorCode.ERR_SemicolonExpected, "public").WithLocation(1, 10), // (1,10): error CS1513: } expected // { label: public Diagnostic(ErrorCode.ERR_RbraceExpected, "public").WithLocation(1, 10) ); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LabeledStatement); { N(SyntaxKind.IdentifierToken, "label"); N(SyntaxKind.ColonToken); M(SyntaxKind.EmptyStatement); { M(SyntaxKind.SemicolonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseElseWithoutPrecedingIfStatement() { UsingStatement("else {}", // (1,1): error CS8641: 'else' cannot start a statement. // else {} Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 1), // (1,1): error CS1003: Syntax error, '(' expected // else {} Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 1), // (1,1): error CS1525: Invalid expression term 'else' // else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 1), // (1,1): error CS1026: ) expected // else {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 1), // (1,1): error CS1525: Invalid expression term 'else' // else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 1), // (1,1): error CS1002: ; expected // else {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 1) ); N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseElseAndElseWithoutPrecedingIfStatement() { UsingStatement("{ else {} else {} }", // (1,3): error CS8641: 'else' cannot start a statement. // { else {} else {} } Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 3), // (1,3): error CS1003: Syntax error, '(' expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 3), // (1,3): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 3), // (1,3): error CS1026: ) expected // { else {} else {} } Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 3), // (1,3): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 3), // (1,3): error CS1002: ; expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 3), // (1,11): error CS8641: 'else' cannot start a statement. // { else {} else {} } Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '(' expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 11), // (1,11): error CS1026: ) expected // { else {} else {} } Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 11), // (1,11): error CS1002: ; expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 11) ); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseSubsequentElseWithoutPrecedingIfStatement() { UsingStatement("{ if (a) { } else { } else { } }", // (1,23): error CS8641: 'else' cannot start a statement. // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 23), // (1,23): error CS1003: Syntax error, '(' expected // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 23), // (1,23): error CS1525: Invalid expression term 'else' // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 23), // (1,23): error CS1026: ) expected // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 23), // (1,23): error CS1525: Invalid expression term 'else' // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 23), // (1,23): error CS1002: ; expected // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 23) ); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseElseKeywordPlacedAsIfEmbeddedStatement() { UsingStatement("if (a) else {}", // (1,8): error CS8641: 'else' cannot start a statement. // if (a) else {} Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 8), // (1,8): error CS1003: Syntax error, '(' expected // if (a) else {} Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 8), // (1,8): error CS1525: Invalid expression term 'else' // if (a) else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 8), // (1,8): error CS1026: ) expected // if (a) else {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 8), // (1,8): error CS1525: Invalid expression term 'else' // if (a) else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 8), // (1,8): error CS1002: ; expected // if (a) else {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 8) ); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } EOF(); } [Fact] public void ParseSwitch01() { UsingStatement("switch 1+2 {}", // (1,8): error CS8415: Parentheses are required around the switch governing expression. // switch 1+2 {} Diagnostic(ErrorCode.ERR_SwitchGoverningExpressionRequiresParens, "1+2").WithLocation(1, 8) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); M(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseSwitch02() { UsingStatement("switch (a: 0) {}", // (1,13): error CS8124: Tuple must contain at least two elements. // switch (a: 0) {} Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(1, 13) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseSwitch03() { UsingStatement("switch (a: 0, b: 4) {}"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseSwitch04() { UsingStatement("switch (1) + (2) {}", // (1,8): error CS8415: Parentheses are required around the switch governing expression. // switch (1) + (2) {} Diagnostic(ErrorCode.ERR_SwitchGoverningExpressionRequiresParens, "(1) + (2)").WithLocation(1, 8) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); M(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseCreateNullableTuple_01() { UsingStatement("_ = new (int, int)? {};"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ObjectInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParseCreateNullableTuple_02() { UsingStatement("_ = new (int, int) ? (x) : (y);", // (1,1): error CS1073: Unexpected token ':' // _ = new (int, int) ? (x) : (y); Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = new (int, int) ? (x) ").WithArguments(":").WithLocation(1, 1), // (1,26): error CS1002: ; expected // _ = new (int, int) ? (x) : (y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(1, 26) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseParenToken); } } } M(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParsePointerToArray() { UsingStatement("int []* p;", // (1,7): error CS1001: Identifier expected // int []* p; Diagnostic(ErrorCode.ERR_IdentifierExpected, "*").WithLocation(1, 7), // (1,7): error CS1003: Syntax error, ',' expected // int []* p; Diagnostic(ErrorCode.ERR_SyntaxError, "*").WithArguments(",", "*").WithLocation(1, 7) ); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParseNewNullableWithInitializer() { UsingStatement("_ = new int? {};"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ObjectInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } private sealed class TokenAndTriviaWalker : CSharpSyntaxWalker { public int Tokens; public TokenAndTriviaWalker() : base(SyntaxWalkerDepth.StructuredTrivia) { } public override void VisitToken(SyntaxToken token) { Tokens++; base.VisitToken(token); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StatementParsingTests : ParsingTests { public StatementParsingTests(ITestOutputHelper output) : base(output) { } private StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions options = null) { return SyntaxFactory.ParseStatement(text, offset, options); } [Fact] [WorkItem(17458, "https://github.com/dotnet/roslyn/issues/17458")] public void ParsePrivate() { UsingStatement("private", // (1,1): error CS1073: Unexpected token 'private' // private Diagnostic(ErrorCode.ERR_UnexpectedToken, "").WithArguments("private").WithLocation(1, 1), // (1,1): error CS1525: Invalid expression term 'private' // private Diagnostic(ErrorCode.ERR_InvalidExprTerm, "private").WithArguments("private").WithLocation(1, 1), // (1,1): error CS1002: ; expected // private Diagnostic(ErrorCode.ERR_SemicolonExpected, "private").WithLocation(1, 1) ); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TestName() { var text = "a();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.IdentifierName, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestDottedName() { var text = "a.b();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a.b()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestGenericName() { var text = "a<b>();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.GenericName, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a<b>()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestGenericDotName() { var text = "a<b>.c();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a<b>.c()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestDotGenericName() { var text = "a.b<c>();"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.InvocationExpression, es.Expression.Kind()); Assert.Equal(SyntaxKind.SimpleMemberAccessExpression, ((InvocationExpressionSyntax)es.Expression).Expression.Kind()); Assert.Equal("a.b<c>()", es.Expression.ToString()); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } private void TestPostfixUnaryOperator(SyntaxKind kind, ParseOptions options = null) { var text = "a" + SyntaxFacts.GetText(kind) + ";"; var statement = this.ParseStatement(text, options: options); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ExpressionStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (ExpressionStatementSyntax)statement; Assert.NotNull(es.Expression); Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); var opKind = SyntaxFacts.GetPostfixUnaryExpression(kind); Assert.Equal(opKind, es.Expression.Kind()); var us = (PostfixUnaryExpressionSyntax)es.Expression; Assert.Equal("a", us.Operand.ToString()); Assert.Equal(kind, us.OperatorToken.Kind()); } [Fact] public void TestPostfixUnaryOperators() { TestPostfixUnaryOperator(SyntaxKind.PlusPlusToken); TestPostfixUnaryOperator(SyntaxKind.MinusMinusToken); TestPostfixUnaryOperator(SyntaxKind.ExclamationToken, TestOptions.Regular8); } [Fact] public void TestLocalDeclarationStatement() { var text = "T a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithVar() { // note: semantically this would require an initializer, but we don't know // about var being special until we bind. var text = "var a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("var", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, ds.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)ds.Declaration.Type).Identifier.Kind()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithTuple() { var text = "(int, int) a;"; var statement = this.ParseStatement(text, options: TestOptions.Regular); (text).ToString(); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("(int, int)", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.TupleType, ds.Declaration.Type.Kind()); var tt = (TupleTypeSyntax)ds.Declaration.Type; Assert.Equal(SyntaxKind.PredefinedType, tt.Elements[0].Type.Kind()); Assert.Equal(SyntaxKind.None, tt.Elements[1].Identifier.Kind()); Assert.Equal(2, tt.Elements.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithNamedTuple() { var text = "(T x, (U k, V l, W m) y) a;"; var statement = this.ParseStatement(text); (text).ToString(); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("(T x, (U k, V l, W m) y)", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.TupleType, ds.Declaration.Type.Kind()); var tt = (TupleTypeSyntax)ds.Declaration.Type; Assert.Equal(SyntaxKind.IdentifierName, tt.Elements[0].Type.Kind()); Assert.Equal("y", tt.Elements[1].Identifier.ToString()); Assert.Equal(2, tt.Elements.Count); tt = (TupleTypeSyntax)tt.Elements[1].Type; Assert.Equal("(U k, V l, W m)", tt.ToString()); Assert.Equal(SyntaxKind.IdentifierName, tt.Elements[0].Type.Kind()); Assert.Equal("l", tt.Elements[1].Identifier.ToString()); Assert.Equal(3, tt.Elements.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithDynamic() { // note: semantically this would require an initializer, but we don't know // about dynamic being special until we bind. var text = "dynamic a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("dynamic", ds.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, ds.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)ds.Declaration.Type).Identifier.Kind()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithGenericType() { var text = "T<a> b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T<a>", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("b", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithDottedType() { var text = "T.X.Y a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T.X.Y", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithMixedType() { var text = "T<t>.X<x>.Y<y> a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T<t>.X<x>.Y<y>", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithArrayType() { var text = "T[][,][,,] a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T[][,][,,]", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithPointerType() { var text = "T* a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T*", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithNullableType() { var text = "T? a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T?", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithMultipleVariables() { var text = "T a, b, c;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(3, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[1].Identifier); Assert.Equal("b", ds.Declaration.Variables[1].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[1].ArgumentList); Assert.Null(ds.Declaration.Variables[1].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[2].Identifier); Assert.Equal("c", ds.Declaration.Variables[2].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[2].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithInitializer() { var text = "T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithMultipleVariablesAndInitializers() { var text = "T a = va, b = vb, c = vc;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(3, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("va", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.Declaration.Variables[1].Identifier); Assert.Equal("b", ds.Declaration.Variables[1].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[1].ArgumentList); Assert.NotEqual(default, ds.Declaration.Variables[1].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[1].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[1].Initializer.Value); Assert.Equal("vb", ds.Declaration.Variables[1].Initializer.Value.ToString()); Assert.NotEqual(default, ds.Declaration.Variables[2].Identifier); Assert.Equal("c", ds.Declaration.Variables[2].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[2].ArgumentList); Assert.NotEqual(default, ds.Declaration.Variables[2].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[2].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[2].Initializer.Value); Assert.Equal("vc", ds.Declaration.Variables[2].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestLocalDeclarationStatementWithArrayInitializer() { var text = "T a = {b, c};"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ArrayInitializerExpression, ds.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal("{b, c}", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestConstLocalDeclarationStatement() { var text = "const T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.ConstKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestStaticLocalDeclarationStatement() { var text = "static T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestReadOnlyLocalDeclarationStatement() { var text = "readonly T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestVolatileLocalDeclarationStatement() { var text = "volatile T a = b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(1, ds.Modifiers.Count); Assert.Equal(SyntaxKind.VolatileKeyword, ds.Modifiers[0].Kind()); Assert.NotNull(ds.Declaration.Type); Assert.Equal("T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.NotNull(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.Declaration.Variables[0].Initializer.EqualsToken); Assert.False(ds.Declaration.Variables[0].Initializer.EqualsToken.IsMissing); Assert.NotNull(ds.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", ds.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestRefLocalDeclarationStatement() { var text = "ref T a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("ref T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); Assert.Null(ds.Declaration.Variables[0].Initializer); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestRefLocalDeclarationStatementWithInitializer() { var text = "ref T a = ref b;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("ref T", ds.Declaration.Type.ToString()); Assert.Equal(1, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); var initializer = ds.Declaration.Variables[0].Initializer as EqualsValueClauseSyntax; Assert.NotNull(initializer); Assert.NotEqual(default, initializer.EqualsToken); Assert.False(initializer.EqualsToken.IsMissing); Assert.Equal(SyntaxKind.RefExpression, initializer.Value.Kind()); Assert.Equal("ref b", initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestRefLocalDeclarationStatementWithMultipleInitializers() { var text = "ref T a = ref b, c = ref d;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (LocalDeclarationStatementSyntax)statement; Assert.Equal(0, ds.Modifiers.Count); Assert.NotNull(ds.Declaration.Type); Assert.Equal("ref T", ds.Declaration.Type.ToString()); Assert.Equal(2, ds.Declaration.Variables.Count); Assert.NotEqual(default, ds.Declaration.Variables[0].Identifier); Assert.Equal("a", ds.Declaration.Variables[0].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[0].ArgumentList); var initializer = ds.Declaration.Variables[0].Initializer as EqualsValueClauseSyntax; Assert.NotNull(initializer); Assert.NotEqual(default, initializer.EqualsToken); Assert.False(initializer.EqualsToken.IsMissing); Assert.Equal(SyntaxKind.RefExpression, initializer.Value.Kind()); Assert.Equal("ref b", initializer.Value.ToString()); Assert.NotEqual(default, ds.Declaration.Variables[1].Identifier); Assert.Equal("c", ds.Declaration.Variables[1].Identifier.ToString()); Assert.Null(ds.Declaration.Variables[1].ArgumentList); initializer = ds.Declaration.Variables[1].Initializer as EqualsValueClauseSyntax; Assert.NotNull(initializer); Assert.NotEqual(default, initializer.EqualsToken); Assert.False(initializer.EqualsToken.IsMissing); Assert.Equal(SyntaxKind.RefExpression, initializer.Value.Kind()); Assert.Equal("ref d", initializer.Value.ToString()); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestFixedStatement() { var text = "fixed(T a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.FixedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (FixedStatementSyntax)statement; Assert.NotEqual(default, fs.FixedKeyword); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotEqual(default, fs.OpenParenToken); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotNull(fs.Declaration); Assert.Equal(SyntaxKind.VariableDeclaration, fs.Declaration.Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.Equal("a = b", fs.Declaration.Variables[0].ToString()); Assert.NotNull(fs.Statement); Assert.Equal(SyntaxKind.Block, fs.Statement.Kind()); Assert.Equal("{ }", fs.Statement.ToString()); } [Fact] public void TestFixedVarStatement() { var text = "fixed(var a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.FixedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (FixedStatementSyntax)statement; Assert.NotEqual(default, fs.FixedKeyword); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotEqual(default, fs.OpenParenToken); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotNull(fs.Declaration); Assert.Equal(SyntaxKind.VariableDeclaration, fs.Declaration.Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("var", fs.Declaration.Type.ToString()); Assert.True(fs.Declaration.Type.IsVar); Assert.Equal(SyntaxKind.IdentifierName, fs.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)fs.Declaration.Type).Identifier.Kind()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.Equal("a = b", fs.Declaration.Variables[0].ToString()); Assert.NotNull(fs.Statement); Assert.Equal(SyntaxKind.Block, fs.Statement.Kind()); Assert.Equal("{ }", fs.Statement.ToString()); } [Fact] public void TestFixedStatementWithMultipleVariables() { var text = "fixed(T a = b, c = d) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.FixedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (FixedStatementSyntax)statement; Assert.NotEqual(default, fs.FixedKeyword); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotEqual(default, fs.OpenParenToken); Assert.False(fs.FixedKeyword.IsMissing); Assert.NotNull(fs.Declaration); Assert.Equal(SyntaxKind.VariableDeclaration, fs.Declaration.Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(2, fs.Declaration.Variables.Count); Assert.Equal("a = b", fs.Declaration.Variables[0].ToString()); Assert.Equal("c = d", fs.Declaration.Variables[1].ToString()); Assert.NotNull(fs.Statement); Assert.Equal(SyntaxKind.Block, fs.Statement.Kind()); Assert.Equal("{ }", fs.Statement.ToString()); } [Fact] public void TestEmptyStatement() { var text = ";"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.EmptyStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var es = (EmptyStatementSyntax)statement; Assert.NotEqual(default, es.SemicolonToken); Assert.False(es.SemicolonToken.IsMissing); } [Fact] public void TestLabeledStatement() { var text = "label: ;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LabeledStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ls = (LabeledStatementSyntax)statement; Assert.NotEqual(default, ls.Identifier); Assert.Equal("label", ls.Identifier.ToString()); Assert.NotEqual(default, ls.ColonToken); Assert.Equal(SyntaxKind.ColonToken, ls.ColonToken.Kind()); Assert.NotNull(ls.Statement); Assert.Equal(SyntaxKind.EmptyStatement, ls.Statement.Kind()); Assert.Equal(";", ls.Statement.ToString()); } [Fact] public void TestBreakStatement() { var text = "break;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.BreakStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var b = (BreakStatementSyntax)statement; Assert.NotEqual(default, b.BreakKeyword); Assert.False(b.BreakKeyword.IsMissing); Assert.Equal(SyntaxKind.BreakKeyword, b.BreakKeyword.Kind()); Assert.NotEqual(default, b.SemicolonToken); Assert.False(b.SemicolonToken.IsMissing); } [Fact] public void TestContinueStatement() { var text = "continue;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ContinueStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var cs = (ContinueStatementSyntax)statement; Assert.NotEqual(default, cs.ContinueKeyword); Assert.False(cs.ContinueKeyword.IsMissing); Assert.Equal(SyntaxKind.ContinueKeyword, cs.ContinueKeyword.Kind()); Assert.NotEqual(default, cs.SemicolonToken); Assert.False(cs.SemicolonToken.IsMissing); } [Fact] public void TestGotoStatement() { var text = "goto label;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.GotoStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var gs = (GotoStatementSyntax)statement; Assert.NotEqual(default, gs.GotoKeyword); Assert.False(gs.GotoKeyword.IsMissing); Assert.Equal(SyntaxKind.GotoKeyword, gs.GotoKeyword.Kind()); Assert.Equal(SyntaxKind.None, gs.CaseOrDefaultKeyword.Kind()); Assert.NotNull(gs.Expression); Assert.Equal("label", gs.Expression.ToString()); Assert.NotEqual(default, gs.SemicolonToken); Assert.False(gs.SemicolonToken.IsMissing); } [Fact] public void TestGotoCaseStatement() { var text = "goto case label;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.GotoCaseStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var gs = (GotoStatementSyntax)statement; Assert.NotEqual(default, gs.GotoKeyword); Assert.False(gs.GotoKeyword.IsMissing); Assert.Equal(SyntaxKind.GotoKeyword, gs.GotoKeyword.Kind()); Assert.NotEqual(default, gs.CaseOrDefaultKeyword); Assert.False(gs.CaseOrDefaultKeyword.IsMissing); Assert.Equal(SyntaxKind.CaseKeyword, gs.CaseOrDefaultKeyword.Kind()); Assert.NotNull(gs.Expression); Assert.Equal("label", gs.Expression.ToString()); Assert.NotEqual(default, gs.SemicolonToken); Assert.False(gs.SemicolonToken.IsMissing); } [Fact] public void TestGotoDefault() { var text = "goto default;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.GotoDefaultStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var gs = (GotoStatementSyntax)statement; Assert.NotEqual(default, gs.GotoKeyword); Assert.False(gs.GotoKeyword.IsMissing); Assert.Equal(SyntaxKind.GotoKeyword, gs.GotoKeyword.Kind()); Assert.NotEqual(default, gs.CaseOrDefaultKeyword); Assert.False(gs.CaseOrDefaultKeyword.IsMissing); Assert.Equal(SyntaxKind.DefaultKeyword, gs.CaseOrDefaultKeyword.Kind()); Assert.Null(gs.Expression); Assert.NotEqual(default, gs.SemicolonToken); Assert.False(gs.SemicolonToken.IsMissing); } [Fact] public void TestReturn() { var text = "return;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ReturnStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var rs = (ReturnStatementSyntax)statement; Assert.NotEqual(default, rs.ReturnKeyword); Assert.False(rs.ReturnKeyword.IsMissing); Assert.Equal(SyntaxKind.ReturnKeyword, rs.ReturnKeyword.Kind()); Assert.Null(rs.Expression); Assert.NotEqual(default, rs.SemicolonToken); Assert.False(rs.SemicolonToken.IsMissing); } [Fact] public void TestReturnExpression() { var text = "return a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ReturnStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var rs = (ReturnStatementSyntax)statement; Assert.NotEqual(default, rs.ReturnKeyword); Assert.False(rs.ReturnKeyword.IsMissing); Assert.Equal(SyntaxKind.ReturnKeyword, rs.ReturnKeyword.Kind()); Assert.NotNull(rs.Expression); Assert.Equal("a", rs.Expression.ToString()); Assert.NotEqual(default, rs.SemicolonToken); Assert.False(rs.SemicolonToken.IsMissing); } [Fact] public void TestYieldReturnExpression() { var text = "yield return a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.YieldReturnStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ys = (YieldStatementSyntax)statement; Assert.NotEqual(default, ys.YieldKeyword); Assert.False(ys.YieldKeyword.IsMissing); Assert.Equal(SyntaxKind.YieldKeyword, ys.YieldKeyword.Kind()); Assert.NotEqual(default, ys.ReturnOrBreakKeyword); Assert.False(ys.ReturnOrBreakKeyword.IsMissing); Assert.Equal(SyntaxKind.ReturnKeyword, ys.ReturnOrBreakKeyword.Kind()); Assert.NotNull(ys.Expression); Assert.Equal("a", ys.Expression.ToString()); Assert.NotEqual(default, ys.SemicolonToken); Assert.False(ys.SemicolonToken.IsMissing); } [Fact] public void TestYieldBreakExpression() { var text = "yield break;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.YieldBreakStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ys = (YieldStatementSyntax)statement; Assert.NotEqual(default, ys.YieldKeyword); Assert.False(ys.YieldKeyword.IsMissing); Assert.Equal(SyntaxKind.YieldKeyword, ys.YieldKeyword.Kind()); Assert.NotEqual(default, ys.ReturnOrBreakKeyword); Assert.False(ys.ReturnOrBreakKeyword.IsMissing); Assert.Equal(SyntaxKind.BreakKeyword, ys.ReturnOrBreakKeyword.Kind()); Assert.Null(ys.Expression); Assert.NotEqual(default, ys.SemicolonToken); Assert.False(ys.SemicolonToken.IsMissing); } [Fact] public void TestThrow() { var text = "throw;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ThrowStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (ThrowStatementSyntax)statement; Assert.NotEqual(default, ts.ThrowKeyword); Assert.False(ts.ThrowKeyword.IsMissing); Assert.Equal(SyntaxKind.ThrowKeyword, ts.ThrowKeyword.ContextualKind()); Assert.Null(ts.Expression); Assert.NotEqual(default, ts.SemicolonToken); Assert.False(ts.SemicolonToken.IsMissing); } [Fact] public void TestThrowExpression() { var text = "throw a;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ThrowStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (ThrowStatementSyntax)statement; Assert.NotEqual(default, ts.ThrowKeyword); Assert.False(ts.ThrowKeyword.IsMissing); Assert.Equal(SyntaxKind.ThrowKeyword, ts.ThrowKeyword.ContextualKind()); Assert.NotNull(ts.Expression); Assert.Equal("a", ts.Expression.ToString()); Assert.NotEqual(default, ts.SemicolonToken); Assert.False(ts.SemicolonToken.IsMissing); } [Fact] public void TestTryCatch() { var text = "try { } catch(T e) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(1, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.Identifier); Assert.Equal("e", ts.Catches[0].Declaration.Identifier.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryCatchWithNoExceptionName() { var text = "try { } catch(T) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(1, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.Equal(SyntaxKind.None, ts.Catches[0].Declaration.Identifier.Kind()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryCatchWithNoExceptionDeclaration() { var text = "try { } catch { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(1, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.Null(ts.Catches[0].Declaration); Assert.NotNull(ts.Catches[0].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryCatchWithMultipleCatches() { var text = "try { } catch(T e) { } catch(T2) { } catch { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(3, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.Identifier); Assert.Equal("e", ts.Catches[0].Declaration.Identifier.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.NotEqual(default, ts.Catches[1].CatchKeyword); Assert.NotNull(ts.Catches[1].Declaration); Assert.NotEqual(default, ts.Catches[1].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[1].Declaration.Type); Assert.Equal("T2", ts.Catches[1].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[1].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[1].Block); Assert.NotEqual(default, ts.Catches[2].CatchKeyword); Assert.Null(ts.Catches[2].Declaration); Assert.NotNull(ts.Catches[2].Block); Assert.Null(ts.Finally); } [Fact] public void TestTryFinally() { var text = "try { } finally { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(0, ts.Catches.Count); Assert.NotNull(ts.Finally); Assert.NotEqual(default, ts.Finally.FinallyKeyword); Assert.NotNull(ts.Finally.Block); } [Fact] public void TestTryCatchWithMultipleCatchesAndFinally() { var text = "try { } catch(T e) { } catch(T2) { } catch { } finally { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.TryStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ts = (TryStatementSyntax)statement; Assert.NotEqual(default, ts.TryKeyword); Assert.False(ts.TryKeyword.IsMissing); Assert.NotNull(ts.Block); Assert.Equal(3, ts.Catches.Count); Assert.NotEqual(default, ts.Catches[0].CatchKeyword); Assert.NotNull(ts.Catches[0].Declaration); Assert.NotEqual(default, ts.Catches[0].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[0].Declaration.Type); Assert.Equal("T", ts.Catches[0].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.Identifier); Assert.Equal("e", ts.Catches[0].Declaration.Identifier.ToString()); Assert.NotEqual(default, ts.Catches[0].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[0].Block); Assert.NotEqual(default, ts.Catches[1].CatchKeyword); Assert.NotNull(ts.Catches[1].Declaration); Assert.NotEqual(default, ts.Catches[1].Declaration.OpenParenToken); Assert.NotNull(ts.Catches[1].Declaration.Type); Assert.Equal("T2", ts.Catches[1].Declaration.Type.ToString()); Assert.NotEqual(default, ts.Catches[1].Declaration.CloseParenToken); Assert.NotNull(ts.Catches[1].Block); Assert.NotEqual(default, ts.Catches[2].CatchKeyword); Assert.Null(ts.Catches[2].Declaration); Assert.NotNull(ts.Catches[2].Block); Assert.NotNull(ts.Finally); Assert.NotEqual(default, ts.Finally.FinallyKeyword); Assert.NotNull(ts.Finally.Block); } [Fact] public void TestChecked() { var text = "checked { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.CheckedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var cs = (CheckedStatementSyntax)statement; Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.CheckedKeyword, cs.Keyword.Kind()); Assert.NotNull(cs.Block); } [Fact] public void TestUnchecked() { var text = "unchecked { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UncheckedStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var cs = (CheckedStatementSyntax)statement; Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.UncheckedKeyword, cs.Keyword.Kind()); Assert.NotNull(cs.Block); } [Fact] public void TestUnsafe() { var text = "unsafe { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UnsafeStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UnsafeStatementSyntax)statement; Assert.NotEqual(default, us.UnsafeKeyword); Assert.Equal(SyntaxKind.UnsafeKeyword, us.UnsafeKeyword.Kind()); Assert.NotNull(us.Block); } [Fact] public void TestWhile() { var text = "while(a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.WhileStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ws = (WhileStatementSyntax)statement; Assert.NotEqual(default, ws.WhileKeyword); Assert.Equal(SyntaxKind.WhileKeyword, ws.WhileKeyword.Kind()); Assert.NotEqual(default, ws.OpenParenToken); Assert.NotNull(ws.Condition); Assert.NotEqual(default, ws.CloseParenToken); Assert.Equal("a", ws.Condition.ToString()); Assert.NotNull(ws.Statement); Assert.Equal(SyntaxKind.Block, ws.Statement.Kind()); } [Fact] public void TestDoWhile() { var text = "do { } while (a);"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.DoStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ds = (DoStatementSyntax)statement; Assert.NotEqual(default, ds.DoKeyword); Assert.Equal(SyntaxKind.DoKeyword, ds.DoKeyword.Kind()); Assert.NotNull(ds.Statement); Assert.NotEqual(default, ds.WhileKeyword); Assert.Equal(SyntaxKind.WhileKeyword, ds.WhileKeyword.Kind()); Assert.Equal(SyntaxKind.Block, ds.Statement.Kind()); Assert.NotEqual(default, ds.OpenParenToken); Assert.NotNull(ds.Condition); Assert.NotEqual(default, ds.CloseParenToken); Assert.Equal("a", ds.Condition.ToString()); Assert.NotEqual(default, ds.SemicolonToken); } [Fact] public void TestFor() { var text = "for(;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithVariableDeclaration() { var text = "for(T a = 0;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithVarDeclaration() { var text = "for(var a = 0;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("var", fs.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, fs.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)fs.Declaration.Type).Identifier.Kind()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithMultipleVariableDeclarations() { var text = "for(T a = 0, b = 1;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(2, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("b", fs.Declaration.Variables[1].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[1].Initializer.Value); Assert.Equal("1", fs.Declaration.Variables[1].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)] public void TestForWithRefVariableDeclaration() { var text = "for(ref T a = ref b, c = ref d;;) { }"; var statement = this.ParseStatement(text); UsingNode(statement); N(SyntaxKind.ForStatement); { N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } } N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } [Fact] public void TestForWithVariableInitializer() { var text = "for(a = 0;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(1, fs.Initializers.Count); Assert.Equal("a = 0", fs.Initializers[0].ToString()); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithMultipleVariableInitializers() { var text = "for(a = 0, b = 1;;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(2, fs.Initializers.Count); Assert.Equal("a = 0", fs.Initializers[0].ToString()); Assert.Equal("b = 1", fs.Initializers[1].ToString()); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithCondition() { var text = "for(; a;) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.NotNull(fs.Condition); Assert.Equal("a", fs.Condition.ToString()); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(0, fs.Incrementors.Count); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithIncrementor() { var text = "for(; ; a++) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(1, fs.Incrementors.Count); Assert.Equal("a++", fs.Incrementors[0].ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithMultipleIncrementors() { var text = "for(; ; a++, b++) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.Null(fs.Declaration); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.Null(fs.Condition); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(2, fs.Incrementors.Count); Assert.Equal("a++", fs.Incrementors[0].ToString()); Assert.Equal("b++", fs.Incrementors[1].ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForWithDeclarationConditionAndIncrementor() { var text = "for(T a = 0; a < 10; a++) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForStatementSyntax)statement; Assert.NotEqual(default, fs.ForKeyword); Assert.False(fs.ForKeyword.IsMissing); Assert.Equal(SyntaxKind.ForKeyword, fs.ForKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Declaration); Assert.NotNull(fs.Declaration.Type); Assert.Equal("T", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("a", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("0", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Equal(0, fs.Initializers.Count); Assert.NotEqual(default, fs.FirstSemicolonToken); Assert.NotNull(fs.Condition); Assert.Equal("a < 10", fs.Condition.ToString()); Assert.NotEqual(default, fs.SecondSemicolonToken); Assert.Equal(1, fs.Incrementors.Count); Assert.Equal("a++", fs.Incrementors[0].ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForEach() { var text = "foreach(T a in b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("T", fs.Type.ToString()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForAsForEach() { var text = "for(T a in b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.True(fs.ForEachKeyword.IsMissing); Assert.Equal(1, fs.ForEachKeyword.TrailingTrivia.Count); Assert.Equal(SyntaxKind.SkippedTokensTrivia, fs.ForEachKeyword.TrailingTrivia[0].Kind()); Assert.Equal("for", fs.ForEachKeyword.TrailingTrivia[0].ToString()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("T", fs.Type.ToString()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestForEachWithVar() { var text = "foreach(var a in b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("var", fs.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, fs.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)fs.Type).Identifier.Kind()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [Fact] public void TestIf() { var text = "if (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (IfStatementSyntax)statement; Assert.NotEqual(default, ss.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, ss.IfKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Condition); Assert.Equal("a", ss.Condition.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotNull(ss.Statement); Assert.Null(ss.Else); } [Fact] public void TestIfElse() { var text = "if (a) { } else { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (IfStatementSyntax)statement; Assert.NotEqual(default, ss.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, ss.IfKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Condition); Assert.Equal("a", ss.Condition.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotNull(ss.Statement); Assert.NotNull(ss.Else); Assert.NotEqual(default, ss.Else.ElseKeyword); Assert.Equal(SyntaxKind.ElseKeyword, ss.Else.ElseKeyword.Kind()); Assert.NotNull(ss.Else.Statement); } [Fact] public void TestIfElseIf() { var text = "if (a) { } else if (b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (IfStatementSyntax)statement; Assert.NotEqual(default, ss.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, ss.IfKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Condition); Assert.Equal("a", ss.Condition.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotNull(ss.Statement); Assert.NotNull(ss.Else); Assert.NotEqual(default, ss.Else.ElseKeyword); Assert.Equal(SyntaxKind.ElseKeyword, ss.Else.ElseKeyword.Kind()); Assert.NotNull(ss.Else.Statement); var subIf = (IfStatementSyntax)ss.Else.Statement; Assert.NotEqual(default, subIf.IfKeyword); Assert.Equal(SyntaxKind.IfKeyword, subIf.IfKeyword.Kind()); Assert.NotNull(subIf.Condition); Assert.Equal("b", subIf.Condition.ToString()); Assert.NotEqual(default, subIf.CloseParenToken); Assert.NotNull(subIf.Statement); } [Fact] public void TestLock() { var text = "lock (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LockStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ls = (LockStatementSyntax)statement; Assert.NotEqual(default, ls.LockKeyword); Assert.Equal(SyntaxKind.LockKeyword, ls.LockKeyword.Kind()); Assert.NotEqual(default, ls.OpenParenToken); Assert.NotNull(ls.Expression); Assert.Equal("a", ls.Expression.ToString()); Assert.NotEqual(default, ls.CloseParenToken); Assert.NotNull(ls.Statement); } [Fact] public void TestSwitch() { var text = "switch (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var diags = statement.ErrorsAndWarnings(); Assert.Equal(0, diags.Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(0, ss.Sections.Count); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithCase() { var text = "switch (a) { case b:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.NotEqual(default, caseLabelSyntax.ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithMultipleCases() { var text = "switch (a) { case b:; case c:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(2, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.NotEqual(default, caseLabelSyntax.ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.Equal(1, ss.Sections[1].Labels.Count); Assert.NotEqual(default, ss.Sections[1].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[1].Labels[0].Keyword.Kind()); var caseLabelSyntax2 = ss.Sections[1].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax2); Assert.NotNull(caseLabelSyntax2.Value); Assert.Equal("c", caseLabelSyntax2.Value.ToString()); Assert.NotEqual(default, caseLabelSyntax2.ColonToken); Assert.Equal(1, ss.Sections[1].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithDefaultCase() { var text = "switch (a) { default:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.DefaultKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); Assert.Equal(SyntaxKind.DefaultSwitchLabel, ss.Sections[0].Labels[0].Kind()); Assert.NotEqual(default, ss.Sections[0].Labels[0].ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithMultipleLabelsOnOneCase() { var text = "switch (a) { case b: case c:; }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(2, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.NotEqual(default, ss.Sections[0].Labels[1].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[1].Keyword.Kind()); var caseLabelSyntax2 = ss.Sections[0].Labels[1] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax2); Assert.NotNull(caseLabelSyntax2.Value); Assert.Equal("c", caseLabelSyntax2.Value.ToString()); Assert.NotEqual(default, ss.Sections[0].Labels[0].ColonToken); Assert.Equal(1, ss.Sections[0].Statements.Count); Assert.Equal(";", ss.Sections[0].Statements[0].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestSwitchWithMultipleStatementsOnOneCase() { var text = "switch (a) { case b: s1(); s2(); }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.SwitchStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var ss = (SwitchStatementSyntax)statement; Assert.NotEqual(default, ss.SwitchKeyword); Assert.Equal(SyntaxKind.SwitchKeyword, ss.SwitchKeyword.Kind()); Assert.NotEqual(default, ss.OpenParenToken); Assert.NotNull(ss.Expression); Assert.Equal("a", ss.Expression.ToString()); Assert.NotEqual(default, ss.CloseParenToken); Assert.NotEqual(default, ss.OpenBraceToken); Assert.Equal(1, ss.Sections.Count); Assert.Equal(1, ss.Sections[0].Labels.Count); Assert.NotEqual(default, ss.Sections[0].Labels[0].Keyword); Assert.Equal(SyntaxKind.CaseKeyword, ss.Sections[0].Labels[0].Keyword.Kind()); var caseLabelSyntax = ss.Sections[0].Labels[0] as CaseSwitchLabelSyntax; Assert.NotNull(caseLabelSyntax); Assert.NotNull(caseLabelSyntax.Value); Assert.Equal("b", caseLabelSyntax.Value.ToString()); Assert.Equal(2, ss.Sections[0].Statements.Count); Assert.Equal("s1();", ss.Sections[0].Statements[0].ToString()); Assert.Equal("s2();", ss.Sections[0].Statements[1].ToString()); Assert.NotEqual(default, ss.CloseBraceToken); } [Fact] public void TestUsingWithExpression() { var text = "using (a) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.Null(us.Declaration); Assert.NotNull(us.Expression); Assert.Equal("a", us.Expression.ToString()); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingWithDeclaration() { var text = "using (T a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarWithDeclaration() { var text = "using T a = b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, us.SemicolonToken); } [Fact] public void TestUsingVarWithDeclarationTree() { UsingStatement(@"using T a = b;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "T"); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingWithVarDeclaration() { var text = "using (var a = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarWithVarDeclaration() { var text = "using var a = b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); } [Fact] [WorkItem(36413, "https://github.com/dotnet/roslyn/issues/36413")] public void TestUsingVarWithInvalidDeclaration() { var text = "using public readonly var a = b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(2, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[0].Code); Assert.Equal("public", statement.Errors()[0].Arguments[0]); Assert.Equal((int)ErrorCode.ERR_BadMemberFlag, statement.Errors()[1].Code); Assert.Equal("readonly", statement.Errors()[1].Arguments[0]); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(2, us.Modifiers.Count); Assert.Equal("public", us.Modifiers[0].ToString()); Assert.Equal("readonly", us.Modifiers[1].ToString()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); } [Fact] public void TestUsingVarWithVarDeclarationTree() { UsingStatement(@"using var a = b;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestAwaitUsingVarWithDeclarationTree() { UsingStatement(@"await using T a = b;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "T"); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestAwaitUsingWithVarDeclaration() { var text = "await using var a = b;"; var statement = this.ParseStatement(text, 0, TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.AwaitKeyword); Assert.Equal(SyntaxKind.AwaitKeyword, us.AwaitKeyword.ContextualKind()); Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("var", us.Declaration.Type.ToString()); Assert.Equal(SyntaxKind.IdentifierName, us.Declaration.Type.Kind()); Assert.Equal(SyntaxKind.IdentifierToken, ((IdentifierNameSyntax)us.Declaration.Type).Identifier.Kind()); Assert.Equal(1, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); } [Fact] public void TestAwaitUsingVarWithVarDeclarationTree() { UsingStatement(@"await using var a = b;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken); } } } } N(SyntaxKind.SemicolonToken); } } [Fact, WorkItem(30565, "https://github.com/dotnet/roslyn/issues/30565")] public void AwaitUsingVarWithVarDecl_Reversed() { UsingTree(@" class C { async void M() { using await var x = null; } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "M"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "await"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "var"); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestAwaitUsingVarWithVarAndNoUsingDeclarationTree() { UsingStatement(@"await var a = b;", TestOptions.Regular8, // (1,1): error CS1073: Unexpected token 'a' // await var a = b; Diagnostic(ErrorCode.ERR_UnexpectedToken, "await var ").WithArguments("a").WithLocation(1, 1), // (1,11): error CS1002: ; expected // await var a = b; Diagnostic(ErrorCode.ERR_SemicolonExpected, "a").WithLocation(1, 11)); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AwaitExpression); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } } M(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void TestUsingWithDeclarationWithMultipleVariables() { var text = "using (T a = b, c = d) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(2, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, us.Declaration.Variables[1].Identifier); Assert.Equal("c", us.Declaration.Variables[1].Identifier.ToString()); Assert.Null(us.Declaration.Variables[1].ArgumentList); Assert.NotNull(us.Declaration.Variables[1].Initializer); Assert.NotEqual(default, us.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[1].Initializer.Value); Assert.Equal("d", us.Declaration.Variables[1].Initializer.Value.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarWithDeclarationWithMultipleVariables() { var text = "using T a = b, c = d;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.NotNull(us.Declaration.Type); Assert.Equal("T", us.Declaration.Type.ToString()); Assert.Equal(2, us.Declaration.Variables.Count); Assert.NotEqual(default, us.Declaration.Variables[0].Identifier); Assert.Equal("a", us.Declaration.Variables[0].Identifier.ToString()); Assert.Null(us.Declaration.Variables[0].ArgumentList); Assert.NotNull(us.Declaration.Variables[0].Initializer); Assert.NotEqual(default, us.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[0].Initializer.Value); Assert.Equal("b", us.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, us.Declaration.Variables[1].Identifier); Assert.Equal("c", us.Declaration.Variables[1].Identifier.ToString()); Assert.Null(us.Declaration.Variables[1].ArgumentList); Assert.NotNull(us.Declaration.Variables[1].Initializer); Assert.NotEqual(default, us.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(us.Declaration.Variables[1].Initializer.Value); Assert.Equal("d", us.Declaration.Variables[1].Initializer.Value.ToString()); } [Fact] public void TestUsingVarWithDeclarationMultipleVariablesTree() { UsingStatement(@"using T a = b, c = d;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "T"); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken, "b"); } } } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "d"); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingSpecialCase1() { var text = "using (f ? x = a : x = b) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.Null(us.Declaration); Assert.NotNull(us.Expression); Assert.Equal("f ? x = a : x = b", us.Expression.ToString()); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarSpecialCase1() { var text = "using var x = f ? a : b;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.Equal("var x = f ? a : b", us.Declaration.ToString()); } [Fact] public void TestUsingVarSpecialCase1Tree() { UsingStatement(@"using var x = f ? a : b;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.ConditionalExpression); { N(SyntaxKind.IdentifierName, "f"); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.IdentifierName, "a"); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); N(SyntaxKind.IdentifierName, "b"); { N(SyntaxKind.IdentifierToken, "b"); } } } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingSpecialCase2() { var text = "using (f ? x = a) { }"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.Equal("f ? x = a", us.Declaration.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarSpecialCase2() { var text = "using f ? x = a;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.Equal("f ? x = a", us.Declaration.ToString()); } [Fact] public void TestUsingVarSpecialCase2Tree() { UsingStatement(@"using f ? x = a;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName, "f"); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "a"); { N(SyntaxKind.IdentifierToken, "a"); } } } N(SyntaxKind.SemicolonToken); } } [Fact] public void TestUsingSpecialCase3() { var text = "using (f ? x, y) { }"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.UsingStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (UsingStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotEqual(default, us.OpenParenToken); Assert.NotNull(us.Declaration); Assert.Equal("f ? x, y", us.Declaration.ToString()); Assert.Null(us.Expression); Assert.NotEqual(default, us.CloseParenToken); Assert.NotNull(us.Statement); } [Fact] public void TestUsingVarSpecialCase3() { var text = "using f ? x, y;"; var statement = this.ParseStatement(text, options: TestOptions.Regular8); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var us = (LocalDeclarationStatementSyntax)statement; Assert.NotEqual(default, us.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, us.UsingKeyword.Kind()); Assert.NotNull(us.Declaration); Assert.Equal("f ? x, y", us.Declaration.ToString()); } [Fact] public void TestUsingVarSpecialCase3Tree() { UsingStatement("using f? x, y;", options: TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.NullableType); { N(SyntaxKind.IdentifierName, "f"); { N(SyntaxKind.IdentifierToken, "f"); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefTree() { UsingStatement("using ref int x = ref y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefReadonlyTree() { UsingStatement("using ref readonly int x = ref y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.ReadOnlyKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefVarTree() { UsingStatement("using ref var x = ref y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarRefVarIsYTree() { UsingStatement("using ref var x = y;", TestOptions.Regular8); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.RefType); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName, "y"); { N(SyntaxKind.IdentifierToken, "y"); } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestUsingVarReadonlyMultipleDeclarations() { UsingStatement("using readonly var x, y = ref z;", TestOptions.Regular8, // (1,7): error CS0106: The modifier 'readonly' is not valid for this item // using readonly var x, y = ref z; Diagnostic(ErrorCode.ERR_BadMemberFlag, "readonly").WithArguments("readonly").WithLocation(1, 7)); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.ReadOnlyKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName, "var"); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "y"); } N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.RefExpression); { N(SyntaxKind.RefKeyword); N(SyntaxKind.IdentifierName, "z"); { N(SyntaxKind.IdentifierToken, "z"); } } } } } N(SyntaxKind.SemicolonToken); } [Fact] public void TestContextualKeywordsAsLocalVariableTypes() { TestContextualKeywordAsLocalVariableType(SyntaxKind.PartialKeyword); TestContextualKeywordAsLocalVariableType(SyntaxKind.AsyncKeyword); TestContextualKeywordAsLocalVariableType(SyntaxKind.AwaitKeyword); } private void TestContextualKeywordAsLocalVariableType(SyntaxKind kind) { var keywordText = SyntaxFacts.GetText(kind); var text = keywordText + " o = null;"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.LocalDeclarationStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); var decl = (LocalDeclarationStatementSyntax)statement; Assert.Equal(keywordText, decl.Declaration.Type.ToString()); Assert.IsType<IdentifierNameSyntax>(decl.Declaration.Type); var name = (IdentifierNameSyntax)decl.Declaration.Type; Assert.Equal(kind, name.Identifier.ContextualKind()); Assert.Equal(SyntaxKind.IdentifierToken, name.Identifier.Kind()); } [Fact] public void Bug862649() { var text = @"static char[] delimiter;"; var tree = SyntaxFactory.ParseStatement(text); var toText = tree.ToFullString(); Assert.Equal(text, toText); } [Fact] public void TestForEachAfterOffset() { const string prefix = "GARBAGE"; var text = "foreach(T a in b) { }"; var statement = this.ParseStatement(prefix + text, offset: prefix.Length); Assert.NotNull(statement); Assert.Equal(SyntaxKind.ForEachStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(0, statement.Errors().Length); var fs = (ForEachStatementSyntax)statement; Assert.NotEqual(default, fs.ForEachKeyword); Assert.Equal(SyntaxKind.ForEachKeyword, fs.ForEachKeyword.Kind()); Assert.NotEqual(default, fs.OpenParenToken); Assert.NotNull(fs.Type); Assert.Equal("T", fs.Type.ToString()); Assert.NotEqual(default, fs.Identifier); Assert.Equal("a", fs.Identifier.ToString()); Assert.NotEqual(default, fs.InKeyword); Assert.False(fs.InKeyword.IsMissing); Assert.Equal(SyntaxKind.InKeyword, fs.InKeyword.Kind()); Assert.NotNull(fs.Expression); Assert.Equal("b", fs.Expression.ToString()); Assert.NotEqual(default, fs.CloseParenToken); Assert.NotNull(fs.Statement); } [WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")] [Fact] public void Bug684860_SkippedTokens() { const int n = 100000; // 100000 instances of "0+" in: // #pragma warning disable 1 0+0+0+... var builder = new System.Text.StringBuilder(); builder.Append("#pragma warning disable 1 "); for (int i = 0; i < n; i++) { builder.Append("0+"); } builder.AppendLine(); var text = builder.ToString(); var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); var walker = new TokenAndTriviaWalker(); walker.Visit(root); Assert.True(walker.Tokens > n); var tokens1 = root.DescendantTokens(descendIntoTrivia: false).ToArray(); var tokens2 = root.DescendantTokens(descendIntoTrivia: true).ToArray(); Assert.True((tokens2.Length - tokens1.Length) > n); } [WorkItem(684860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/684860")] [Fact] public void Bug684860_XmlText() { const int n = 100000; // 100000 instances of "&lt;" in: // /// <x a="&lt;&lt;&lt;..."/> // class { } var builder = new System.Text.StringBuilder(); builder.Append("/// <x a=\""); for (int i = 0; i < n; i++) { builder.Append("&lt;"); } builder.AppendLine("\"/>"); builder.AppendLine("class C { }"); var text = builder.ToString(); var tree = SyntaxFactory.ParseSyntaxTree(text, options: new CSharpParseOptions(documentationMode: DocumentationMode.Parse)); var root = tree.GetRoot(); var walker = new TokenAndTriviaWalker(); walker.Visit(root); Assert.True(walker.Tokens > n); var tokens = root.DescendantTokens(descendIntoTrivia: true).ToArray(); Assert.True(tokens.Length > n); } [Fact] public void ExceptionFilter_IfKeyword() { const string source = @" class C { void M() { try { } catch (System.Exception e) if (true) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var root = tree.GetRoot(); tree.GetDiagnostics(root).Verify( // (7,36): error CS1003: Syntax error, 'when' expected // catch (System.Exception e) if (true) { } CSharpTestBase.Diagnostic(ErrorCode.ERR_SyntaxError, "if").WithArguments("when", "if").WithLocation(7, 36)); var filterClause = root.DescendantNodes().OfType<CatchFilterClauseSyntax>().Single(); Assert.Equal(SyntaxKind.WhenKeyword, filterClause.WhenKeyword.Kind()); Assert.True(filterClause.WhenKeyword.HasStructuredTrivia); } [Fact] public void Tuple001() { var source = @" class C1 { static void Test(int arg1, (byte, byte) arg2) { (int, int)? t1 = new(int, int)?(); (int, int)? t1a = new(int, int)?((1,1)); (int, int)? t1b = new(int, int)?[1]; (int, int)? t1c = new(int, int)?[] {(1,1)}; (int, int)? t2 = default((int a, int b)); (int, int) t3 = (a: (int)arg1, b: (int)arg1); (int, int) t4 = ((int a, int b))(arg1, arg1); (int, int) t5 = ((int, int))arg2; List<(int, int)> l = new List<(int, int)>() { (a: arg1, b: arg1), (arg1, arg1) }; Func<(int a, int b), (int a, int b)> f = ((int a, int b) t) => t; var x = from i in ""qq"" from j in ""ee"" select (i, j); foreach ((int, int) e in new (int, int)[10]) { } } } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); tree.GetDiagnostics().Verify(); } [Fact] [WorkItem(684860, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/266237")] public void DevDiv266237() { var source = @" class Program { static void Go() { using (var p = new P { } protected override void M() { } } "; var tree = SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Regular); tree.GetDiagnostics(tree.GetRoot()).Verify( // (9,10): error CS1026: ) expected // } CSharpTestBase.Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(9, 10), // (9,10): error CS1002: ; expected // } CSharpTestBase.Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(9, 10), // (9,10): error CS1513: } expected // } CSharpTestBase.Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(9, 10)); } [WorkItem(6676, "https://github.com/dotnet/roslyn/issues/6676")] [Fact] public void TestRunEmbeddedStatementNotFollowedBySemicolon() { var text = @"if (true) System.Console.WriteLine(true)"; var statement = this.ParseStatement(text); Assert.NotNull(statement); Assert.Equal(SyntaxKind.IfStatement, statement.Kind()); Assert.Equal(text, statement.ToString()); Assert.Equal(1, statement.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, statement.Errors()[0].Code); } [WorkItem(266237, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?_a=edit&id=266237")] [Fact] public void NullExceptionInLabeledStatement() { UsingStatement(@"{ label: public", // (1,1): error CS1073: Unexpected token 'public' // { label: public Diagnostic(ErrorCode.ERR_UnexpectedToken, "{ label: ").WithArguments("public").WithLocation(1, 1), // (1,10): error CS1002: ; expected // { label: public Diagnostic(ErrorCode.ERR_SemicolonExpected, "public").WithLocation(1, 10), // (1,10): error CS1513: } expected // { label: public Diagnostic(ErrorCode.ERR_RbraceExpected, "public").WithLocation(1, 10) ); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LabeledStatement); { N(SyntaxKind.IdentifierToken, "label"); N(SyntaxKind.ColonToken); M(SyntaxKind.EmptyStatement); { M(SyntaxKind.SemicolonToken); } } M(SyntaxKind.CloseBraceToken); } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseElseWithoutPrecedingIfStatement() { UsingStatement("else {}", // (1,1): error CS8641: 'else' cannot start a statement. // else {} Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 1), // (1,1): error CS1003: Syntax error, '(' expected // else {} Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 1), // (1,1): error CS1525: Invalid expression term 'else' // else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 1), // (1,1): error CS1026: ) expected // else {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 1), // (1,1): error CS1525: Invalid expression term 'else' // else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 1), // (1,1): error CS1002: ; expected // else {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 1) ); N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseElseAndElseWithoutPrecedingIfStatement() { UsingStatement("{ else {} else {} }", // (1,3): error CS8641: 'else' cannot start a statement. // { else {} else {} } Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 3), // (1,3): error CS1003: Syntax error, '(' expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 3), // (1,3): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 3), // (1,3): error CS1026: ) expected // { else {} else {} } Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 3), // (1,3): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 3), // (1,3): error CS1002: ; expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 3), // (1,11): error CS8641: 'else' cannot start a statement. // { else {} else {} } Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 11), // (1,11): error CS1003: Syntax error, '(' expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 11), // (1,11): error CS1026: ) expected // { else {} else {} } Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 11), // (1,11): error CS1525: Invalid expression term 'else' // { else {} else {} } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 11), // (1,11): error CS1002: ; expected // { else {} else {} } Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 11) ); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseSubsequentElseWithoutPrecedingIfStatement() { UsingStatement("{ if (a) { } else { } else { } }", // (1,23): error CS8641: 'else' cannot start a statement. // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 23), // (1,23): error CS1003: Syntax error, '(' expected // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 23), // (1,23): error CS1525: Invalid expression term 'else' // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 23), // (1,23): error CS1026: ) expected // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 23), // (1,23): error CS1525: Invalid expression term 'else' // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 23), // (1,23): error CS1002: ; expected // { if (a) { } else { } else { } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 23) ); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } EOF(); } [WorkItem(27866, "https://github.com/dotnet/roslyn/issues/27866")] [Fact] public void ParseElseKeywordPlacedAsIfEmbeddedStatement() { UsingStatement("if (a) else {}", // (1,8): error CS8641: 'else' cannot start a statement. // if (a) else {} Diagnostic(ErrorCode.ERR_ElseCannotStartStatement, "else").WithLocation(1, 8), // (1,8): error CS1003: Syntax error, '(' expected // if (a) else {} Diagnostic(ErrorCode.ERR_SyntaxError, "else").WithArguments("(", "else").WithLocation(1, 8), // (1,8): error CS1525: Invalid expression term 'else' // if (a) else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 8), // (1,8): error CS1026: ) expected // if (a) else {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "else").WithLocation(1, 8), // (1,8): error CS1525: Invalid expression term 'else' // if (a) else {} Diagnostic(ErrorCode.ERR_InvalidExprTerm, "else").WithArguments("else").WithLocation(1, 8), // (1,8): error CS1002: ; expected // if (a) else {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "else").WithLocation(1, 8) ); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IfStatement); { M(SyntaxKind.IfKeyword); M(SyntaxKind.OpenParenToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.CloseParenToken); M(SyntaxKind.ExpressionStatement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ElseClause); { N(SyntaxKind.ElseKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } } EOF(); } [Fact] public void ParseSwitch01() { UsingStatement("switch 1+2 {}", // (1,8): error CS8415: Parentheses are required around the switch governing expression. // switch 1+2 {} Diagnostic(ErrorCode.ERR_SwitchGoverningExpressionRequiresParens, "1+2").WithLocation(1, 8) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); M(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.PlusToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } } M(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseSwitch02() { UsingStatement("switch (a: 0) {}", // (1,13): error CS8124: Tuple must contain at least two elements. // switch (a: 0) {} Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(1, 13) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } M(SyntaxKind.CommaToken); M(SyntaxKind.Argument); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseSwitch03() { UsingStatement("switch (a: 0, b: 4) {}"); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.TupleExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.NameColon); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.ColonToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "4"); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseSwitch04() { UsingStatement("switch (1) + (2) {}", // (1,8): error CS8415: Parentheses are required around the switch governing expression. // switch (1) + (2) {} Diagnostic(ErrorCode.ERR_SwitchGoverningExpressionRequiresParens, "(1) + (2)").WithLocation(1, 8) ); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); M(SyntaxKind.OpenParenToken); N(SyntaxKind.AddExpression); { N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.PlusToken); N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "2"); } N(SyntaxKind.CloseParenToken); } } M(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } EOF(); } [Fact] public void ParseCreateNullableTuple_01() { UsingStatement("_ = new (int, int)? {};"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ObjectInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParseCreateNullableTuple_02() { UsingStatement("_ = new (int, int) ? (x) : (y);", // (1,1): error CS1073: Unexpected token ':' // _ = new (int, int) ? (x) : (y); Diagnostic(ErrorCode.ERR_UnexpectedToken, "_ = new (int, int) ? (x) ").WithArguments(":").WithLocation(1, 1), // (1,26): error CS1002: ; expected // _ = new (int, int) ? (x) : (y); Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(1, 26) ); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } } N(SyntaxKind.CloseParenToken); } } } M(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParsePointerToArray() { UsingStatement("int []* p;", // (1,7): error CS1001: Identifier expected // int []* p; Diagnostic(ErrorCode.ERR_IdentifierExpected, "*").WithLocation(1, 7), // (1,7): error CS1003: Syntax error, ',' expected // int []* p; Diagnostic(ErrorCode.ERR_SyntaxError, "*").WithArguments(",", "*").WithLocation(1, 7) ); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.SemicolonToken); } EOF(); } [Fact] public void ParseNewNullableWithInitializer() { UsingStatement("_ = new int? {};"); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "_"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.NullableType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.QuestionToken); } N(SyntaxKind.ObjectInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.SemicolonToken); } EOF(); } private sealed class TokenAndTriviaWalker : CSharpSyntaxWalker { public int Tokens; public TokenAndTriviaWalker() : base(SyntaxWalkerDepth.StructuredTrivia) { } public override void VisitToken(SyntaxToken token) { Tokens++; base.VisitToken(token); } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/WorkspaceServices/SemanticModelReuse/ISemanticModelReuseWorkspaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SemanticModelReuse { /// <summary> /// a service that provides a semantic model that will re-use last known compilation if /// semantic version hasn't changed. /// </summary> internal interface ISemanticModelReuseWorkspaceService : IWorkspaceService { /// <summary> /// Don't call this directly. use <see cref="DocumentExtensions.ReuseExistingSpeculativeModelAsync(Document, SyntaxNode, CancellationToken)"/> (or an overload). /// </summary> ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.SemanticModelReuse { /// <summary> /// a service that provides a semantic model that will re-use last known compilation if /// semantic version hasn't changed. /// </summary> internal interface ISemanticModelReuseWorkspaceService : IWorkspaceService { /// <summary> /// Don't call this directly. use <see cref="DocumentExtensions.ReuseExistingSpeculativeModelAsync(Document, SyntaxNode, CancellationToken)"/> (or an overload). /// </summary> ValueTask<SemanticModel> ReuseExistingSpeculativeModelAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/IntroduceVariable/IntroduceLocalForExpressionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.IntroduceVariable; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntroduceVariable { public partial class IntroduceLocalForExpressionTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpIntroduceLocalForExpressionCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_NoSemicolon() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime()[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_NoSemicolon_BlankLineAfter() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime()[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_NoSemicolon_SelectExpression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { [|new DateTime()|] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task IntroduceLocal_Inside_Expression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new TimeSpan() +[||] new TimeSpan(); } }", @" using System; class C { void M() { TimeSpan {|Rename:timeSpan|} = new TimeSpan() + new TimeSpan(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime();[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon_BlankLineAfter() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime();[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon_SelectExpression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { [|new DateTime()|]; } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon_SelectStatement() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { [|new DateTime();|] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task MissingOnAssignmentExpressionStatement() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { int a = 42; [||]a = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Space() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime(); [||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_LeadingTrivia() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { // Comment new DateTime();[||] } }", @" using System; class C { void M() { // Comment DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_PreferVar() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime();[||] } }", @" using System; class C { void M() { var {|Rename:dateTime|} = new DateTime(); } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSuggestionEnforcement }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement }, }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task MissingOnVoidCall() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { Console.WriteLine();[||] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task MissingOnDeclaration() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { var v = new DateTime()[||] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_ArithmeticExpression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { 1 + 1[||] } }", @" using System; class C { void M() { int {|Rename:v|} = 1 + 1; } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.IntroduceVariable; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.IntroduceVariable { public partial class IntroduceLocalForExpressionTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpIntroduceLocalForExpressionCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_NoSemicolon() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime()[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_NoSemicolon_BlankLineAfter() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime()[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_NoSemicolon_SelectExpression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { [|new DateTime()|] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] public async Task IntroduceLocal_Inside_Expression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new TimeSpan() +[||] new TimeSpan(); } }", @" using System; class C { void M() { TimeSpan {|Rename:timeSpan|} = new TimeSpan() + new TimeSpan(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime();[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon_BlankLineAfter() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime();[||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon_SelectExpression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { [|new DateTime()|]; } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Semicolon_SelectStatement() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { [|new DateTime();|] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task MissingOnAssignmentExpressionStatement() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { int a = 42; [||]a = 42; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_Space() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime(); [||] } }", @" using System; class C { void M() { DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_LeadingTrivia() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { // Comment new DateTime();[||] } }", @" using System; class C { void M() { // Comment DateTime {|Rename:dateTime|} = new DateTime(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_PreferVar() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { new DateTime();[||] } }", @" using System; class C { void M() { var {|Rename:dateTime|} = new DateTime(); } }", options: new OptionsCollection(GetLanguage()) { { CSharpCodeStyleOptions.VarElsewhere, CodeStyleOptions2.TrueWithSuggestionEnforcement }, { CSharpCodeStyleOptions.VarWhenTypeIsApparent, CodeStyleOptions2.TrueWithSuggestionEnforcement }, }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task MissingOnVoidCall() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { Console.WriteLine();[||] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task MissingOnDeclaration() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { var v = new DateTime()[||] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceLocalForExpression)] public async Task IntroduceLocal_ArithmeticExpression() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { 1 + 1[||] } }", @" using System; class C { void M() { int {|Rename:v|} = 1 + 1; } }"); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Analyzers/CSharp/Tests/NewLines/ConstructorInitializerPlacement/ConstructorInitializerPlacementTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.NewLines.ConstructorInitializerPlacement; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConstructorInitializerPlacement { using Verify = CSharpCodeFixVerifier< ConstructorInitializerPlacementDiagnosticAnalyzer, ConstructorInitializerPlacementCodeFixProvider>; public class ConstructorInitializerPlacementTests { [Fact] public async Task TestNotWithOptionOff() { var code = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.TrueWithSilentEnforcement } } }.RunAsync(); } [Fact] public async Task TestSimpleCase() { var code = @" class C { public C() [|:|] base() { } }"; var fixedCode = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestNotOnSameLine1() { var code = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestNotOnSameLine2() { var code = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestNotWithColonTrailingComment() { var code = @" class C { public C() : //comment base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithCloseParenTrailingComment1() { var code = @" class C { public C() /*comment*/ [|:|] base() { } }"; var fixedCode = @" class C { public C() /*comment*/ : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithColonLeadingComment1() { var code = @" class C { public C() // comment [|:|] base() { } }"; var fixedCode = @" class C { public C() // comment : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithLeadingComment() { var code = @" class C { public C() [|:|] // comment base() { } }"; var fixedCode = @" class C { public C() // comment : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithLeadingDirective() { var code = @" class C { public C() : #if true base() { } #endif }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.NewLines.ConstructorInitializerPlacement; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.NewLines.ConstructorInitializerPlacement { using Verify = CSharpCodeFixVerifier< ConstructorInitializerPlacementDiagnosticAnalyzer, ConstructorInitializerPlacementCodeFixProvider>; public class ConstructorInitializerPlacementTests { [Fact] public async Task TestNotWithOptionOff() { var code = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.TrueWithSilentEnforcement } } }.RunAsync(); } [Fact] public async Task TestSimpleCase() { var code = @" class C { public C() [|:|] base() { } }"; var fixedCode = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestNotOnSameLine1() { var code = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestNotOnSameLine2() { var code = @" class C { public C() : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestNotWithColonTrailingComment() { var code = @" class C { public C() : //comment base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithCloseParenTrailingComment1() { var code = @" class C { public C() /*comment*/ [|:|] base() { } }"; var fixedCode = @" class C { public C() /*comment*/ : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithColonLeadingComment1() { var code = @" class C { public C() // comment [|:|] base() { } }"; var fixedCode = @" class C { public C() // comment : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithLeadingComment() { var code = @" class C { public C() [|:|] // comment base() { } }"; var fixedCode = @" class C { public C() // comment : base() { } }"; await new Verify.Test() { TestCode = code, FixedCode = fixedCode, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } [Fact] public async Task TestWithLeadingDirective() { var code = @" class C { public C() : #if true base() { } #endif }"; await new Verify.Test() { TestCode = code, FixedCode = code, Options = { { CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CodeStyleOptions2.FalseWithSuggestionEnforcement } } }.RunAsync(); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/VisualBasic/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ConstructorDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of SubNewStatementSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, constructorDeclaration As SubNewStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(constructorDeclaration, spans, optionProvider) Dim block = TryCast(constructorDeclaration.Parent, ConstructorBlockSyntax) If Not block?.EndBlockStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=constructorDeclaration, autoCollapse:=True, type:=BlockTypes.Member, isCollapsible:=True)) End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ConstructorDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of SubNewStatementSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, constructorDeclaration As SubNewStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) CollectCommentsRegions(constructorDeclaration, spans, optionProvider) Dim block = TryCast(constructorDeclaration.Parent, ConstructorBlockSyntax) If Not block?.EndBlockStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=constructorDeclaration, autoCollapse:=True, type:=BlockTypes.Member, isCollapsible:=True)) End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/LockKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class LockKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public LockKeywordRecommender() : base(SyntaxKind.LockKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class LockKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public LockKeywordRecommender() : base(SyntaxKind.LockKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedDelegateSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Dynamic call-site delegate, for call-sites that do not /// match System.Action or System.Func signatures. /// </summary> internal sealed class SynthesizedDelegateSymbol : SynthesizedContainer { private readonly NamespaceOrTypeSymbol _containingSymbol; private readonly MethodSymbol _constructor; private readonly MethodSymbol _invoke; public SynthesizedDelegateSymbol( NamespaceOrTypeSymbol containingSymbol, string name, TypeSymbol objectType, TypeSymbol intPtrType, TypeSymbol? voidReturnTypeOpt, int parameterCount, RefKindVector refKinds) : base(name, parameterCount, returnsVoid: voidReturnTypeOpt is not null) { Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (voidReturnTypeOpt is { } ? 0 : 1)); _containingSymbol = containingSymbol; _constructor = new DelegateConstructor(this, objectType, intPtrType); _invoke = new InvokeMethod(this, refKinds, voidReturnTypeOpt); } public override Symbol ContainingSymbol { get { return _containingSymbol; } } public override TypeKind TypeKind { get { return TypeKind.Delegate; } } internal override MethodSymbol Constructor { get { return _constructor; } } public override IEnumerable<string> MemberNames { get { return new[] { _constructor.Name, _invoke.Name }; } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray.Create<Symbol>(_constructor, _invoke); } public override ImmutableArray<Symbol> GetMembers(string name) { return (name == _constructor.Name) ? ImmutableArray.Create<Symbol>(_constructor) : (name == _invoke.Name) ? ImmutableArray.Create<Symbol>(_invoke) : ImmutableArray<Symbol>.Empty; } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } public override bool IsSealed { get { return true; } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(SpecialType.System_MulticastDelegate); public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; private sealed class DelegateConstructor : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; public DelegateConstructor(NamedTypeSymbol containingType, TypeSymbol objectType, TypeSymbol intPtrType) : base(containingType) { _parameters = ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(objectType), 0, RefKind.None, "object"), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intPtrType), 1, RefKind.None, "method")); } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } } private sealed class InvokeMethod : SynthesizedInstanceMethodSymbol { private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly TypeSymbol _containingType; private readonly TypeSymbol _returnType; private readonly RefKind _returnRefKind; internal InvokeMethod(SynthesizedDelegateSymbol containingType, RefKindVector refKinds, TypeSymbol? voidReturnTypeOpt) { var typeParams = containingType.TypeParameters; _containingType = containingType; int parameterCount = typeParams.Length - (voidReturnTypeOpt is null ? 1 : 0); var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(parameterCount); for (int i = 0; i < parameterCount; i++) { var parameterRefKind = refKinds.IsNull ? RefKind.None : refKinds[i]; parameters.Add(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(typeParams[i]), i, parameterRefKind)); } _parameters = parameters.ToImmutableAndFree(); // if we are given Void type the method returns Void, otherwise its return type is the last type parameter of the delegate: _returnType = voidReturnTypeOpt ?? typeParams[parameterCount]; _returnRefKind = (refKinds.IsNull || voidReturnTypeOpt is { }) ? RefKind.None : refKinds[parameterCount]; } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.DelegateInvoke; } } public override int Arity { get { return 0; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData? GetDllImportData() { return null; } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return false; } } public override bool ReturnsVoid { get { return _returnType.IsVoidType(); } } public override bool IsAsync { get { return false; } } public override RefKind RefKind { get { return _returnRefKind; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(_returnType); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol? AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override Microsoft.Cci.CallingConvention CallingConvention { get { return Microsoft.Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override Accessibility DeclaredAccessibility { get { // Invoke method of a delegate used in a dynamic call-site must be public // since the DLR looks only for public Invoke methods: return Accessibility.Public; } } public override bool IsStatic { get { return false; } } public override bool IsVirtual { get { return true; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Dynamic call-site delegate, for call-sites that do not /// match System.Action or System.Func signatures. /// </summary> internal sealed class SynthesizedDelegateSymbol : SynthesizedContainer { private readonly NamespaceOrTypeSymbol _containingSymbol; private readonly MethodSymbol _constructor; private readonly MethodSymbol _invoke; public SynthesizedDelegateSymbol( NamespaceOrTypeSymbol containingSymbol, string name, TypeSymbol objectType, TypeSymbol intPtrType, TypeSymbol? voidReturnTypeOpt, int parameterCount, RefKindVector refKinds) : base(name, parameterCount, returnsVoid: voidReturnTypeOpt is not null) { Debug.Assert(refKinds.IsNull || parameterCount == refKinds.Capacity - (voidReturnTypeOpt is { } ? 0 : 1)); _containingSymbol = containingSymbol; _constructor = new DelegateConstructor(this, objectType, intPtrType); _invoke = new InvokeMethod(this, refKinds, voidReturnTypeOpt); } public override Symbol ContainingSymbol { get { return _containingSymbol; } } public override TypeKind TypeKind { get { return TypeKind.Delegate; } } internal override MethodSymbol Constructor { get { return _constructor; } } public override IEnumerable<string> MemberNames { get { return new[] { _constructor.Name, _invoke.Name }; } } public override ImmutableArray<Symbol> GetMembers() { return ImmutableArray.Create<Symbol>(_constructor, _invoke); } public override ImmutableArray<Symbol> GetMembers(string name) { return (name == _constructor.Name) ? ImmutableArray.Create<Symbol>(_constructor) : (name == _invoke.Name) ? ImmutableArray.Create<Symbol>(_invoke) : ImmutableArray<Symbol>.Empty; } public override Accessibility DeclaredAccessibility { get { return Accessibility.Internal; } } public override bool IsSealed { get { return true; } } internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(SpecialType.System_MulticastDelegate); public sealed override bool AreLocalsZeroed { get { throw ExceptionUtilities.Unreachable; } } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; private sealed class DelegateConstructor : SynthesizedInstanceConstructor { private readonly ImmutableArray<ParameterSymbol> _parameters; public DelegateConstructor(NamedTypeSymbol containingType, TypeSymbol objectType, TypeSymbol intPtrType) : base(containingType) { _parameters = ImmutableArray.Create<ParameterSymbol>( SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(objectType), 0, RefKind.None, "object"), SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(intPtrType), 1, RefKind.None, "method")); } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } } private sealed class InvokeMethod : SynthesizedInstanceMethodSymbol { private readonly ImmutableArray<ParameterSymbol> _parameters; private readonly TypeSymbol _containingType; private readonly TypeSymbol _returnType; private readonly RefKind _returnRefKind; internal InvokeMethod(SynthesizedDelegateSymbol containingType, RefKindVector refKinds, TypeSymbol? voidReturnTypeOpt) { var typeParams = containingType.TypeParameters; _containingType = containingType; int parameterCount = typeParams.Length - (voidReturnTypeOpt is null ? 1 : 0); var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(parameterCount); for (int i = 0; i < parameterCount; i++) { var parameterRefKind = refKinds.IsNull ? RefKind.None : refKinds[i]; parameters.Add(SynthesizedParameterSymbol.Create(this, TypeWithAnnotations.Create(typeParams[i]), i, parameterRefKind)); } _parameters = parameters.ToImmutableAndFree(); // if we are given Void type the method returns Void, otherwise its return type is the last type parameter of the delegate: _returnType = voidReturnTypeOpt ?? typeParams[parameterCount]; _returnRefKind = (refKinds.IsNull || voidReturnTypeOpt is { }) ? RefKind.None : refKinds[parameterCount]; } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return true; } internal override bool IsMetadataFinal { get { return false; } } public override MethodKind MethodKind { get { return MethodKind.DelegateInvoke; } } public override int Arity { get { return 0; } } public override bool IsExtensionMethod { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal override bool HasDeclarativeSecurity { get { return false; } } public override DllImportData? GetDllImportData() { return null; } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation { get { return null; } } internal override bool RequiresSecurityObject { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsVararg { get { return false; } } public override bool ReturnsVoid { get { return _returnType.IsVoidType(); } } public override bool IsAsync { get { return false; } } public override RefKind RefKind { get { return _returnRefKind; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { return TypeWithAnnotations.Create(_returnType); } } public override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => ImmutableHashSet<string>.Empty; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations { get { return ImmutableArray<TypeWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } public override Symbol? AssociatedSymbol { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } internal override Microsoft.Cci.CallingConvention CallingConvention { get { return Microsoft.Cci.CallingConvention.HasThis; } } internal override bool GenerateDebugInfo { get { return false; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override Accessibility DeclaredAccessibility { get { // Invoke method of a delegate used in a dynamic call-site must be public // since the DLR looks only for public Invoke methods: return Accessibility.Public; } } public override bool IsStatic { get { return false; } } public override bool IsVirtual { get { return true; } } public override bool IsOverride { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsExtern { get { return false; } } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/CSharp/Portable/UpgradeProject/CSharpUpgradeProjectCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UpgradeProject; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UpgradeProject { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UpgradeProject), Shared] internal class CSharpUpgradeProjectCodeFixProvider : AbstractUpgradeProjectCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUpgradeProjectCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( new[] { "CS8022", // error CS8022: Feature is not available in C# 1. Please use language version X or greater. "CS8023", // error CS8023: Feature is not available in C# 2. Please use language version X or greater. "CS8024", // error CS8024: Feature is not available in C# 3. Please use language version X or greater. "CS8025", // error CS8025: Feature is not available in C# 4. Please use language version X or greater. "CS8026", // error CS8026: Feature is not available in C# 5. Please use language version X or greater. "CS8059", // error CS8059: Feature is not available in C# 6. Please use language version X or greater. "CS8107", // error CS8059: Feature is not available in C# 7.0. Please use language version X or greater. "CS8302", // error CS8302: Feature is not available in C# 7.1. Please use language version X or greater. "CS8306", // error CS8306: ... Please use language version 7.1 or greater to access a un-named element by its inferred name. "CS8314", // error CS8314: An expression of type '{0}' cannot be handled by a pattern of type '{1}' in C# {2}. Please use language version {3} or greater. "CS8320", // error CS8320: Feature is not available in C# 7.2. Please use language version X or greater. "CS1738", // error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. "CS8370", // error CS8370: Feature is not available in C# 7.3. Please use language version X or greater. "CS8371", // warning CS8371: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. "CS8400", // error CS8400: Feature is not available in C# 8.0. Please use language version X or greater. "CS8401", // error CS8401: To use '@$' instead of '$@" for a verbatim interpolated string, please use language version 8.0 or greater. "CS8511", // error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version 'preview' or greater to match an open type with a constant pattern. "CS8627", // error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '{0}' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. "CS8652", // error CS8652: The feature '' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. "CS8773", // error CS8773: Feature is not available in C# 9.0. Please use language version X or greater. "CS8703", // error CS8703: The modifier '{0}' is not valid for this item in C# {1}. Please use language version '{2}' or greater. "CS8706", // error CS8706: '{0}' cannot implement interface member '{1}' in type '{2}' because feature '{3}' is not available in C# {4}. Please use language version '{5}' or greater. "CS8904", // error CS8904: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M1(T1)' unless language version 'preview' or greater is used. 'T1' is covariant. "CS8912", // error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# {0}. Please use language version '{1}' or greater. "CS8704", // error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version 'preview' or greater. "CS8957", // error CS8957: Conditional expression is not valid in language version '8.0' because a common type was not found between 'int' and '<null>'. To use a target-typed conversion, upgrade to language version '9.0' or greater. }); public override string UpgradeThisProjectResource => CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0; public override string UpgradeAllProjectsResource => CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0; public override string SuggestedVersion(ImmutableArray<Diagnostic> diagnostics) => RequiredVersion(diagnostics).ToDisplayString(); private static LanguageVersion RequiredVersion(ImmutableArray<Diagnostic> diagnostics) { LanguageVersion max = 0; foreach (var diagnostic in diagnostics) { if (diagnostic.Properties.TryGetValue(DiagnosticPropertyConstants.RequiredLanguageVersion, out var requiredVersion) && LanguageVersionFacts.TryParse(requiredVersion, out var required)) { max = max > required ? max : required; } else if (diagnostic.Id == "CS8652") { max = LanguageVersion.Preview; break; } } return max; } public override Solution UpgradeProject(Project project, string newVersion) { if (IsUpgrade(project, newVersion)) { Contract.ThrowIfFalse(LanguageVersionFacts.TryParse(newVersion, out var parsedNewVersion)); var parseOptions = (CSharpParseOptions)project.ParseOptions!; return project.Solution.WithProjectParseOptions(project.Id, parseOptions.WithLanguageVersion(parsedNewVersion)); } else { // when fixing all projects in a solution, don't downgrade those with newer language versions return project.Solution; } } public override bool IsUpgrade(Project project, string newVersion) { Contract.ThrowIfFalse(LanguageVersionFacts.TryParse(newVersion, out var parsedNewVersion)); var parseOptions = (CSharpParseOptions)project.ParseOptions!; var mappedVersion = parsedNewVersion.MapSpecifiedToEffectiveVersion(); var workspace = project.Solution.Workspace; // treat equivalent versions (one generic and one specific) to be a valid upgrade return mappedVersion >= parseOptions.LanguageVersion && parseOptions.SpecifiedLanguageVersion.ToDisplayString() != newVersion && workspace.CanApplyParseOptionChange(parseOptions, parseOptions.WithLanguageVersion(parsedNewVersion), project); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UpgradeProject; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UpgradeProject { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UpgradeProject), Shared] internal class CSharpUpgradeProjectCodeFixProvider : AbstractUpgradeProjectCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUpgradeProjectCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create( new[] { "CS8022", // error CS8022: Feature is not available in C# 1. Please use language version X or greater. "CS8023", // error CS8023: Feature is not available in C# 2. Please use language version X or greater. "CS8024", // error CS8024: Feature is not available in C# 3. Please use language version X or greater. "CS8025", // error CS8025: Feature is not available in C# 4. Please use language version X or greater. "CS8026", // error CS8026: Feature is not available in C# 5. Please use language version X or greater. "CS8059", // error CS8059: Feature is not available in C# 6. Please use language version X or greater. "CS8107", // error CS8059: Feature is not available in C# 7.0. Please use language version X or greater. "CS8302", // error CS8302: Feature is not available in C# 7.1. Please use language version X or greater. "CS8306", // error CS8306: ... Please use language version 7.1 or greater to access a un-named element by its inferred name. "CS8314", // error CS8314: An expression of type '{0}' cannot be handled by a pattern of type '{1}' in C# {2}. Please use language version {3} or greater. "CS8320", // error CS8320: Feature is not available in C# 7.2. Please use language version X or greater. "CS1738", // error CS1738: Named argument specifications must appear after all fixed arguments have been specified. Please use language version 7.2 or greater to allow non-trailing named arguments. "CS8370", // error CS8370: Feature is not available in C# 7.3. Please use language version X or greater. "CS8371", // warning CS8371: Field-targeted attributes on auto-properties are not supported in language version 7.2. Please use language version 7.3 or greater. "CS8400", // error CS8400: Feature is not available in C# 8.0. Please use language version X or greater. "CS8401", // error CS8401: To use '@$' instead of '$@" for a verbatim interpolated string, please use language version 8.0 or greater. "CS8511", // error CS8511: An expression of type 'T' cannot be handled by a pattern of type '<null>'. Please use language version 'preview' or greater to match an open type with a constant pattern. "CS8627", // error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '{0}' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. "CS8652", // error CS8652: The feature '' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. "CS8773", // error CS8773: Feature is not available in C# 9.0. Please use language version X or greater. "CS8703", // error CS8703: The modifier '{0}' is not valid for this item in C# {1}. Please use language version '{2}' or greater. "CS8706", // error CS8706: '{0}' cannot implement interface member '{1}' in type '{2}' because feature '{3}' is not available in C# {4}. Please use language version '{5}' or greater. "CS8904", // error CS8904: Invalid variance: The type parameter 'T1' must be contravariantly valid on 'I2<T1, T2>.M1(T1)' unless language version 'preview' or greater is used. 'T1' is covariant. "CS8912", // error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# {0}. Please use language version '{1}' or greater. "CS8704", // error CS8704: 'Test1' does not implement interface member 'I1.M1()'. 'Test1.M1()' cannot implicitly implement a non-public member in C# 9.0. Please use language version 'preview' or greater. "CS8957", // error CS8957: Conditional expression is not valid in language version '8.0' because a common type was not found between 'int' and '<null>'. To use a target-typed conversion, upgrade to language version '9.0' or greater. }); public override string UpgradeThisProjectResource => CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0; public override string UpgradeAllProjectsResource => CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0; public override string SuggestedVersion(ImmutableArray<Diagnostic> diagnostics) => RequiredVersion(diagnostics).ToDisplayString(); private static LanguageVersion RequiredVersion(ImmutableArray<Diagnostic> diagnostics) { LanguageVersion max = 0; foreach (var diagnostic in diagnostics) { if (diagnostic.Properties.TryGetValue(DiagnosticPropertyConstants.RequiredLanguageVersion, out var requiredVersion) && LanguageVersionFacts.TryParse(requiredVersion, out var required)) { max = max > required ? max : required; } else if (diagnostic.Id == "CS8652") { max = LanguageVersion.Preview; break; } } return max; } public override Solution UpgradeProject(Project project, string newVersion) { if (IsUpgrade(project, newVersion)) { Contract.ThrowIfFalse(LanguageVersionFacts.TryParse(newVersion, out var parsedNewVersion)); var parseOptions = (CSharpParseOptions)project.ParseOptions!; return project.Solution.WithProjectParseOptions(project.Id, parseOptions.WithLanguageVersion(parsedNewVersion)); } else { // when fixing all projects in a solution, don't downgrade those with newer language versions return project.Solution; } } public override bool IsUpgrade(Project project, string newVersion) { Contract.ThrowIfFalse(LanguageVersionFacts.TryParse(newVersion, out var parsedNewVersion)); var parseOptions = (CSharpParseOptions)project.ParseOptions!; var mappedVersion = parsedNewVersion.MapSpecifiedToEffectiveVersion(); var workspace = project.Solution.Workspace; // treat equivalent versions (one generic and one specific) to be a valid upgrade return mappedVersion >= parseOptions.LanguageVersion && parseOptions.SpecifiedLanguageVersion.ToDisplayString() != newVersion && workspace.CanApplyParseOptionChange(parseOptions, parseOptions.WithLanguageVersion(parsedNewVersion), project); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/OperatorDeclarationStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class OperatorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<OperatorDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new OperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public static bool operator $$==(Goo a, Goo b); }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestOperator3() { const string code = @" class C { $${|#0:public static int operator +(int i){|textspan: { }|#0} |} public static int operator -(int i) { } }"; await VerifyBlockSpansAsync(code, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class OperatorDeclarationStructureTests : AbstractCSharpSyntaxNodeStructureTests<OperatorDeclarationSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new OperatorDeclarationStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task NoCommentsOrAttributes() { const string code = @" class Goo { public static bool operator $$==(Goo a, Goo b); }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithAttributes() { const string code = @" class Goo { {|hint:{|textspan:[Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAndAttributes() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task WithCommentsAttributesAndModifiers() { const string code = @" class Goo { {|hint:{|textspan:// Summary: // This is a summary. [Blah] |}public static bool operator $$==(Goo a, Goo b);|} }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestOperator3() { const string code = @" class C { $${|#0:public static int operator +(int i){|textspan: { }|#0} |} public static int operator -(int i) { } }"; await VerifyBlockSpansAsync(code, Region("textspan", "#0", CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Def/Implementation/CommonControls/NewTypeDestinationSelectionViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class NewTypeDestinationSelectionViewModel : AbstractNotifyPropertyChanged { public static NewTypeDestinationSelectionViewModel Default = new( string.Empty, LanguageNames.CSharp, string.Empty, string.Empty, ImmutableArray<string>.Empty, null ); private readonly string _fileExtension; private readonly string _defaultNamespace; private readonly string _generatedNameTypeParameterSuffix; private readonly ImmutableArray<string> _conflictingNames; private readonly string _defaultName; private readonly ISyntaxFactsService? _syntaxFactsService; private readonly string _languageName; public NewTypeDestinationSelectionViewModel( string defaultName, string languageName, string defaultNamespace, string generatedNameTypeParameterSuffix, ImmutableArray<string> conflictingNames, ISyntaxFactsService? syntaxFactsService) { _defaultName = defaultName; _fileExtension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; _languageName = languageName; _generatedNameTypeParameterSuffix = generatedNameTypeParameterSuffix; _conflictingNames = conflictingNames; _defaultNamespace = defaultNamespace; _typeName = _defaultName; _syntaxFactsService = syntaxFactsService; _fileName = $"{defaultName}{_fileExtension}"; } private string _typeName; public string TypeName { get { return _typeName; } set { if (SetProperty(ref _typeName, value)) { FileName = string.Format("{0}{1}", value.Trim(), _fileExtension); NotifyPropertyChanged(nameof(GeneratedName)); } } } public string GeneratedName { get { return string.Format( "{0}{1}{2}", string.IsNullOrEmpty(_defaultNamespace) ? string.Empty : _defaultNamespace + ".", _typeName.Trim(), _generatedNameTypeParameterSuffix); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } private NewTypeDestination _destination = NewTypeDestination.NewFile; public NewTypeDestination Destination { get { return _destination; } set { if (SetProperty(ref _destination, value)) { NotifyPropertyChanged(nameof(FileNameEnabled)); } } } internal bool TrySubmit([NotNullWhen(returnValue: false)] out string? message) { message = null; if (_syntaxFactsService is null) { throw new InvalidOperationException(); } var trimmedName = TypeName.Trim(); if (_conflictingNames.Contains(trimmedName)) { message = ServicesVSResources.Name_conflicts_with_an_existing_type_name; return false; } if (!_syntaxFactsService.IsValidIdentifier(trimmedName)) { message = string.Format(ServicesVSResources.Name_is_not_a_valid_0_identifier, _languageName); return false; } var trimmedFileName = FileName.Trim(); if (!Path.GetExtension(trimmedFileName).Equals(_fileExtension, StringComparison.OrdinalIgnoreCase)) { message = string.Format(ServicesVSResources.File_name_must_have_the_0_extension, _fileExtension); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { message = ServicesVSResources.Illegal_characters_in_path; return false; } return true; } public bool FileNameEnabled => Destination == NewTypeDestination.NewFile; } internal enum NewTypeDestination { CurrentFile, NewFile }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class NewTypeDestinationSelectionViewModel : AbstractNotifyPropertyChanged { public static NewTypeDestinationSelectionViewModel Default = new( string.Empty, LanguageNames.CSharp, string.Empty, string.Empty, ImmutableArray<string>.Empty, null ); private readonly string _fileExtension; private readonly string _defaultNamespace; private readonly string _generatedNameTypeParameterSuffix; private readonly ImmutableArray<string> _conflictingNames; private readonly string _defaultName; private readonly ISyntaxFactsService? _syntaxFactsService; private readonly string _languageName; public NewTypeDestinationSelectionViewModel( string defaultName, string languageName, string defaultNamespace, string generatedNameTypeParameterSuffix, ImmutableArray<string> conflictingNames, ISyntaxFactsService? syntaxFactsService) { _defaultName = defaultName; _fileExtension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; _languageName = languageName; _generatedNameTypeParameterSuffix = generatedNameTypeParameterSuffix; _conflictingNames = conflictingNames; _defaultNamespace = defaultNamespace; _typeName = _defaultName; _syntaxFactsService = syntaxFactsService; _fileName = $"{defaultName}{_fileExtension}"; } private string _typeName; public string TypeName { get { return _typeName; } set { if (SetProperty(ref _typeName, value)) { FileName = string.Format("{0}{1}", value.Trim(), _fileExtension); NotifyPropertyChanged(nameof(GeneratedName)); } } } public string GeneratedName { get { return string.Format( "{0}{1}{2}", string.IsNullOrEmpty(_defaultNamespace) ? string.Empty : _defaultNamespace + ".", _typeName.Trim(), _generatedNameTypeParameterSuffix); } } private string _fileName; public string FileName { get { return _fileName; } set { SetProperty(ref _fileName, value); } } private NewTypeDestination _destination = NewTypeDestination.NewFile; public NewTypeDestination Destination { get { return _destination; } set { if (SetProperty(ref _destination, value)) { NotifyPropertyChanged(nameof(FileNameEnabled)); } } } internal bool TrySubmit([NotNullWhen(returnValue: false)] out string? message) { message = null; if (_syntaxFactsService is null) { throw new InvalidOperationException(); } var trimmedName = TypeName.Trim(); if (_conflictingNames.Contains(trimmedName)) { message = ServicesVSResources.Name_conflicts_with_an_existing_type_name; return false; } if (!_syntaxFactsService.IsValidIdentifier(trimmedName)) { message = string.Format(ServicesVSResources.Name_is_not_a_valid_0_identifier, _languageName); return false; } var trimmedFileName = FileName.Trim(); if (!Path.GetExtension(trimmedFileName).Equals(_fileExtension, StringComparison.OrdinalIgnoreCase)) { message = string.Format(ServicesVSResources.File_name_must_have_the_0_extension, _fileExtension); return false; } if (trimmedFileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { message = ServicesVSResources.Illegal_characters_in_path; return false; } return true; } public bool FileNameEnabled => Destination == NewTypeDestination.NewFile; } internal enum NewTypeDestination { CurrentFile, NewFile }; }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Core/Portable/PEWriter/MethodSpecComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MethodSpecComparer : IEqualityComparer<IGenericMethodInstanceReference> { private readonly MetadataWriter _metadataWriter; internal MethodSpecComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); return _metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context)) && _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); } public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) { return Hash.Combine( _metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class MethodSpecComparer : IEqualityComparer<IGenericMethodInstanceReference> { private readonly MetadataWriter _metadataWriter; internal MethodSpecComparer(MetadataWriter metadataWriter) { _metadataWriter = metadataWriter; } public bool Equals(IGenericMethodInstanceReference? x, IGenericMethodInstanceReference? y) { if (x == y) { return true; } RoslynDebug.Assert(x is object && y is object); return _metadataWriter.GetMethodDefinitionOrReferenceHandle(x.GetGenericMethod(_metadataWriter.Context)) == _metadataWriter.GetMethodDefinitionOrReferenceHandle(y.GetGenericMethod(_metadataWriter.Context)) && _metadataWriter.GetMethodSpecificationSignatureHandle(x) == _metadataWriter.GetMethodSpecificationSignatureHandle(y); } public int GetHashCode(IGenericMethodInstanceReference methodInstanceReference) { return Hash.Combine( _metadataWriter.GetMethodDefinitionOrReferenceHandle(methodInstanceReference.GetGenericMethod(_metadataWriter.Context)).GetHashCode(), _metadataWriter.GetMethodSpecificationSignatureHandle(methodInstanceReference).GetHashCode()); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Portable/Binder/LookupResultKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Classifies the different ways in which a found symbol might be incorrect. /// Higher values are considered "better" than lower values. These values are used /// in a few different places: /// 1) Inside a LookupResult to indicate the quality of a symbol from lookup. /// 2) Inside a bound node (for example, BoundBadExpression), to indicate /// the "binding quality" of the symbols referenced by that bound node. /// 3) Inside an error type symbol, to indicate the reason that the candidate symbols /// in the error type symbols were not good. /// /// While most of the values can occur in all places, some of the problems are not /// detected at lookup time (e.g., NotAVariable), so only occur in bound nodes. /// </summary> /// <remarks> /// This enumeration is parallel to and almost the same as the CandidateReason enumeration. /// Changes to one should usually result in changes to the other. /// /// There are two enumerations because: /// 1) CandidateReason in language-independent, while this enum is language specific. /// 2) The name "CandidateReason" didn't make much sense in the way LookupResultKind is used internally. /// 3) Viable isn't used in CandidateReason, but we need it in LookupResultKind, and there isn't a /// a way to have internal enumeration values. /// </remarks> internal enum LookupResultKind : byte { // Note: order is important! High values take precedences over lower values. Empty, NotATypeOrNamespace, NotAnAttributeType, WrongArity, NotCreatable, // E.g., new of an interface or static class Inaccessible, NotReferencable, // E.g., get_Goo binding to an accessor. NotAValue, NotAVariable, // used for several slightly different places, e.g. LHS of =, out/ref parameters, etc. NotInvocable, NotLabel, // used when a label is required StaticInstanceMismatch, OverloadResolutionFailure, // Note: within LookupResult, LookupResultKind.Ambiguous is currently not used (in C#). Instead // ambiguous results are determined later by examining multiple viable results to determine if // they are ambiguous or overloaded. Thus, LookupResultKind.Ambiguous does not occur in a LookupResult, // but can occur within a BoundBadExpression. Ambiguous, // Indicates a set of symbols, and they are totally fine. MemberGroup, // Indicates a single symbol is totally fine. Viable, } internal static class LookupResultKindExtensions { /// <summary> /// Maps a LookupResultKind to a CandidateReason. Should not be called on LookupResultKind.Viable! /// </summary> public static CandidateReason ToCandidateReason(this LookupResultKind resultKind) { switch (resultKind) { case LookupResultKind.Empty: return CandidateReason.None; case LookupResultKind.NotATypeOrNamespace: return CandidateReason.NotATypeOrNamespace; case LookupResultKind.NotAnAttributeType: return CandidateReason.NotAnAttributeType; case LookupResultKind.WrongArity: return CandidateReason.WrongArity; case LookupResultKind.Inaccessible: return CandidateReason.Inaccessible; case LookupResultKind.NotCreatable: return CandidateReason.NotCreatable; case LookupResultKind.NotReferencable: return CandidateReason.NotReferencable; case LookupResultKind.NotAValue: return CandidateReason.NotAValue; case LookupResultKind.NotAVariable: return CandidateReason.NotAVariable; case LookupResultKind.NotInvocable: return CandidateReason.NotInvocable; case LookupResultKind.StaticInstanceMismatch: return CandidateReason.StaticInstanceMismatch; case LookupResultKind.OverloadResolutionFailure: return CandidateReason.OverloadResolutionFailure; case LookupResultKind.Ambiguous: return CandidateReason.Ambiguous; case LookupResultKind.MemberGroup: return CandidateReason.MemberGroup; case LookupResultKind.Viable: Debug.Assert(false, "Should not call this on LookupResultKind.Viable"); return CandidateReason.None; default: throw ExceptionUtilities.UnexpectedValue(resultKind); } } // Return the lowest non-empty result kind public static LookupResultKind WorseResultKind(this LookupResultKind resultKind1, LookupResultKind resultKind2) { if (resultKind1 == LookupResultKind.Empty) return resultKind2; if (resultKind2 == LookupResultKind.Empty) return resultKind1; if (resultKind1 < resultKind2) return resultKind1; else return resultKind2; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Classifies the different ways in which a found symbol might be incorrect. /// Higher values are considered "better" than lower values. These values are used /// in a few different places: /// 1) Inside a LookupResult to indicate the quality of a symbol from lookup. /// 2) Inside a bound node (for example, BoundBadExpression), to indicate /// the "binding quality" of the symbols referenced by that bound node. /// 3) Inside an error type symbol, to indicate the reason that the candidate symbols /// in the error type symbols were not good. /// /// While most of the values can occur in all places, some of the problems are not /// detected at lookup time (e.g., NotAVariable), so only occur in bound nodes. /// </summary> /// <remarks> /// This enumeration is parallel to and almost the same as the CandidateReason enumeration. /// Changes to one should usually result in changes to the other. /// /// There are two enumerations because: /// 1) CandidateReason in language-independent, while this enum is language specific. /// 2) The name "CandidateReason" didn't make much sense in the way LookupResultKind is used internally. /// 3) Viable isn't used in CandidateReason, but we need it in LookupResultKind, and there isn't a /// a way to have internal enumeration values. /// </remarks> internal enum LookupResultKind : byte { // Note: order is important! High values take precedences over lower values. Empty, NotATypeOrNamespace, NotAnAttributeType, WrongArity, NotCreatable, // E.g., new of an interface or static class Inaccessible, NotReferencable, // E.g., get_Goo binding to an accessor. NotAValue, NotAVariable, // used for several slightly different places, e.g. LHS of =, out/ref parameters, etc. NotInvocable, NotLabel, // used when a label is required StaticInstanceMismatch, OverloadResolutionFailure, // Note: within LookupResult, LookupResultKind.Ambiguous is currently not used (in C#). Instead // ambiguous results are determined later by examining multiple viable results to determine if // they are ambiguous or overloaded. Thus, LookupResultKind.Ambiguous does not occur in a LookupResult, // but can occur within a BoundBadExpression. Ambiguous, // Indicates a set of symbols, and they are totally fine. MemberGroup, // Indicates a single symbol is totally fine. Viable, } internal static class LookupResultKindExtensions { /// <summary> /// Maps a LookupResultKind to a CandidateReason. Should not be called on LookupResultKind.Viable! /// </summary> public static CandidateReason ToCandidateReason(this LookupResultKind resultKind) { switch (resultKind) { case LookupResultKind.Empty: return CandidateReason.None; case LookupResultKind.NotATypeOrNamespace: return CandidateReason.NotATypeOrNamespace; case LookupResultKind.NotAnAttributeType: return CandidateReason.NotAnAttributeType; case LookupResultKind.WrongArity: return CandidateReason.WrongArity; case LookupResultKind.Inaccessible: return CandidateReason.Inaccessible; case LookupResultKind.NotCreatable: return CandidateReason.NotCreatable; case LookupResultKind.NotReferencable: return CandidateReason.NotReferencable; case LookupResultKind.NotAValue: return CandidateReason.NotAValue; case LookupResultKind.NotAVariable: return CandidateReason.NotAVariable; case LookupResultKind.NotInvocable: return CandidateReason.NotInvocable; case LookupResultKind.StaticInstanceMismatch: return CandidateReason.StaticInstanceMismatch; case LookupResultKind.OverloadResolutionFailure: return CandidateReason.OverloadResolutionFailure; case LookupResultKind.Ambiguous: return CandidateReason.Ambiguous; case LookupResultKind.MemberGroup: return CandidateReason.MemberGroup; case LookupResultKind.Viable: Debug.Assert(false, "Should not call this on LookupResultKind.Viable"); return CandidateReason.None; default: throw ExceptionUtilities.UnexpectedValue(resultKind); } } // Return the lowest non-empty result kind public static LookupResultKind WorseResultKind(this LookupResultKind resultKind1, LookupResultKind resultKind2) { if (resultKind1 == LookupResultKind.Empty) return resultKind2; if (resultKind2 == LookupResultKind.Empty) return resultKind1; if (resultKind1 < resultKind2) return resultKind1; else return resultKind2; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/VisualBasic/Portable/Formatting/Rules/BaseFormattingRule.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Friend Class BaseFormattingRule Inherits CompatAbstractFormattingRule Public Sub New() End Sub Protected Shared Sub AddIndentBlockOperation(operations As List(Of IndentBlockOperation), startToken As SyntaxToken, endToken As SyntaxToken, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) If startToken.Kind = SyntaxKind.None OrElse endToken.Kind = SyntaxKind.None Then Return End If Dim span = GetIndentBlockSpan(startToken, endToken) operations.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, span, indentationDelta:=1, [option]:=[option])) End Sub Protected Shared Sub AddIndentBlockOperation(operations As List(Of IndentBlockOperation), baseToken As SyntaxToken, startToken As SyntaxToken, endToken As SyntaxToken, Optional textSpan As TextSpan = Nothing, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) Dim span = If(textSpan = Nothing, GetIndentBlockSpan(startToken, endToken), textSpan) operations.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta:=1, [option]:=[option])) End Sub Protected Shared Sub SetAlignmentBlockOperation(operations As List(Of IndentBlockOperation), baseToken As SyntaxToken, startToken As SyntaxToken, endToken As SyntaxToken, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) SetAlignmentBlockOperation(operations, baseToken, startToken, endToken, GetAlignmentSpan(startToken, endToken), [option]) End Sub Protected Shared Sub SetAlignmentBlockOperation(operations As List(Of IndentBlockOperation), baseToken As SyntaxToken, startToken As SyntaxToken, endToken As SyntaxToken, span As TextSpan, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) operations.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta:=0, [option]:=[option])) End Sub Protected Shared Sub AddAbsolutePositionIndentBlockOperation(operations As List(Of IndentBlockOperation), startToken As SyntaxToken, endToken As SyntaxToken, indentation As Integer, Optional [option] As IndentBlockOption = IndentBlockOption.AbsolutePosition) AddAbsolutePositionIndentBlockOperation(operations, startToken, endToken, indentation, GetIndentBlockSpan(startToken, endToken), [option]) End Sub Protected Shared Sub AddAbsolutePositionIndentBlockOperation(operations As List(Of IndentBlockOperation), startToken As SyntaxToken, endToken As SyntaxToken, indentation As Integer, span As TextSpan, Optional [option] As IndentBlockOption = IndentBlockOption.AbsolutePosition) operations.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, span, indentation, [option])) End Sub Private Shared Function GetAlignmentSpan(startToken As SyntaxToken, endToken As SyntaxToken) As TextSpan Dim previousToken = startToken.GetPreviousToken(includeZeroWidth:=True) Return TextSpan.FromBounds(previousToken.Span.End, endToken.FullSpan.End) End Function Private Shared Function GetIndentBlockSpan(startToken As SyntaxToken, endToken As SyntaxToken) As TextSpan ' special case for colon trivia Dim spanStart = startToken.GetPreviousToken(includeZeroWidth:=True).Span.End Dim nextToken = endToken.GetNextToken(includeZeroWidth:=True) For Each trivia In nextToken.LeadingTrivia.Reverse() If trivia.Kind = SyntaxKind.EndOfLineTrivia Then Exit For ElseIf trivia.Kind = SyntaxKind.ColonTrivia Then Return TextSpan.FromBounds(spanStart, trivia.FullSpan.Start) End If Next Return TextSpan.FromBounds(spanStart, nextToken.SpanStart) End Function #Disable Warning IDE0060 ' Remove unused parameter Protected Shared Sub AddSuppressWrappingIfOnSingleLineOperation(operations As List(Of SuppressOperation), startToken As SyntaxToken, endToken As SyntaxToken) ' VB doesn't need to use this operation Throw ExceptionUtilities.Unreachable End Sub Protected Shared Sub AddSuppressAllOperationIfOnMultipleLine(operations As List(Of SuppressOperation), startToken As SyntaxToken, endToken As SyntaxToken) ' VB doesn't need to use this operation Throw ExceptionUtilities.Unreachable End Sub #Enable Warning IDE0060 ' Remove unused parameter Protected Shared Sub AddAnchorIndentationOperation(operations As List(Of AnchorIndentationOperation), startToken As SyntaxToken, endToken As SyntaxToken) If startToken.Kind = SyntaxKind.None OrElse endToken.Kind = SyntaxKind.None Then Return End If operations.Add(FormattingOperations.CreateAnchorIndentationOperation(startToken, endToken)) End Sub Protected Shared Sub AddAlignIndentationOfTokensToBaseTokenOperation(operations As List(Of AlignTokensOperation), containingNode As SyntaxNode, baseToken As SyntaxToken, tokens As IEnumerable(Of SyntaxToken)) If containingNode Is Nothing OrElse tokens Is Nothing Then Return End If operations.Add(FormattingOperations.CreateAlignTokensOperation(baseToken, tokens, AlignTokensOption.AlignIndentationOfTokensToBaseToken)) End Sub Protected Shared Function CreateAdjustNewLinesOperation(line As Integer, [option] As AdjustNewLinesOption) As AdjustNewLinesOperation Return FormattingOperations.CreateAdjustNewLinesOperation(line, [option]) End Function Protected Shared Function CreateAdjustSpacesOperation(space As Integer, [option] As AdjustSpacesOption) As AdjustSpacesOperation Return FormattingOperations.CreateAdjustSpacesOperation(space, [option]) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Friend Class BaseFormattingRule Inherits CompatAbstractFormattingRule Public Sub New() End Sub Protected Shared Sub AddIndentBlockOperation(operations As List(Of IndentBlockOperation), startToken As SyntaxToken, endToken As SyntaxToken, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) If startToken.Kind = SyntaxKind.None OrElse endToken.Kind = SyntaxKind.None Then Return End If Dim span = GetIndentBlockSpan(startToken, endToken) operations.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, span, indentationDelta:=1, [option]:=[option])) End Sub Protected Shared Sub AddIndentBlockOperation(operations As List(Of IndentBlockOperation), baseToken As SyntaxToken, startToken As SyntaxToken, endToken As SyntaxToken, Optional textSpan As TextSpan = Nothing, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) Dim span = If(textSpan = Nothing, GetIndentBlockSpan(startToken, endToken), textSpan) operations.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta:=1, [option]:=[option])) End Sub Protected Shared Sub SetAlignmentBlockOperation(operations As List(Of IndentBlockOperation), baseToken As SyntaxToken, startToken As SyntaxToken, endToken As SyntaxToken, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) SetAlignmentBlockOperation(operations, baseToken, startToken, endToken, GetAlignmentSpan(startToken, endToken), [option]) End Sub Protected Shared Sub SetAlignmentBlockOperation(operations As List(Of IndentBlockOperation), baseToken As SyntaxToken, startToken As SyntaxToken, endToken As SyntaxToken, span As TextSpan, Optional [option] As IndentBlockOption = IndentBlockOption.RelativePosition) operations.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta:=0, [option]:=[option])) End Sub Protected Shared Sub AddAbsolutePositionIndentBlockOperation(operations As List(Of IndentBlockOperation), startToken As SyntaxToken, endToken As SyntaxToken, indentation As Integer, Optional [option] As IndentBlockOption = IndentBlockOption.AbsolutePosition) AddAbsolutePositionIndentBlockOperation(operations, startToken, endToken, indentation, GetIndentBlockSpan(startToken, endToken), [option]) End Sub Protected Shared Sub AddAbsolutePositionIndentBlockOperation(operations As List(Of IndentBlockOperation), startToken As SyntaxToken, endToken As SyntaxToken, indentation As Integer, span As TextSpan, Optional [option] As IndentBlockOption = IndentBlockOption.AbsolutePosition) operations.Add(FormattingOperations.CreateIndentBlockOperation(startToken, endToken, span, indentation, [option])) End Sub Private Shared Function GetAlignmentSpan(startToken As SyntaxToken, endToken As SyntaxToken) As TextSpan Dim previousToken = startToken.GetPreviousToken(includeZeroWidth:=True) Return TextSpan.FromBounds(previousToken.Span.End, endToken.FullSpan.End) End Function Private Shared Function GetIndentBlockSpan(startToken As SyntaxToken, endToken As SyntaxToken) As TextSpan ' special case for colon trivia Dim spanStart = startToken.GetPreviousToken(includeZeroWidth:=True).Span.End Dim nextToken = endToken.GetNextToken(includeZeroWidth:=True) For Each trivia In nextToken.LeadingTrivia.Reverse() If trivia.Kind = SyntaxKind.EndOfLineTrivia Then Exit For ElseIf trivia.Kind = SyntaxKind.ColonTrivia Then Return TextSpan.FromBounds(spanStart, trivia.FullSpan.Start) End If Next Return TextSpan.FromBounds(spanStart, nextToken.SpanStart) End Function #Disable Warning IDE0060 ' Remove unused parameter Protected Shared Sub AddSuppressWrappingIfOnSingleLineOperation(operations As List(Of SuppressOperation), startToken As SyntaxToken, endToken As SyntaxToken) ' VB doesn't need to use this operation Throw ExceptionUtilities.Unreachable End Sub Protected Shared Sub AddSuppressAllOperationIfOnMultipleLine(operations As List(Of SuppressOperation), startToken As SyntaxToken, endToken As SyntaxToken) ' VB doesn't need to use this operation Throw ExceptionUtilities.Unreachable End Sub #Enable Warning IDE0060 ' Remove unused parameter Protected Shared Sub AddAnchorIndentationOperation(operations As List(Of AnchorIndentationOperation), startToken As SyntaxToken, endToken As SyntaxToken) If startToken.Kind = SyntaxKind.None OrElse endToken.Kind = SyntaxKind.None Then Return End If operations.Add(FormattingOperations.CreateAnchorIndentationOperation(startToken, endToken)) End Sub Protected Shared Sub AddAlignIndentationOfTokensToBaseTokenOperation(operations As List(Of AlignTokensOperation), containingNode As SyntaxNode, baseToken As SyntaxToken, tokens As IEnumerable(Of SyntaxToken)) If containingNode Is Nothing OrElse tokens Is Nothing Then Return End If operations.Add(FormattingOperations.CreateAlignTokensOperation(baseToken, tokens, AlignTokensOption.AlignIndentationOfTokensToBaseToken)) End Sub Protected Shared Function CreateAdjustNewLinesOperation(line As Integer, [option] As AdjustNewLinesOption) As AdjustNewLinesOperation Return FormattingOperations.CreateAdjustNewLinesOperation(line, [option]) End Function Protected Shared Function CreateAdjustSpacesOperation(space As Integer, [option] As AdjustSpacesOption) As AdjustSpacesOperation Return FormattingOperations.CreateAdjustSpacesOperation(space, [option]) End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements <Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)> Public NotInheritable Class SplitIntoNestedIfStatementsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicSplitIntoNestedIfStatementsCodeRefactoringProvider() End Function <Theory> <InlineData("a [||]andalso b")> <InlineData("a an[||]dalso b")> <InlineData("a andalso[||] b")> <InlineData("a [|andalso|] b")> Public Async Function SplitOnAndAlsoOperatorSpans(condition As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if {condition} then end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then end if end if end sub end class") End Function <Theory> <InlineData("a [|and|]also b")> <InlineData("a[| andalso|] b")> <InlineData("a[||] andalso b")> Public Async Function NotSplitOnAndAlsoOperatorSpans(condition As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if {condition} then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnIfKeyword() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [||]if a andalso b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnOrElseOperator() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]orelse b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnBitwiseAndOperator() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]and b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnAndAlsoOperatorOutsideIfStatement() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) dim v = a [||]andalso b end sub end class") End Function <Fact> Public Async Function NotSplitOnAndAlsoOperatorInIfStatementBody() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a andalso b then a [||]andalso b end if end sub end class") End Function <Fact> Public Async Function NotSplitOnSingleLineIf() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a [||]andalso b andalso c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a then if b andalso c andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b [||]andalso c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b then if c andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression3() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso c [||]andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso c then if d then end if end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a [||]andalso b) andalso c andalso d then end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso (c [||]andalso d) then end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses3() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a andalso b [||]andalso c andalso d) then end if end sub end class") End Function <Fact> Public Async Function SplitWithOtherExpressionInsideParentheses1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a [||]andalso (b andalso c) andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a then if (b andalso c) andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithOtherExpressionInsideParentheses2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso (b andalso c) [||]andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso (b andalso c) then if d then end if end if end sub end class") End Function <Fact> Public Async Function NotSplitWithMixedOrElseExpression1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso b orelse c then end if end sub end class") End Function <Fact> Public Async Function NotSplitWithMixedOrElseExpression2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a orelse b [||]andalso c then end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedOrElseExpressionInsideParentheses1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso (b orelse c) then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a then if (b orelse c) then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedOrElseExpressionInsideParentheses2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if (a orelse b) [||]andalso c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if (a orelse b) then if c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedEqualsExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso b = c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a then if b = c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedEqualsExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a = b [||]andalso c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a = b then if c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine(a andalso b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine(a andalso b) end if end if end sub end class") End Function <Fact> Public Async Function SplitWithNestedIfStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then if true end if end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then if true end if end if end if end sub end class") End Function <Fact> Public Async Function SplitWithElseStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() else System.Console.WriteLine(a andalso b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() else System.Console.WriteLine(a andalso b) end if else System.Console.WriteLine(a andalso b) end if end sub end class") End Function <Fact> Public Async Function SplitWithElseNestedIfStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() else if true end if end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() else if true end if end if else if true end if end if end sub end class") End Function <Fact> Public Async Function SplitWithElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function SplitAsPartOfElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a [||]andalso b then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a then if b then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function SplitAsPartOfElseIfElseIf() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a [||]andalso b then System.Console.WriteLine(a) elseif a orelse b System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a then if b then System.Console.WriteLine(a) elseif a orelse b System.Console.WriteLine(b) end if elseif a orelse b System.Console.WriteLine(b) end if end sub end class") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements <Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)> Public NotInheritable Class SplitIntoNestedIfStatementsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicSplitIntoNestedIfStatementsCodeRefactoringProvider() End Function <Theory> <InlineData("a [||]andalso b")> <InlineData("a an[||]dalso b")> <InlineData("a andalso[||] b")> <InlineData("a [|andalso|] b")> Public Async Function SplitOnAndAlsoOperatorSpans(condition As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if {condition} then end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then end if end if end sub end class") End Function <Theory> <InlineData("a [|and|]also b")> <InlineData("a[| andalso|] b")> <InlineData("a[||] andalso b")> Public Async Function NotSplitOnAndAlsoOperatorSpans(condition As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if {condition} then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnIfKeyword() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [||]if a andalso b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnOrElseOperator() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]orelse b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnBitwiseAndOperator() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]and b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnAndAlsoOperatorOutsideIfStatement() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) dim v = a [||]andalso b end sub end class") End Function <Fact> Public Async Function NotSplitOnAndAlsoOperatorInIfStatementBody() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a andalso b then a [||]andalso b end if end sub end class") End Function <Fact> Public Async Function NotSplitOnSingleLineIf() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a [||]andalso b andalso c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a then if b andalso c andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b [||]andalso c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b then if c andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression3() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso c [||]andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso c then if d then end if end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a [||]andalso b) andalso c andalso d then end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso (c [||]andalso d) then end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses3() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a andalso b [||]andalso c andalso d) then end if end sub end class") End Function <Fact> Public Async Function SplitWithOtherExpressionInsideParentheses1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a [||]andalso (b andalso c) andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a then if (b andalso c) andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithOtherExpressionInsideParentheses2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso (b andalso c) [||]andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso (b andalso c) then if d then end if end if end sub end class") End Function <Fact> Public Async Function NotSplitWithMixedOrElseExpression1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso b orelse c then end if end sub end class") End Function <Fact> Public Async Function NotSplitWithMixedOrElseExpression2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a orelse b [||]andalso c then end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedOrElseExpressionInsideParentheses1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso (b orelse c) then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a then if (b orelse c) then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedOrElseExpressionInsideParentheses2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if (a orelse b) [||]andalso c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if (a orelse b) then if c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedEqualsExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso b = c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a then if b = c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedEqualsExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a = b [||]andalso c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a = b then if c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine(a andalso b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine(a andalso b) end if end if end sub end class") End Function <Fact> Public Async Function SplitWithNestedIfStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then if true end if end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then if true end if end if end if end sub end class") End Function <Fact> Public Async Function SplitWithElseStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() else System.Console.WriteLine(a andalso b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() else System.Console.WriteLine(a andalso b) end if else System.Console.WriteLine(a andalso b) end if end sub end class") End Function <Fact> Public Async Function SplitWithElseNestedIfStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() else if true end if end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() else if true end if end if else if true end if end if end sub end class") End Function <Fact> Public Async Function SplitWithElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function SplitAsPartOfElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a [||]andalso b then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a then if b then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function SplitAsPartOfElseIfElseIf() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a [||]andalso b then System.Console.WriteLine(a) elseif a orelse b System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a then if b then System.Console.WriteLine(a) elseif a orelse b System.Console.WriteLine(b) end if elseif a orelse b System.Console.WriteLine(b) end if end sub end class") End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameActionAnnotation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// This annotation will be used by rename to mark all places where it needs to rename an identifier (token replacement) and where to /// check if the semantics have been changes (conflict detection). /// </summary> /// <remarks>This annotation should be put on tokens only.</remarks> internal class RenameActionAnnotation : RenameAnnotation { /// <summary> /// The span this token occupied in the original syntax tree. Can be used to show e.g. conflicts in the UI. /// </summary> public readonly TextSpan OriginalSpan; /// <summary> /// A flag indicating whether this is a location that needs to be renamed or just tracked for conflicts. /// </summary> public readonly bool IsRenameLocation; /// <summary> /// A flag indicating whether the token at this location has the same ValueText then the original name /// of the symbol that gets renamed. /// </summary> public readonly bool IsOriginalTextLocation; /// <summary> /// When replacing the annotated token this string will be prepended to the token's value. This is used when renaming compiler /// generated fields and methods backing properties (e.g. "get_X" or "_X" for property "X"). /// </summary> public readonly string Prefix; /// <summary> /// When replacing the annotated token this string will be appended to the token's value. This is used when renaming compiler /// generated types whose names are derived from user given names (e.g. "XEventHandler" for event "X"). /// </summary> public readonly string Suffix; /// <summary> /// A single dimensional array of annotations to verify after rename. /// </summary> public readonly RenameDeclarationLocationReference[] RenameDeclarationLocationReferences; /// <summary> /// States if this token is a Namespace Declaration Reference /// </summary> public readonly bool IsNamespaceDeclarationReference; /// <summary> /// States if this token is a member group reference, typically found in NameOf expressions /// </summary> public readonly bool IsMemberGroupReference; /// <summary> /// States if this token is annotated as a part of the Invocation Expression that needs to be checked for the Conflicts /// </summary> public readonly bool IsInvocationExpression; public RenameActionAnnotation( TextSpan originalSpan, bool isRenameLocation, string prefix, string suffix, bool isOriginalTextLocation, RenameDeclarationLocationReference[] renameDeclarationLocations, bool isNamespaceDeclarationReference, bool isInvocationExpression, bool isMemberGroupReference) { this.OriginalSpan = originalSpan; this.IsRenameLocation = isRenameLocation; this.Prefix = prefix; this.Suffix = suffix; this.RenameDeclarationLocationReferences = renameDeclarationLocations; this.IsOriginalTextLocation = isOriginalTextLocation; this.IsNamespaceDeclarationReference = isNamespaceDeclarationReference; this.IsInvocationExpression = isInvocationExpression; this.IsMemberGroupReference = isMemberGroupReference; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { /// <summary> /// This annotation will be used by rename to mark all places where it needs to rename an identifier (token replacement) and where to /// check if the semantics have been changes (conflict detection). /// </summary> /// <remarks>This annotation should be put on tokens only.</remarks> internal class RenameActionAnnotation : RenameAnnotation { /// <summary> /// The span this token occupied in the original syntax tree. Can be used to show e.g. conflicts in the UI. /// </summary> public readonly TextSpan OriginalSpan; /// <summary> /// A flag indicating whether this is a location that needs to be renamed or just tracked for conflicts. /// </summary> public readonly bool IsRenameLocation; /// <summary> /// A flag indicating whether the token at this location has the same ValueText then the original name /// of the symbol that gets renamed. /// </summary> public readonly bool IsOriginalTextLocation; /// <summary> /// When replacing the annotated token this string will be prepended to the token's value. This is used when renaming compiler /// generated fields and methods backing properties (e.g. "get_X" or "_X" for property "X"). /// </summary> public readonly string Prefix; /// <summary> /// When replacing the annotated token this string will be appended to the token's value. This is used when renaming compiler /// generated types whose names are derived from user given names (e.g. "XEventHandler" for event "X"). /// </summary> public readonly string Suffix; /// <summary> /// A single dimensional array of annotations to verify after rename. /// </summary> public readonly RenameDeclarationLocationReference[] RenameDeclarationLocationReferences; /// <summary> /// States if this token is a Namespace Declaration Reference /// </summary> public readonly bool IsNamespaceDeclarationReference; /// <summary> /// States if this token is a member group reference, typically found in NameOf expressions /// </summary> public readonly bool IsMemberGroupReference; /// <summary> /// States if this token is annotated as a part of the Invocation Expression that needs to be checked for the Conflicts /// </summary> public readonly bool IsInvocationExpression; public RenameActionAnnotation( TextSpan originalSpan, bool isRenameLocation, string prefix, string suffix, bool isOriginalTextLocation, RenameDeclarationLocationReference[] renameDeclarationLocations, bool isNamespaceDeclarationReference, bool isInvocationExpression, bool isMemberGroupReference) { this.OriginalSpan = originalSpan; this.IsRenameLocation = isRenameLocation; this.Prefix = prefix; this.Suffix = suffix; this.RenameDeclarationLocationReferences = renameDeclarationLocations; this.IsOriginalTextLocation = isOriginalTextLocation; this.IsNamespaceDeclarationReference = isNamespaceDeclarationReference; this.IsInvocationExpression = isInvocationExpression; this.IsMemberGroupReference = isMemberGroupReference; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.DocumentChangeTracker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { internal interface IDocumentChangeTracker { void StartTracking(Uri documentUri, SourceText initialText); void UpdateTrackedDocument(Uri documentUri, SourceText text); void StopTracking(Uri documentUri); bool IsTracking(Uri documentUri); IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments(); SourceText GetTrackedDocumentSourceText(Uri documentUri); } private class NonMutatingDocumentChangeTracker : IDocumentChangeTracker { private readonly DocumentChangeTracker _tracker; public NonMutatingDocumentChangeTracker(DocumentChangeTracker tracker) { _tracker = tracker; } public IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments() => _tracker.GetTrackedDocuments(); public SourceText GetTrackedDocumentSourceText(Uri documentUri) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } public bool IsTracking(Uri documentUri) => _tracker.IsTracking(documentUri); public void StartTracking(Uri documentUri, SourceText initialText) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } public void StopTracking(Uri documentUri) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } public void UpdateTrackedDocument(Uri documentUri, SourceText text) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } } /// <summary> /// Keeps track of changes to documents that are opened in the LSP client. Calls MUST not overlap, so this /// should be called from a mutating request handler. See <see cref="RequestExecutionQueue"/> for more details. /// </summary> internal class DocumentChangeTracker : IWorkspaceService, IDocumentChangeTracker { private readonly Dictionary<Uri, SourceText> _trackedDocuments = new(); public bool IsTracking(Uri documentUri) => _trackedDocuments.ContainsKey(documentUri); public void StartTracking(Uri documentUri, SourceText initialText) { Contract.ThrowIfTrue(_trackedDocuments.ContainsKey(documentUri), $"didOpen received for {documentUri} which is already open."); _trackedDocuments.Add(documentUri, initialText); } public void UpdateTrackedDocument(Uri documentUri, SourceText text) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), $"didChange received for {documentUri} which is not open."); _trackedDocuments[documentUri] = text; } public SourceText GetTrackedDocumentSourceText(Uri documentUri) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), "didChange received for a document that isn't open."); return _trackedDocuments[documentUri]; } public void StopTracking(Uri documentUri) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), $"didClose received for {documentUri} which is not open."); _trackedDocuments.Remove(documentUri); } public IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments() => _trackedDocuments.Select(k => (k.Key, k.Value)); } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly RequestExecutionQueue _queue; public TestAccessor(RequestExecutionQueue queue) => _queue = queue; public List<SourceText> GetTrackedTexts() => _queue._documentChangeTracker.GetTrackedDocuments().Select(i => i.Text).ToList(); public bool IsComplete() => _queue._queue.IsCompleted && _queue._queue.IsEmpty; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { internal interface IDocumentChangeTracker { void StartTracking(Uri documentUri, SourceText initialText); void UpdateTrackedDocument(Uri documentUri, SourceText text); void StopTracking(Uri documentUri); bool IsTracking(Uri documentUri); IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments(); SourceText GetTrackedDocumentSourceText(Uri documentUri); } private class NonMutatingDocumentChangeTracker : IDocumentChangeTracker { private readonly DocumentChangeTracker _tracker; public NonMutatingDocumentChangeTracker(DocumentChangeTracker tracker) { _tracker = tracker; } public IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments() => _tracker.GetTrackedDocuments(); public SourceText GetTrackedDocumentSourceText(Uri documentUri) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } public bool IsTracking(Uri documentUri) => _tracker.IsTracking(documentUri); public void StartTracking(Uri documentUri, SourceText initialText) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } public void StopTracking(Uri documentUri) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } public void UpdateTrackedDocument(Uri documentUri, SourceText text) { Contract.Fail("Mutating documents not allowed in a non-mutating request handler"); throw new NotImplementedException(); } } /// <summary> /// Keeps track of changes to documents that are opened in the LSP client. Calls MUST not overlap, so this /// should be called from a mutating request handler. See <see cref="RequestExecutionQueue"/> for more details. /// </summary> internal class DocumentChangeTracker : IWorkspaceService, IDocumentChangeTracker { private readonly Dictionary<Uri, SourceText> _trackedDocuments = new(); public bool IsTracking(Uri documentUri) => _trackedDocuments.ContainsKey(documentUri); public void StartTracking(Uri documentUri, SourceText initialText) { Contract.ThrowIfTrue(_trackedDocuments.ContainsKey(documentUri), $"didOpen received for {documentUri} which is already open."); _trackedDocuments.Add(documentUri, initialText); } public void UpdateTrackedDocument(Uri documentUri, SourceText text) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), $"didChange received for {documentUri} which is not open."); _trackedDocuments[documentUri] = text; } public SourceText GetTrackedDocumentSourceText(Uri documentUri) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), "didChange received for a document that isn't open."); return _trackedDocuments[documentUri]; } public void StopTracking(Uri documentUri) { Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), $"didClose received for {documentUri} which is not open."); _trackedDocuments.Remove(documentUri); } public IEnumerable<(Uri DocumentUri, SourceText Text)> GetTrackedDocuments() => _trackedDocuments.Select(k => (k.Key, k.Value)); } internal TestAccessor GetTestAccessor() => new TestAccessor(this); internal readonly struct TestAccessor { private readonly RequestExecutionQueue _queue; public TestAccessor(RequestExecutionQueue queue) => _queue = queue; public List<SourceText> GetTrackedTexts() => _queue._documentChangeTracker.GetTrackedDocuments().Select(i => i.Text).ToList(); public bool IsComplete() => _queue._queue.IsCompleted && _queue._queue.IsEmpty; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Impl/CodeModel/CodeModelState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Shared state common to all code model objects. /// </summary> internal sealed class CodeModelState { public IThreadingContext ThreadingContext { get; } public IServiceProvider ServiceProvider { get; } public ICodeModelService CodeModelService { get; } public ISyntaxFactsService SyntaxFactsService { get; } public ICodeGenerationService CodeGenerator { get; } public VisualStudioWorkspace Workspace { get; } public ProjectCodeModelFactory ProjectCodeModelFactory { get; } public CodeModelState( IThreadingContext threadingContext, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace, ProjectCodeModelFactory projectCodeModelFactory) { Debug.Assert(threadingContext != null); Debug.Assert(serviceProvider != null); Debug.Assert(languageServices != null); Debug.Assert(workspace != null); // ⚠ This code runs on the main thread. Language services accessed here should be preloaded in // ProjectCodemodelFactory to avoid blocking MEF operations. this.ThreadingContext = threadingContext; this.ServiceProvider = serviceProvider; this.CodeModelService = languageServices.GetService<ICodeModelService>(); this.SyntaxFactsService = languageServices.GetService<ISyntaxFactsService>(); this.CodeGenerator = languageServices.GetService<ICodeGenerationService>(); this.ProjectCodeModelFactory = projectCodeModelFactory; this.Workspace = workspace; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Shared state common to all code model objects. /// </summary> internal sealed class CodeModelState { public IThreadingContext ThreadingContext { get; } public IServiceProvider ServiceProvider { get; } public ICodeModelService CodeModelService { get; } public ISyntaxFactsService SyntaxFactsService { get; } public ICodeGenerationService CodeGenerator { get; } public VisualStudioWorkspace Workspace { get; } public ProjectCodeModelFactory ProjectCodeModelFactory { get; } public CodeModelState( IThreadingContext threadingContext, IServiceProvider serviceProvider, HostLanguageServices languageServices, VisualStudioWorkspace workspace, ProjectCodeModelFactory projectCodeModelFactory) { Debug.Assert(threadingContext != null); Debug.Assert(serviceProvider != null); Debug.Assert(languageServices != null); Debug.Assert(workspace != null); // ⚠ This code runs on the main thread. Language services accessed here should be preloaded in // ProjectCodemodelFactory to avoid blocking MEF operations. this.ThreadingContext = threadingContext; this.ServiceProvider = serviceProvider; this.CodeModelService = languageServices.GetService<ICodeModelService>(); this.SyntaxFactsService = languageServices.GetService<ISyntaxFactsService>(); this.CodeGenerator = languageServices.GetService<ICodeGenerationService>(); this.ProjectCodeModelFactory = projectCodeModelFactory; this.Workspace = workspace; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Test/Semantic/Diagnostics/MethodGroupConversion.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MethodGroupConversion : CSharpTestBase { [Fact] public void TestAmbiguous() { var source = @" partial class Program { static void Main() { D d; d = M; d = new D(M); M2(M); d = M3; d = new D(M3); M2(M3); } static void M(I1 i1) {} static void M(I2 i2) {} static void M2(D d) {} static void M3(int x) {} } interface I1 {} interface I2 {} class C : I1, I2 {} delegate void D(C c); "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,13): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(I1)' and 'Program.M(I2)' // d = M; Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(I1)", "Program.M(I2)").WithLocation(7, 13), // (8,19): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(I1)' and 'Program.M(I2)' // d = new D(M); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(I1)", "Program.M(I2)").WithLocation(8, 19), // (9,12): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(I1)' and 'Program.M(I2)' // M2(M); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(I1)", "Program.M(I2)").WithLocation(9, 12), // (11,13): error CS0123: No overload for 'M3' matches delegate 'D' // d = M3; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M3").WithArguments("M3", "D").WithLocation(11, 13), // (12,13): error CS0123: No overload for 'M3' matches delegate 'D' // d = new D(M3); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D(M3)").WithArguments("M3", "D").WithLocation(12, 13), // (13,12): error CS1503: Argument 1: cannot convert from 'method group' to 'D' // M2(M3); Diagnostic(ErrorCode.ERR_BadArgType, "M3").WithArguments("1", "method group", "D").WithLocation(13, 12) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class MethodGroupConversion : CSharpTestBase { [Fact] public void TestAmbiguous() { var source = @" partial class Program { static void Main() { D d; d = M; d = new D(M); M2(M); d = M3; d = new D(M3); M2(M3); } static void M(I1 i1) {} static void M(I2 i2) {} static void M2(D d) {} static void M3(int x) {} } interface I1 {} interface I2 {} class C : I1, I2 {} delegate void D(C c); "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,13): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(I1)' and 'Program.M(I2)' // d = M; Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(I1)", "Program.M(I2)").WithLocation(7, 13), // (8,19): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(I1)' and 'Program.M(I2)' // d = new D(M); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(I1)", "Program.M(I2)").WithLocation(8, 19), // (9,12): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(I1)' and 'Program.M(I2)' // M2(M); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(I1)", "Program.M(I2)").WithLocation(9, 12), // (11,13): error CS0123: No overload for 'M3' matches delegate 'D' // d = M3; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "M3").WithArguments("M3", "D").WithLocation(11, 13), // (12,13): error CS0123: No overload for 'M3' matches delegate 'D' // d = new D(M3); Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new D(M3)").WithArguments("M3", "D").WithLocation(12, 13), // (13,12): error CS1503: Argument 1: cannot convert from 'method group' to 'D' // M2(M3); Diagnostic(ErrorCode.ERR_BadArgType, "M3").WithArguments("1", "method group", "D").WithLocation(13, 12) ); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/CatchKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class CatchKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public CatchKeywordRecommender() : base(SyntaxKind.CatchKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsCatchOrFinallyContext(position, context.LeftToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class CatchKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public CatchKeywordRecommender() : base(SyntaxKind.CatchKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsCatchOrFinallyContext(position, context.LeftToken); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/RQName/Nodes/RQArrayType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQArrayType : RQArrayOrPointerType { public readonly int Rank; public RQArrayType(int rank, RQType elementType) : base(elementType) { Rank = rank; } public override SimpleTreeNode ToSimpleTree() { var rankNode = new SimpleLeafNode(Rank.ToString()); return new SimpleGroupNode(RQNameStrings.Array, rankNode, ElementType.ToSimpleTree()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQArrayType : RQArrayOrPointerType { public readonly int Rank; public RQArrayType(int rank, RQType elementType) : base(elementType) { Rank = rank; } public override SimpleTreeNode ToSimpleTree() { var rankNode = new SimpleLeafNode(Rank.ToString()); return new SimpleGroupNode(RQNameStrings.Array, rankNode, ElementType.ToSimpleTree()); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/VisualBasic/Portable/CodeFixes/IncorrectFunctionReturnType/IncorrectFunctionReturnTypeCodeFixProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.IncorrectFunctionReturnType <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FixIncorrectFunctionReturnType), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementInterface)> Friend Class IncorrectFunctionReturnTypeCodeFixProvider Inherits CodeFixProvider Friend Const BC36938 As String = "BC36938" ' Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator. Friend Const BC36945 As String = "BC36945" ' The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T). <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC36938, BC36945) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported for this code fix Return Nothing End Function Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim document = context.Document Dim span = context.Span Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(span.Start) If Not token.Span.IntersectsWith(span) Then Return End If Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim lambdaHeader = GetNodeToFix(Of LambdaHeaderSyntax)(token, span) If lambdaHeader IsNot Nothing Then Dim rewrittenLambdaHeader = AsyncOrIteratorFunctionReturnTypeFixer.RewriteLambdaHeader(lambdaHeader, semanticModel, cancellationToken) context.RegisterFixes( Await GetCodeActionsAsync(document, lambdaHeader, rewrittenLambdaHeader, cancellationToken).ConfigureAwait(False), context.Diagnostics) Return End If Dim methodStatement = GetNodeToFix(Of MethodStatementSyntax)(token, span) If methodStatement IsNot Nothing Then Dim rewrittenMethodStatement = AsyncOrIteratorFunctionReturnTypeFixer.RewriteMethodStatement(methodStatement, semanticModel, cancellationToken) context.RegisterFixes( Await GetCodeActionsAsync(document, methodStatement, rewrittenMethodStatement, cancellationToken).ConfigureAwait(False), context.Diagnostics) Return End If End Function Private Shared Function GetNodeToFix(Of T As SyntaxNode)(token As SyntaxToken, span As TextSpan) As T Return token.GetAncestors(Of T)() _ .FirstOrDefault(Function(c) c.Span.IntersectsWith(span)) End Function Private Shared Async Function GetCodeActionsAsync(document As Document, node As SyntaxNode, rewrittenNode As SyntaxNode, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of CodeAction)) If rewrittenNode IsNot node Then Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim newRoot = root.ReplaceNode(node, rewrittenNode) Dim newDocument = document.WithSyntaxRoot(newRoot) Return {New MyCodeAction(newDocument)} End If Return SpecializedCollections.EmptyEnumerable(Of CodeAction)() End Function Private Class MyCodeAction Inherits CodeAction.DocumentChangeAction Public Sub New(newDocument As Document) MyBase.New(VBFeaturesResources.Fix_Incorrect_Function_Return_Type, Function(c) Task.FromResult(newDocument), NameOf(VBFeaturesResources.Fix_Incorrect_Function_Return_Type)) End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeFixes.IncorrectFunctionReturnType <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FixIncorrectFunctionReturnType), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.ImplementInterface)> Friend Class IncorrectFunctionReturnTypeCodeFixProvider Inherits CodeFixProvider Friend Const BC36938 As String = "BC36938" ' Iterator functions must return either IEnumerable(Of T), or IEnumerator(Of T), or the non-generic forms IEnumerable or IEnumerator. Friend Const BC36945 As String = "BC36945" ' The 'Async' modifier can only be used on Subs, or on Functions that return Task or Task(Of T). <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public NotOverridable Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return ImmutableArray.Create(BC36938, BC36945) End Get End Property Public Overrides Function GetFixAllProvider() As FixAllProvider ' Fix All is not supported for this code fix Return Nothing End Function Public NotOverridable Overrides Async Function RegisterCodeFixesAsync(context As CodeFixContext) As Task Dim document = context.Document Dim span = context.Span Dim cancellationToken = context.CancellationToken Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim token = root.FindToken(span.Start) If Not token.Span.IntersectsWith(span) Then Return End If Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False) Dim lambdaHeader = GetNodeToFix(Of LambdaHeaderSyntax)(token, span) If lambdaHeader IsNot Nothing Then Dim rewrittenLambdaHeader = AsyncOrIteratorFunctionReturnTypeFixer.RewriteLambdaHeader(lambdaHeader, semanticModel, cancellationToken) context.RegisterFixes( Await GetCodeActionsAsync(document, lambdaHeader, rewrittenLambdaHeader, cancellationToken).ConfigureAwait(False), context.Diagnostics) Return End If Dim methodStatement = GetNodeToFix(Of MethodStatementSyntax)(token, span) If methodStatement IsNot Nothing Then Dim rewrittenMethodStatement = AsyncOrIteratorFunctionReturnTypeFixer.RewriteMethodStatement(methodStatement, semanticModel, cancellationToken) context.RegisterFixes( Await GetCodeActionsAsync(document, methodStatement, rewrittenMethodStatement, cancellationToken).ConfigureAwait(False), context.Diagnostics) Return End If End Function Private Shared Function GetNodeToFix(Of T As SyntaxNode)(token As SyntaxToken, span As TextSpan) As T Return token.GetAncestors(Of T)() _ .FirstOrDefault(Function(c) c.Span.IntersectsWith(span)) End Function Private Shared Async Function GetCodeActionsAsync(document As Document, node As SyntaxNode, rewrittenNode As SyntaxNode, cancellationToken As CancellationToken) As Task(Of IEnumerable(Of CodeAction)) If rewrittenNode IsNot node Then Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim newRoot = root.ReplaceNode(node, rewrittenNode) Dim newDocument = document.WithSyntaxRoot(newRoot) Return {New MyCodeAction(newDocument)} End If Return SpecializedCollections.EmptyEnumerable(Of CodeAction)() End Function Private Class MyCodeAction Inherits CodeAction.DocumentChangeAction Public Sub New(newDocument As Document) MyBase.New(VBFeaturesResources.Fix_Incorrect_Function_Return_Type, Function(c) Task.FromResult(newDocument), NameOf(VBFeaturesResources.Fix_Incorrect_Function_Return_Type)) End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Tools/PrepareTests/PrepareTests.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <SignAssembly>false</SignAssembly> <UseVSHostingProcess>false</UseVSHostingProcess> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <PackageReference Include="Mono.Options" Version="$(MonoOptionsVersion)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net5.0</TargetFramework> <SignAssembly>false</SignAssembly> <UseVSHostingProcess>false</UseVSHostingProcess> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <PackageReference Include="Mono.Options" Version="$(MonoOptionsVersion)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/SelectBlockHighlighterTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class SelectBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(SelectBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock1() As Task Await TestAsync(<Text> Class C Sub M() {|Cursor:[|Select Case|]|} x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock2() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x {|Cursor:[|Case|]|} 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock3() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") {|Cursor:[|Case|]|} 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock4() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 {|Cursor:[|Exit Select|]|} [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock5() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] {|Cursor:[|Case Else|]|} Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock6() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") {|Cursor:[|End Select|]|} End Sub End Class</Text>) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class SelectBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(SelectBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock1() As Task Await TestAsync(<Text> Class C Sub M() {|Cursor:[|Select Case|]|} x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock2() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x {|Cursor:[|Case|]|} 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock3() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") {|Cursor:[|Case|]|} 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock4() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 {|Cursor:[|Exit Select|]|} [|Case Else|] Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock5() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] {|Cursor:[|Case Else|]|} Console.WriteLine("Otherwise") [|End Select|] End Sub End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestSelectBlock6() As Task Await TestAsync(<Text> Class C Sub M() [|Select Case|] x [|Case|] 5 Console.WriteLine("x = 5") [|Case|] 10 [|Exit Select|] [|Case Else|] Console.WriteLine("Otherwise") {|Cursor:[|End Select|]|} End Sub End Class</Text>) End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/CSharp/Portable/GenerateConstructor/CSharpGenerateConstructorService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared] internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateConstructorService() { } protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => containingType.ContainingTypesOrSelfHasUnsafeKeyword(); protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is SimpleNameSyntax; protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ConstructorInitializerSyntax; protected override bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ImplicitObjectCreationExpressionSyntax; protected override bool TryInitializeConstructorInitializerGeneration( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var constructorInitializer = (ConstructorInitializerSyntax)node; if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing) { token = constructorInitializer.ThisOrBaseKeyword; arguments = GetArguments(constructorInitializer.ArgumentList.Arguments); var semanticModel = document.SemanticModel; var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken); typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer) ? currentType : currentType.BaseType.OriginalDefinition; return typeToGenerateIn != null; } token = default; arguments = default; typeToGenerateIn = null; return false; } private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument(a.GetRefKind(), a.NameColon?.Name.Identifier.ValueText, a.Expression)); private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<AttributeArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument( refKind: RefKind.None, a.NameEquals?.Name.Identifier.ValueText ?? a.NameColon?.Name.Identifier.ValueText, a.Expression)); protected override bool TryInitializeSimpleNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is ObjectCreationExpressionSyntax objectCreationExpression) { if (objectCreationExpression.ArgumentList != null && !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken); token = simpleName.Identifier; arguments = GetArguments(objectCreationExpression.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol; return typeToGenerateIn != null; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleAttributeNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is AttributeSyntax attribute) { if (attribute.ArgumentList != null && !attribute.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty) { token = simpleName.Identifier; arguments = GetArguments(attribute.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol; return typeToGenerateIn != null; } } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var implicitObjectCreation = (ImplicitObjectCreationExpressionSyntax)node; if (implicitObjectCreation.ArgumentList != null && !implicitObjectCreation.ArgumentList.CloseParenToken.IsMissing) { var typeInfo = document.SemanticModel.GetTypeInfo(implicitObjectCreation, cancellationToken); if (typeInfo.Type is INamedTypeSymbol typeSymbol) { token = implicitObjectCreation.NewKeyword; arguments = GetArguments(implicitObjectCreation.ArgumentList.Arguments); typeToGenerateIn = typeSymbol; return true; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override string GenerateNameForExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) => semanticModel.GenerateNameForExpression(expression, capitalize: false, cancellationToken: cancellationToken); protected override ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken) => InternalExtensions.DetermineParameterType(argument.Expression, semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; protected override IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => token.GetAncestor<ConstructorDeclarationSyntax>() is { } constructor ? semanticModel.GetDeclaredSymbol(constructor, cancellationToken) : null; protected override IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken) { if (constructor.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken) is ConstructorDeclarationSyntax constructorDeclarationSyntax && constructorDeclarationSyntax.Initializer.IsKind(SyntaxKind.ThisConstructorInitializer)) { return semanticModel.GetSymbolInfo(constructorDeclarationSyntax.Initializer, cancellationToken).Symbol as IMethodSymbol; } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.GenerateConstructor { [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared] internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ExpressionSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpGenerateConstructorService() { } protected override bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType) => containingType.ContainingTypesOrSelfHasUnsafeKeyword(); protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is SimpleNameSyntax; protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ConstructorInitializerSyntax; protected override bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) => node is ImplicitObjectCreationExpressionSyntax; protected override bool TryInitializeConstructorInitializerGeneration( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var constructorInitializer = (ConstructorInitializerSyntax)node; if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing) { token = constructorInitializer.ThisOrBaseKeyword; arguments = GetArguments(constructorInitializer.ArgumentList.Arguments); var semanticModel = document.SemanticModel; var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken); typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer) ? currentType : currentType.BaseType.OriginalDefinition; return typeToGenerateIn != null; } token = default; arguments = default; typeToGenerateIn = null; return false; } private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument(a.GetRefKind(), a.NameColon?.Name.Identifier.ValueText, a.Expression)); private static ImmutableArray<Argument> GetArguments(SeparatedSyntaxList<AttributeArgumentSyntax> arguments) => arguments.SelectAsArray(a => new Argument( refKind: RefKind.None, a.NameEquals?.Name.Identifier.ValueText ?? a.NameColon?.Name.Identifier.ValueText, a.Expression)); protected override bool TryInitializeSimpleNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is ObjectCreationExpressionSyntax objectCreationExpression) { if (objectCreationExpression.ArgumentList != null && !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken); token = simpleName.Identifier; arguments = GetArguments(objectCreationExpression.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol; return typeToGenerateIn != null; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleAttributeNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is AttributeSyntax attribute) { if (attribute.ArgumentList != null && !attribute.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty) { token = simpleName.Identifier; arguments = GetArguments(attribute.ArgumentList.Arguments); typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol; return typeToGenerateIn != null; } } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn) { var implicitObjectCreation = (ImplicitObjectCreationExpressionSyntax)node; if (implicitObjectCreation.ArgumentList != null && !implicitObjectCreation.ArgumentList.CloseParenToken.IsMissing) { var typeInfo = document.SemanticModel.GetTypeInfo(implicitObjectCreation, cancellationToken); if (typeInfo.Type is INamedTypeSymbol typeSymbol) { token = implicitObjectCreation.NewKeyword; arguments = GetArguments(implicitObjectCreation.ArgumentList.Arguments); typeToGenerateIn = typeSymbol; return true; } } token = default; arguments = default; typeToGenerateIn = null; return false; } protected override string GenerateNameForExpression(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken) => semanticModel.GenerateNameForExpression(expression, capitalize: false, cancellationToken: cancellationToken); protected override ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken) => InternalExtensions.DetermineParameterType(argument.Expression, semanticModel, cancellationToken); protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) => compilation.ClassifyConversion(sourceType, targetType).IsImplicit; protected override IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) => token.GetAncestor<ConstructorDeclarationSyntax>() is { } constructor ? semanticModel.GetDeclaredSymbol(constructor, cancellationToken) : null; protected override IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken) { if (constructor.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken) is ConstructorDeclarationSyntax constructorDeclarationSyntax && constructorDeclarationSyntax.Initializer.IsKind(SyntaxKind.ThisConstructorInitializer)) { return semanticModel.GetSymbolInfo(constructorDeclarationSyntax.Initializer, cancellationToken).Symbol as IMethodSymbol; } return null; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest2/Recommendations/RecordKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RecordKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord1() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord2() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { public $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord3() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { [X] $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicRecord() { await VerifyAbsenceAsync( @"public record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$ where U : T"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { // readonly record struct is allowed. await VerifyKeywordAsync("readonly $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class RecordKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCompilationUnit() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterExtern() { await VerifyKeywordAsync( @"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUsing() { await VerifyKeywordAsync( @"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalUsing() { await VerifyKeywordAsync( @"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNamespace() { await VerifyKeywordAsync( @"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterFileScopedNamespace() { await VerifyKeywordAsync( @"namespace N; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterTypeDeclaration() { await VerifyKeywordAsync( @"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateDeclaration() { await VerifyKeywordAsync( @"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"$$ global using Goo;"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAssemblyAttribute() { await VerifyKeywordAsync( @"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRootAttribute() { await VerifyKeywordAsync( @"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord1() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord2() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { public $$", absent: false, options: TestOptions.RegularPreview); } [WorkItem(50783, "https://github.com/dotnet/roslyn/issues/50783")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideRecord3() { // The recommender doesn't work in record in script // Tracked by https://github.com/dotnet/roslyn/issues/44865 await VerifyWorkerAsync( @"record C { [X] $$", absent: false, options: TestOptions.RegularPreview); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicRecord() { await VerifyAbsenceAsync( @"public record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAbstract() { await VerifyKeywordAsync( @"abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal() { await VerifyKeywordAsync( @"internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic() { await VerifyKeywordAsync( @"static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublicStatic() { await VerifyKeywordAsync( @"public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInvalidPublic() => await VerifyAbsenceAsync(@"virtual public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic() { await VerifyKeywordAsync( @"public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate() { await VerifyKeywordAsync( @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProtected() { await VerifyKeywordAsync( @"protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterSealed() { await VerifyKeywordAsync( @"sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStatic() { await VerifyKeywordAsync( @"static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInUsingDirective() { await VerifyAbsenceAsync( @"using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticInGlobalUsingDirective() { await VerifyAbsenceAsync( @"global using static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenUsings() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_01() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(32214, "https://github.com/dotnet/roslyn/issues/32214")] public async Task TestNotBetweenGlobalUsings_02() { // Recommendation in scripting is not stable. See https://github.com/dotnet/roslyn/issues/32214 await VerifyAbsenceAsync(SourceCodeKind.Regular, @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyAbsenceAsync( @"class C { void Goo<T>() where T : $$ where U : T"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonly() { // readonly record struct is allowed. await VerifyKeywordAsync("readonly $$"); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Analyzers/Core/CodeFixes/RemoveRedundantEquality/RemoveRedundantEqualityCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveRedundantEquality { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared] internal sealed class RemoveRedundantEqualityCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveRedundantEqualityCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix(new MyCodeAction( AnalyzersResources.Remove_redundant_equality, c => FixAsync(context.Document, diagnostic, c)), diagnostic); } return Task.CompletedTask; } protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); editor.ReplaceNode(node, (n, _) => { if (!syntaxFacts.IsBinaryExpression(n)) { // This should happen only in error cases. return n; } syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right); if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right) { return WithElasticTrailingTrivia(left); } else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left) { return WithElasticTrailingTrivia(right); } return n; }); } return; static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node) { return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic)); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.RemoveRedundantEquality { [ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared] internal sealed class RemoveRedundantEqualityCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveRedundantEqualityCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId); internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix(new MyCodeAction( AnalyzersResources.Remove_redundant_equality, c => FixAsync(context.Document, diagnostic, c)), diagnostic); } return Task.CompletedTask; } protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics) { var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true); editor.ReplaceNode(node, (n, _) => { if (!syntaxFacts.IsBinaryExpression(n)) { // This should happen only in error cases. return n; } syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right); if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right) { return WithElasticTrailingTrivia(left); } else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left) { return WithElasticTrailingTrivia(right); } return n; }); } return; static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node) { return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic)); } } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/SyntaxTreeIndex_Create.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal interface IDeclaredSymbolInfoFactoryService : ILanguageService { // `rootNamespace` is required for VB projects that has non-global namespace as root namespace, // otherwise we would not be able to get correct data from syntax. void AddDeclaredSymbolInfos(Document document, SyntaxNode root, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, CancellationToken cancellationToken); } internal sealed partial class SyntaxTreeIndex { // The probability of getting a false positive when calling ContainsIdentifier. private const double FalsePositiveProbability = 0.0001; public static readonly ObjectPool<HashSet<string>> StringLiteralHashSetPool = SharedPools.Default<HashSet<string>>(); public static readonly ObjectPool<HashSet<long>> LongLiteralHashSetPool = SharedPools.Default<HashSet<long>>(); /// <summary> /// String interning table so that we can share many more strings in our DeclaredSymbolInfo /// buckets. Keyed off a Project instance so that we share all these strings as we create /// the or load the index items for this a specific Project. This helps as we will generally /// be creating or loading all the index items for the documents in a Project at the same time. /// Once this project is let go of (which happens with any solution change) then we'll dump /// this string table. The table will have already served its purpose at that point and /// doesn't need to be kept around further. /// </summary> private static readonly ConditionalWeakTable<Project, StringTable> s_projectStringTable = new(); private static async Task<SyntaxTreeIndex> CreateIndexAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { Contract.ThrowIfFalse(document.SupportsSyntaxTree); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return CreateIndex(document, root, checksum, cancellationToken); } private static SyntaxTreeIndex CreateIndex( Document document, SyntaxNode root, Checksum checksum, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var infoFactory = document.GetRequiredLanguageService<IDeclaredSymbolInfoFactoryService>(); var ignoreCase = !syntaxFacts.IsCaseSensitive; var isCaseSensitive = !ignoreCase; GetIdentifierSet(ignoreCase, out var identifiers, out var escapedIdentifiers); var stringLiterals = StringLiteralHashSetPool.Allocate(); var longLiterals = LongLiteralHashSetPool.Allocate(); using var _1 = ArrayBuilder<DeclaredSymbolInfo>.GetInstance(out var declaredSymbolInfos); using var _2 = PooledDictionary<string, ArrayBuilder<int>>.GetInstance(out var extensionMethodInfo); try { var containsForEachStatement = false; var containsLockStatement = false; var containsUsingStatement = false; var containsQueryExpression = false; var containsThisConstructorInitializer = false; var containsBaseConstructorInitializer = false; var containsElementAccess = false; var containsIndexerMemberCref = false; var containsDeconstruction = false; var containsAwait = false; var containsTupleExpressionOrTupleType = false; var containsImplicitObjectCreation = false; var containsGlobalAttributes = false; var containsConversion = false; var predefinedTypes = (int)PredefinedType.None; var predefinedOperators = (int)PredefinedOperator.None; if (syntaxFacts != null) { foreach (var current in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true)) { if (current.IsNode) { var node = current.AsNode(); containsForEachStatement = containsForEachStatement || syntaxFacts.IsForEachStatement(node); containsLockStatement = containsLockStatement || syntaxFacts.IsLockStatement(node); containsUsingStatement = containsUsingStatement || syntaxFacts.IsUsingStatement(node); containsQueryExpression = containsQueryExpression || syntaxFacts.IsQueryExpression(node); containsElementAccess = containsElementAccess || syntaxFacts.IsElementAccessExpression(node); containsIndexerMemberCref = containsIndexerMemberCref || syntaxFacts.IsIndexerMemberCRef(node); containsDeconstruction = containsDeconstruction || syntaxFacts.IsDeconstructionAssignment(node) || syntaxFacts.IsDeconstructionForEachStatement(node); containsAwait = containsAwait || syntaxFacts.IsAwaitExpression(node); containsTupleExpressionOrTupleType = containsTupleExpressionOrTupleType || syntaxFacts.IsTupleExpression(node) || syntaxFacts.IsTupleType(node); containsImplicitObjectCreation = containsImplicitObjectCreation || syntaxFacts.IsImplicitObjectCreationExpression(node); containsGlobalAttributes = containsGlobalAttributes || syntaxFacts.IsGlobalAttribute(node); containsConversion = containsConversion || syntaxFacts.IsConversionExpression(node); } else { var token = (SyntaxToken)current; containsThisConstructorInitializer = containsThisConstructorInitializer || syntaxFacts.IsThisConstructorInitializer(token); containsBaseConstructorInitializer = containsBaseConstructorInitializer || syntaxFacts.IsBaseConstructorInitializer(token); if (syntaxFacts.IsIdentifier(token) || syntaxFacts.IsGlobalNamespaceKeyword(token)) { var valueText = token.ValueText; identifiers.Add(valueText); if (valueText.Length != token.Width()) { escapedIdentifiers.Add(valueText); } } if (syntaxFacts.TryGetPredefinedType(token, out var predefinedType)) { predefinedTypes |= (int)predefinedType; } if (syntaxFacts.TryGetPredefinedOperator(token, out var predefinedOperator)) { predefinedOperators |= (int)predefinedOperator; } if (syntaxFacts.IsStringLiteral(token)) { stringLiterals.Add(token.ValueText); } if (syntaxFacts.IsCharacterLiteral(token)) { longLiterals.Add((char)token.Value!); } if (syntaxFacts.IsNumericLiteral(token)) { var value = token.Value; switch (value) { case decimal d: // not supported for now. break; case double d: longLiterals.Add(BitConverter.DoubleToInt64Bits(d)); break; case float f: longLiterals.Add(BitConverter.DoubleToInt64Bits(f)); break; default: longLiterals.Add(IntegerUtilities.ToInt64(token.Value)); break; } } } } infoFactory.AddDeclaredSymbolInfos( document, root, declaredSymbolInfos, extensionMethodInfo, cancellationToken); } return new SyntaxTreeIndex( checksum, new LiteralInfo( new BloomFilter(FalsePositiveProbability, stringLiterals, longLiterals)), new IdentifierInfo( new BloomFilter(FalsePositiveProbability, isCaseSensitive, identifiers), new BloomFilter(FalsePositiveProbability, isCaseSensitive, escapedIdentifiers)), new ContextInfo( predefinedTypes, predefinedOperators, containsForEachStatement, containsLockStatement, containsUsingStatement, containsQueryExpression, containsThisConstructorInitializer, containsBaseConstructorInitializer, containsElementAccess, containsIndexerMemberCref, containsDeconstruction, containsAwait, containsTupleExpressionOrTupleType, containsImplicitObjectCreation, containsGlobalAttributes, containsConversion), new DeclarationInfo(declaredSymbolInfos.ToImmutable()), new ExtensionMethodInfo( extensionMethodInfo.ToImmutableDictionary( static kvp => kvp.Key, static kvp => kvp.Value.ToImmutable()))); } finally { Free(ignoreCase, identifiers, escapedIdentifiers); StringLiteralHashSetPool.ClearAndFree(stringLiterals); LongLiteralHashSetPool.ClearAndFree(longLiterals); foreach (var (_, builder) in extensionMethodInfo) builder.Free(); } } public static StringTable GetStringTable(Project project) => s_projectStringTable.GetValue(project, static _ => StringTable.GetInstance()); private static void GetIdentifierSet(bool ignoreCase, out HashSet<string> identifiers, out HashSet<string> escapedIdentifiers) { if (ignoreCase) { identifiers = SharedPools.StringIgnoreCaseHashSet.AllocateAndClear(); escapedIdentifiers = SharedPools.StringIgnoreCaseHashSet.AllocateAndClear(); Debug.Assert(identifiers.Comparer == StringComparer.OrdinalIgnoreCase); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.OrdinalIgnoreCase); return; } identifiers = SharedPools.StringHashSet.AllocateAndClear(); escapedIdentifiers = SharedPools.StringHashSet.AllocateAndClear(); Debug.Assert(identifiers.Comparer == StringComparer.Ordinal); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.Ordinal); } private static void Free(bool ignoreCase, HashSet<string> identifiers, HashSet<string> escapedIdentifiers) { if (ignoreCase) { Debug.Assert(identifiers.Comparer == StringComparer.OrdinalIgnoreCase); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.OrdinalIgnoreCase); SharedPools.StringIgnoreCaseHashSet.ClearAndFree(identifiers); SharedPools.StringIgnoreCaseHashSet.ClearAndFree(escapedIdentifiers); return; } Debug.Assert(identifiers.Comparer == StringComparer.Ordinal); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.Ordinal); SharedPools.StringHashSet.ClearAndFree(identifiers); SharedPools.StringHashSet.ClearAndFree(escapedIdentifiers); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { internal interface IDeclaredSymbolInfoFactoryService : ILanguageService { // `rootNamespace` is required for VB projects that has non-global namespace as root namespace, // otherwise we would not be able to get correct data from syntax. void AddDeclaredSymbolInfos(Document document, SyntaxNode root, ArrayBuilder<DeclaredSymbolInfo> declaredSymbolInfos, Dictionary<string, ArrayBuilder<int>> extensionMethodInfo, CancellationToken cancellationToken); } internal sealed partial class SyntaxTreeIndex { // The probability of getting a false positive when calling ContainsIdentifier. private const double FalsePositiveProbability = 0.0001; public static readonly ObjectPool<HashSet<string>> StringLiteralHashSetPool = SharedPools.Default<HashSet<string>>(); public static readonly ObjectPool<HashSet<long>> LongLiteralHashSetPool = SharedPools.Default<HashSet<long>>(); /// <summary> /// String interning table so that we can share many more strings in our DeclaredSymbolInfo /// buckets. Keyed off a Project instance so that we share all these strings as we create /// the or load the index items for this a specific Project. This helps as we will generally /// be creating or loading all the index items for the documents in a Project at the same time. /// Once this project is let go of (which happens with any solution change) then we'll dump /// this string table. The table will have already served its purpose at that point and /// doesn't need to be kept around further. /// </summary> private static readonly ConditionalWeakTable<Project, StringTable> s_projectStringTable = new(); private static async Task<SyntaxTreeIndex> CreateIndexAsync( Document document, Checksum checksum, CancellationToken cancellationToken) { Contract.ThrowIfFalse(document.SupportsSyntaxTree); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return CreateIndex(document, root, checksum, cancellationToken); } private static SyntaxTreeIndex CreateIndex( Document document, SyntaxNode root, Checksum checksum, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var infoFactory = document.GetRequiredLanguageService<IDeclaredSymbolInfoFactoryService>(); var ignoreCase = !syntaxFacts.IsCaseSensitive; var isCaseSensitive = !ignoreCase; GetIdentifierSet(ignoreCase, out var identifiers, out var escapedIdentifiers); var stringLiterals = StringLiteralHashSetPool.Allocate(); var longLiterals = LongLiteralHashSetPool.Allocate(); using var _1 = ArrayBuilder<DeclaredSymbolInfo>.GetInstance(out var declaredSymbolInfos); using var _2 = PooledDictionary<string, ArrayBuilder<int>>.GetInstance(out var extensionMethodInfo); try { var containsForEachStatement = false; var containsLockStatement = false; var containsUsingStatement = false; var containsQueryExpression = false; var containsThisConstructorInitializer = false; var containsBaseConstructorInitializer = false; var containsElementAccess = false; var containsIndexerMemberCref = false; var containsDeconstruction = false; var containsAwait = false; var containsTupleExpressionOrTupleType = false; var containsImplicitObjectCreation = false; var containsGlobalAttributes = false; var containsConversion = false; var predefinedTypes = (int)PredefinedType.None; var predefinedOperators = (int)PredefinedOperator.None; if (syntaxFacts != null) { foreach (var current in root.DescendantNodesAndTokensAndSelf(descendIntoTrivia: true)) { if (current.IsNode) { var node = current.AsNode(); containsForEachStatement = containsForEachStatement || syntaxFacts.IsForEachStatement(node); containsLockStatement = containsLockStatement || syntaxFacts.IsLockStatement(node); containsUsingStatement = containsUsingStatement || syntaxFacts.IsUsingStatement(node); containsQueryExpression = containsQueryExpression || syntaxFacts.IsQueryExpression(node); containsElementAccess = containsElementAccess || syntaxFacts.IsElementAccessExpression(node); containsIndexerMemberCref = containsIndexerMemberCref || syntaxFacts.IsIndexerMemberCRef(node); containsDeconstruction = containsDeconstruction || syntaxFacts.IsDeconstructionAssignment(node) || syntaxFacts.IsDeconstructionForEachStatement(node); containsAwait = containsAwait || syntaxFacts.IsAwaitExpression(node); containsTupleExpressionOrTupleType = containsTupleExpressionOrTupleType || syntaxFacts.IsTupleExpression(node) || syntaxFacts.IsTupleType(node); containsImplicitObjectCreation = containsImplicitObjectCreation || syntaxFacts.IsImplicitObjectCreationExpression(node); containsGlobalAttributes = containsGlobalAttributes || syntaxFacts.IsGlobalAttribute(node); containsConversion = containsConversion || syntaxFacts.IsConversionExpression(node); } else { var token = (SyntaxToken)current; containsThisConstructorInitializer = containsThisConstructorInitializer || syntaxFacts.IsThisConstructorInitializer(token); containsBaseConstructorInitializer = containsBaseConstructorInitializer || syntaxFacts.IsBaseConstructorInitializer(token); if (syntaxFacts.IsIdentifier(token) || syntaxFacts.IsGlobalNamespaceKeyword(token)) { var valueText = token.ValueText; identifiers.Add(valueText); if (valueText.Length != token.Width()) { escapedIdentifiers.Add(valueText); } } if (syntaxFacts.TryGetPredefinedType(token, out var predefinedType)) { predefinedTypes |= (int)predefinedType; } if (syntaxFacts.TryGetPredefinedOperator(token, out var predefinedOperator)) { predefinedOperators |= (int)predefinedOperator; } if (syntaxFacts.IsStringLiteral(token)) { stringLiterals.Add(token.ValueText); } if (syntaxFacts.IsCharacterLiteral(token)) { longLiterals.Add((char)token.Value!); } if (syntaxFacts.IsNumericLiteral(token)) { var value = token.Value; switch (value) { case decimal d: // not supported for now. break; case double d: longLiterals.Add(BitConverter.DoubleToInt64Bits(d)); break; case float f: longLiterals.Add(BitConverter.DoubleToInt64Bits(f)); break; default: longLiterals.Add(IntegerUtilities.ToInt64(token.Value)); break; } } } } infoFactory.AddDeclaredSymbolInfos( document, root, declaredSymbolInfos, extensionMethodInfo, cancellationToken); } return new SyntaxTreeIndex( checksum, new LiteralInfo( new BloomFilter(FalsePositiveProbability, stringLiterals, longLiterals)), new IdentifierInfo( new BloomFilter(FalsePositiveProbability, isCaseSensitive, identifiers), new BloomFilter(FalsePositiveProbability, isCaseSensitive, escapedIdentifiers)), new ContextInfo( predefinedTypes, predefinedOperators, containsForEachStatement, containsLockStatement, containsUsingStatement, containsQueryExpression, containsThisConstructorInitializer, containsBaseConstructorInitializer, containsElementAccess, containsIndexerMemberCref, containsDeconstruction, containsAwait, containsTupleExpressionOrTupleType, containsImplicitObjectCreation, containsGlobalAttributes, containsConversion), new DeclarationInfo(declaredSymbolInfos.ToImmutable()), new ExtensionMethodInfo( extensionMethodInfo.ToImmutableDictionary( static kvp => kvp.Key, static kvp => kvp.Value.ToImmutable()))); } finally { Free(ignoreCase, identifiers, escapedIdentifiers); StringLiteralHashSetPool.ClearAndFree(stringLiterals); LongLiteralHashSetPool.ClearAndFree(longLiterals); foreach (var (_, builder) in extensionMethodInfo) builder.Free(); } } public static StringTable GetStringTable(Project project) => s_projectStringTable.GetValue(project, static _ => StringTable.GetInstance()); private static void GetIdentifierSet(bool ignoreCase, out HashSet<string> identifiers, out HashSet<string> escapedIdentifiers) { if (ignoreCase) { identifiers = SharedPools.StringIgnoreCaseHashSet.AllocateAndClear(); escapedIdentifiers = SharedPools.StringIgnoreCaseHashSet.AllocateAndClear(); Debug.Assert(identifiers.Comparer == StringComparer.OrdinalIgnoreCase); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.OrdinalIgnoreCase); return; } identifiers = SharedPools.StringHashSet.AllocateAndClear(); escapedIdentifiers = SharedPools.StringHashSet.AllocateAndClear(); Debug.Assert(identifiers.Comparer == StringComparer.Ordinal); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.Ordinal); } private static void Free(bool ignoreCase, HashSet<string> identifiers, HashSet<string> escapedIdentifiers) { if (ignoreCase) { Debug.Assert(identifiers.Comparer == StringComparer.OrdinalIgnoreCase); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.OrdinalIgnoreCase); SharedPools.StringIgnoreCaseHashSet.ClearAndFree(identifiers); SharedPools.StringIgnoreCaseHashSet.ClearAndFree(escapedIdentifiers); return; } Debug.Assert(identifiers.Comparer == StringComparer.Ordinal); Debug.Assert(escapedIdentifiers.Comparer == StringComparer.Ordinal); SharedPools.StringHashSet.ClearAndFree(identifiers); SharedPools.StringHashSet.ClearAndFree(escapedIdentifiers); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/CoreTest/SolutionTests/SolutionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Threading; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.Workspace)] public class SolutionTests : TestBase { #nullable enable private static readonly MetadataReference s_mscorlib = TestMetadata.Net451.mscorlib; private static readonly DocumentId s_unrelatedDocumentId = DocumentId.CreateNewId(ProjectId.CreateNewId()); private static Workspace CreateWorkspaceWithProjectAndDocuments() { var projectId = ProjectId.CreateNewId(); var workspace = CreateWorkspace(); Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", "text") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"), filePath: "/a/b"))); return workspace; } private static IEnumerable<T> EmptyEnumerable<T>() { yield break; } // Returns an enumerable that can only be enumerated once. private static IEnumerable<T> OnceEnumerable<T>(params T[] items) => OnceEnumerableImpl(new StrongBox<int>(), items); private static IEnumerable<T> OnceEnumerableImpl<T>(StrongBox<int> counter, T[] items) { Assert.Equal(0, counter.Value); counter.Value++; foreach (var item in items) { yield return item; } } [Fact] public void RemoveDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAdditionalDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAdditionalDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAnalyzerConfigDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAnalyzerConfigDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void WithDocumentName() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var name = "new name"; var newSolution1 = solution.WithDocumentName(documentId, name); Assert.Equal(name, newSolution1.GetDocument(documentId)!.Name); var newSolution2 = newSolution1.WithDocumentName(documentId, name); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(documentId, name: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(null!, name)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentName(s_unrelatedDocumentId, name)); } [Fact] public void WithDocumentFolders() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var folders = new[] { "folder1", "folder2" }; var newSolution1 = solution.WithDocumentFolders(documentId, folders); Assert.Equal(folders, newSolution1.GetDocument(documentId)!.Folders); var newSolution2 = newSolution1.WithDocumentFolders(documentId, folders); Assert.Same(newSolution2, newSolution1); // empty: var newSolution3 = solution.WithDocumentFolders(documentId, new string[0]); Assert.Equal(new string[0], newSolution3.GetDocument(documentId)!.Folders); var newSolution4 = solution.WithDocumentFolders(documentId, ImmutableArray<string>.Empty); Assert.Same(newSolution3, newSolution4); var newSolution5 = solution.WithDocumentFolders(documentId, null); Assert.Same(newSolution3, newSolution5); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(documentId, folders: new string[] { null! })); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(null!, folders)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFolders(s_unrelatedDocumentId, folders)); } [Fact] [WorkItem(34837, "https://github.com/dotnet/roslyn/issues/34837")] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/37125")] public void WithDocumentFilePath() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var path = "new path"; var newSolution1 = solution.WithDocumentFilePath(documentId, path); Assert.Equal(path, newSolution1.GetDocument(documentId)!.FilePath); AssertEx.Equal(new[] { documentId }, newSolution1.GetDocumentIdsWithFilePath(path)); var newSolution2 = newSolution1.WithDocumentFilePath(documentId, path); Assert.Same(newSolution1, newSolution2); // empty path (TODO https://github.com/dotnet/roslyn/issues/37125): var newSolution3 = solution.WithDocumentFilePath(documentId, ""); Assert.Equal("", newSolution3.GetDocument(documentId)!.FilePath); Assert.Empty(newSolution3.GetDocumentIdsWithFilePath("")); // TODO: https://github.com/dotnet/roslyn/issues/37125 Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(documentId, filePath: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(null!, path)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFilePath(s_unrelatedDocumentId, path)); } [Fact] public void WithSourceCodeKind() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); Assert.Same(solution, solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Regular)); var newSolution1 = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, newSolution1.GetDocument(documentId)!.SourceCodeKind); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSourceCodeKind(documentId, (SourceCodeKind)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSourceCodeKind(null!, SourceCodeKind.Script)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSourceCodeKind(s_unrelatedDocumentId, SourceCodeKind.Script)); } [Fact, Obsolete] public void WithSourceCodeKind_Obsolete() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var newSolution = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Interactive); Assert.Equal(SourceCodeKind.Script, newSolution.GetDocument(documentId)!.SourceCodeKind); } [Fact] public void WithDocumentSyntaxRoot() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var root = CS.SyntaxFactory.ParseSyntaxTree("class NewClass {}").GetRoot(); var newSolution1 = solution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetSyntaxRoot(out var actualRoot)); Assert.Equal(root.ToString(), actualRoot!.ToString()); // the actual root has a new parent SyntaxTree: Assert.NotSame(root, actualRoot); var newSolution2 = newSolution1.WithDocumentSyntaxRoot(documentId, actualRoot); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSyntaxRoot(documentId, root, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSyntaxRoot(null!, root)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSyntaxRoot(s_unrelatedDocumentId, root)); } [Fact] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/41940")] public async Task WithDocumentSyntaxRoot_AnalyzerConfigWithoutFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config")); var project = solution.GetProject(projectId)!; var compilation = (await project.GetCompilationAsync())!; var tree = compilation.SyntaxTrees.Single(); var provider = compilation.Options.SyntaxTreeOptionsProvider!; Assert.Throws<ArgumentException>(() => provider.TryGetDiagnosticValue(tree, "CA1234", CancellationToken.None, out _)); } [Fact] public void WithDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_MultipleDocuments() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); // documents not in solution are skipped: https://github.com/dotnet/roslyn/issues/42029 Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { null! }, text)); Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { s_unrelatedDocumentId }, text)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId[])null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(new[] { documentId }, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(new[] { documentId }, text, (PreservationMode)(-1))); } [Fact] public void WithAdditionalDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAdditionalDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAnalyzerConfigDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithProjectAssemblyName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var assemblyName = "\0<>a/b/*.dll"; var newSolution = solution.WithProjectAssemblyName(projectId, assemblyName); Assert.Equal(assemblyName, newSolution.GetProject(projectId)!.AssemblyName); Assert.Same(newSolution, newSolution.WithProjectAssemblyName(projectId, assemblyName)); Assert.Throws<ArgumentNullException>("assemblyName", () => solution.WithProjectAssemblyName(projectId, null!)); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAssemblyName(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAssemblyName(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputFilePath(projectId, value), s => s.GetProject(projectId)!.OutputFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputRefFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputRefFilePath(projectId, value), s => s.GetProject(projectId)!.OutputRefFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputRefFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputRefFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectCompilationOutputInfo() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectCompilationOutputInfo(projectId, value), s => s.GetProject(projectId)!.CompilationOutputInfo, new CompilationOutputInfo(path), defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOutputInfo(null!, new CompilationOutputInfo("x.dll"))); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOutputInfo(ProjectId.CreateNewId(), new CompilationOutputInfo("x.dll"))); } [Fact] public void WithProjectDefaultNamespace() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var defaultNamespace = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectDefaultNamespace(projectId, value), s => s.GetProject(projectId)!.DefaultNamespace, (string?)defaultNamespace, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectDefaultNamespace(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectDefaultNamespace(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var projectName = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectName(projectId, value), s => s.GetProject(projectId)!.Name, projectName, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectName(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectName(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.csproj"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectFilePath(projectId, value), s => s.GetProject(projectId)!.FilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectFilePath(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectFilePath(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectCompilationOptionsExceptionHandling() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpCompilationOptions(OutputKind.NetModule); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOptions(ProjectId.CreateNewId(), options)); } [Theory] [CombinatorialData] public void WithProjectCompilationOptionsReplacesSyntaxTreeOptionProvider([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", languageName); // We always have a non-null SyntaxTreeOptionsProvider for C# and VB projects var originalSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(originalSyntaxTreeOptionsProvider); var defaultOptions = solution.Projects.Single().LanguageServices.GetRequiredService<ICompilationFactoryService>().GetDefaultCompilationOptions(); Assert.Null(defaultOptions.SyntaxTreeOptionsProvider); solution = solution.WithProjectCompilationOptions(projectId, defaultOptions); // The CompilationOptions we replaced with didn't have a SyntaxTreeOptionsProvider, but we would have placed it // back. The SyntaxTreeOptionsProvider should behave the same as the prior one and thus should be equal. var newSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(newSyntaxTreeOptionsProvider); Assert.Equal(originalSyntaxTreeOptionsProvider, newSyntaxTreeOptionsProvider); } [Fact] public void WithProjectParseOptions() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpParseOptions(CS.LanguageVersion.CSharp1); SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectParseOptions(projectId, value), s => s.GetProject(projectId)!.ParseOptions!, (ParseOptions)options, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectParseOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectParseOptions(ProjectId.CreateNewId(), options)); } [Fact] public void WithProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef = new ProjectReference(projectId2); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectReferences(projectId, value), opt => opt.GetProject(projectId)!.AllProjectReferences, projectRef, allowDuplicates: false); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create( new ProjectReference(projectId2), new ProjectReference(projectId2, ImmutableArray.Create("alias")), new ProjectReference(projectId2, embedInteropTypes: true)); var solution2 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, solution2.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectReferences(null!, new[] { projectRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(ProjectId.CreateNewId(), new[] { projectRef })); // cycles: Assert.Throws<InvalidOperationException>(() => solution2.WithProjectReferences(projectId2, new[] { new ProjectReference(projectId) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] [WorkItem(42406, "https://github.com/dotnet/roslyn/issues/42406")] public void WithProjectReferences_ProjectNotInSolution() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(externalProjectRef); var newSolution1 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, newSolution1.GetProject(projectId)!.AllProjectReferences); // project reference is not included: Assert.Empty(newSolution1.GetProject(projectId)!.ProjectReferences); } [Fact] public void AddProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp) .AddProject(projectId3, "proj3", "proj3.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var projectRef3 = new ProjectReference(projectId3); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.AddProjectReference(projectId3, projectRef2); var solution2 = solution.AddProjectReferences(projectId, EmptyEnumerable<ProjectReference>()); Assert.Same(solution, solution2); var e = OnceEnumerable(projectRef2, externalProjectRef); var solution3 = solution.AddProjectReferences(projectId, e); AssertEx.Equal(new[] { projectRef2 }, solution3.GetProject(projectId)!.ProjectReferences); AssertEx.Equal(new[] { projectRef2, externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddProjectReferences(null!, new[] { projectRef2 })); Assert.Throws<ArgumentNullException>("projectReferences", () => solution.AddProjectReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("projectReferences[0]", () => solution.AddProjectReferences(projectId, new ProjectReference[] { null! })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { projectRef2, projectRef2 })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { new ProjectReference(projectId2), new ProjectReference(projectId2) })); // dup: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId3, new[] { projectRef2 })); // cycles: Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId2, new[] { projectRef3 })); Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] public void RemoveProjectReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.WithProjectReferences(projectId, new[] { projectRef2, externalProjectRef }); // remove reference to a project that's not part of the solution: var solution2 = solution.RemoveProjectReference(projectId, externalProjectRef); AssertEx.Equal(new[] { projectRef2 }, solution2.GetProject(projectId)!.AllProjectReferences); // remove reference to a project that's part of the solution: var solution3 = solution.RemoveProjectReference(projectId, projectRef2); AssertEx.Equal(new[] { externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); var solution4 = solution3.RemoveProjectReference(projectId, externalProjectRef); Assert.Empty(solution4.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveProjectReference(null!, projectRef2)); Assert.Throws<ArgumentNullException>("projectReference", () => solution.RemoveProjectReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<ArgumentException>("projectReference", () => solution.RemoveProjectReference(projectId, new ProjectReference(ProjectId.CreateNewId()))); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveProjectReference(ProjectId.CreateNewId(), projectRef2)); } [Fact] public void ProjectReferences_Submissions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId0 = ProjectId.CreateNewId(); var submissionId1 = ProjectId.CreateNewId(); var submissionId2 = ProjectId.CreateNewId(); var submissionId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId0, "non-submission", "non-submission.dll", LanguageNames.CSharp) .AddProject(ProjectInfo.Create(submissionId1, VersionStamp.Default, name: "submission1", assemblyName: "submission1.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId2, VersionStamp.Default, name: "submission2", assemblyName: "submission2.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId3, VersionStamp.Default, name: "submission3", assemblyName: "submission3.dll", LanguageNames.CSharp, isSubmission: true)) .AddProjectReference(submissionId2, new ProjectReference(submissionId1)) .WithProjectReferences(submissionId2, new[] { new ProjectReference(submissionId1) }); // submission may be referenced from multiple submissions (forming a tree): _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); // submission may reference a non-submission project: _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); // submission can't reference multiple submissions: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(submissionId2, new[] { new ProjectReference(submissionId3) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(submissionId1, new[] { new ProjectReference(submissionId2), new ProjectReference(submissionId3) })); // non-submission project can't reference a submission: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); } [Fact] public void WithProjectMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef = (MetadataReference)new TestMetadataReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectMetadataReferences(projectId, value), opt => opt.GetProject(projectId)!.MetadataReferences, metadataRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectMetadataReferences(null!, new[] { metadataRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectMetadataReferences(ProjectId.CreateNewId(), new[] { metadataRef })); } [Fact] public void AddMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddMetadataReferences(projectId, EmptyEnumerable<MetadataReference>()); Assert.Same(solution, solution2); var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); var solution3 = solution.AddMetadataReferences(projectId, OnceEnumerable(metadataRef1, metadataRef2)); AssertEx.Equal(new[] { metadataRef1, metadataRef2 }, solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddMetadataReferences(null!, new[] { metadataRef1 })); Assert.Throws<ArgumentNullException>("metadataReferences", () => solution.AddMetadataReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("metadataReferences[0]", () => solution.AddMetadataReferences(projectId, new MetadataReference[] { null! })); Assert.Throws<ArgumentException>("metadataReferences[1]", () => solution.AddMetadataReferences(projectId, new[] { metadataRef1, metadataRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddMetadataReferences(projectId, new[] { metadataRef1 })); } [Fact] public void RemoveMetadataReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); solution = solution.WithProjectMetadataReferences(projectId, new[] { metadataRef1, metadataRef2 }); var solution2 = solution.RemoveMetadataReference(projectId, metadataRef1); AssertEx.Equal(new[] { metadataRef2 }, solution2.GetProject(projectId)!.MetadataReferences); var solution3 = solution2.RemoveMetadataReference(projectId, metadataRef2); Assert.Empty(solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveMetadataReference(null!, metadataRef1)); Assert.Throws<ArgumentNullException>("metadataReference", () => solution.RemoveMetadataReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(projectId, new TestMetadataReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(ProjectId.CreateNewId(), metadataRef1)); } [Fact] public void WithProjectAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectAnalyzerReferences(projectId, value), opt => opt.GetProject(projectId)!.AnalyzerReferences, analyzerRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAnalyzerReferences(null!, new[] { analyzerRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAnalyzerReferences(ProjectId.CreateNewId(), new[] { analyzerRef })); } [Fact] public void AddAnalyzerReferences_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddAnalyzerReferences(projectId, EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(projectId, OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.GetProject(projectId)!.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(projectId, new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddAnalyzerReferences(null!, new[] { analyzerRef1 })); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(projectId, new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(projectId, new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithProjectAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(projectId, analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.GetProject(projectId)!.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(projectId, analyzerRef2); Assert.Empty(solution3.GetProject(projectId)!.AnalyzerReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveAnalyzerReference(null!, analyzerRef1)); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(projectId, new TestAnalyzerReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(ProjectId.CreateNewId(), analyzerRef1)); } [Fact] public void WithAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithAnalyzerReferences(value), opt => opt.AnalyzerReferences, analyzerRef, allowDuplicates: false); } [Fact] public void AddAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var solution2 = solution.AddAnalyzerReferences(EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithAnalyzerReferences(new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(analyzerRef2); Assert.Empty(solution3.AnalyzerReferences); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(new TestAnalyzerReference())); } #nullable disable [Fact] public void TestAddProject() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(solution.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.False(project.HasDocuments); } [Fact] public void TestUpdateAssemblyName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.WithProjectAssemblyName(project1, "bar"); var project = solution.GetProject(project1); Assert.Equal("bar", project.AssemblyName); } [Fact] [WorkItem(543964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543964")] public void MultipleProjectsWithSameDisplayName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); var project2 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp); solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp); Assert.Equal(2, solution.GetProjectsByName("name").Count()); } [Fact] public async Task TestAddFirstDocumentAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); // verify project & document Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.NotNull(project); Assert.True(solution.ContainsProject(pid), "Solution was expected to have project " + pid); Assert.True(project.HasDocuments, "Project was expected to have documents"); Assert.Equal(project, solution.GetProject(pid)); Assert.NotNull(did); var document = solution.GetDocument(did); Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did); Assert.Equal(document, project.GetDocument(did)); Assert.Equal(document, solution.GetDocument(did)); var semantics = await document.GetSemanticModelAsync(); Assert.NotNull(semantics); await ValidateSolutionAndCompilationsAsync(solution); var pid2 = solution.Projects.Single().Id; var did2 = DocumentId.CreateNewId(pid2); solution = solution.AddDocument(did2, "bar.cs", "public class Bar { }"); // verify project & document var project2 = solution.GetProject(pid2); Assert.NotNull(project2); Assert.NotNull(did2); var document2 = solution.GetDocument(did2); Assert.True(project2.ContainsDocument(did2), "Project was expected to have document " + did2); Assert.Equal(document2, project2.GetDocument(did2)); Assert.Equal(document2, solution.GetDocument(did2)); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForSingleProject() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project = Assert.Single(solution.Projects); var document1 = project.GetDocument(documentInfo1.Id); var document2 = project.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForTwoProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project1 = solution.GetProject(projectId1); var project2 = solution.GetProject(projectId2); var document1 = project1.GetDocument(documentInfo1.Id); var document2 = project2.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); Assert.NotSame(document1.Project, document2.Project); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public void AddTwoDocumentsWithMissingProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); // We're only adding the first project, but not the second one using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp); Assert.ThrowsAny<InvalidOperationException>(() => solution.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2))); } [Fact] public void RemoveZeroDocuments() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Same(solution, solution.RemoveDocuments(ImmutableArray<DocumentId>.Empty)); } [Fact] public async Task RemoveTwoDocuments() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "project1", "project1.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); var finalProject = solution.Projects.Single(); Assert.Empty(finalProject.Documents); Assert.Empty((await finalProject.GetCompilationAsync()).SyntaxTrees); } [Fact] public void RemoveTwoDocumentsFromDifferentProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); Assert.All(solution.Projects, p => Assert.Single(p.Documents)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); Assert.All(solution.Projects, p => Assert.Empty(p.Documents)); } [Fact] public void RemoveDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAdditionalDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.txt"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAdditionalDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAdditionalDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAnalyzerConfigDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), ".editorconfig"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1)); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public async Task TestOneCSharpProjectAsync() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject("goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(s_mscorlib) .AddDocument("goo.cs", "public class Goo { }") .Project.Solution; await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestTwoCSharpProjectsAsync() { using var workspace = CreateWorkspace(); var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); var doc1 = DocumentId.CreateNewId(pm1); var doc2 = DocumentId.CreateNewId(pm2); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(doc1, "goo.cs", "public class Goo { }") .AddDocument(doc2, "bar.cs", "public class Bar : Goo { }"); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestCrossLanguageProjectsAsync() { var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(pm1, s_mscorlib) .AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic) .AddMetadataReference(pm2, s_mscorlib) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(DocumentId.CreateNewId(pm1), "goo.cs", "public class X { }") .AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class"); await ValidateSolutionAndCompilationsAsync(solution); } private static async Task ValidateSolutionAndCompilationsAsync(Solution solution) { foreach (var project in solution.Projects) { Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id); Assert.Equal(project, solution.GetProject(project.Id)); // these won't always be unique in real-world but should be for these tests Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault()); var compilation = await project.GetCompilationAsync(); Assert.NotNull(compilation); // check that the options are the same Assert.Equal(project.CompilationOptions, compilation.Options); // check that all known metadata references are present in the compilation foreach (var meta in project.MetadataReferences) { Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta); } // check that all project-to-project reference metadata is present in the compilation foreach (var referenced in project.ProjectReferences) { if (solution.ContainsProject(referenced.ProjectId)) { var referencedMetadata = await solution.State.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None); Assert.NotNull(referencedMetadata); if (referencedMetadata is CompilationReference compilationReference) { compilation.References.Single(r => { var cr = r as CompilationReference; return cr != null && cr.Compilation == compilationReference.Compilation; }); } } } // check that the syntax trees are the same var docs = project.Documents.ToList(); var trees = compilation.SyntaxTrees.ToList(); Assert.Equal(docs.Count, trees.Count); foreach (var doc in docs) { Assert.True(trees.Contains(await doc.GetSyntaxTreeAsync()), "trees list was expected to contain the syntax tree of doc"); } } } #if false [Fact(Skip = "641963")] public void TestDeepProjectReferenceTree() { int projectCount = 5; var solution = CreateSolutionWithProjectDependencyChain(projectCount); ProjectId[] projectIds = solution.ProjectIds.ToArray(); Compilation compilation; for (int i = 0; i < projectCount; i++) { Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation)); } var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result; var partialSolution = solution.GetPartialSolution(); for (int i = 0; i < projectCount; i++) { // While holding a compilation, we also hold its references, plus one further level // of references alive. However, the references are only partial Declaration // compilations var isPartialAvailable = i >= projectCount - 3; var isFinalAvailable = i == projectCount - 1; var projectId = projectIds[i]; Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation)); Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation)); } } #endif [WorkItem(636431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636431")] [Fact] public async Task TestProjectDependencyLoadingAsync() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var projectIds = Enumerable.Range(0, 5).Select(i => ProjectId.CreateNewId()).ToArray(); for (var i = 0; i < projectIds.Length; i++) { solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp); if (i >= 1) { solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1])); } } await solution.GetProject(projectIds[0]).GetCompilationAsync(CancellationToken.None); await solution.GetProject(projectIds[2]).GetCompilationAsync(CancellationToken.None); } [Fact] public async Task TestAddMetadataReferencesAsync() { var mefReference = TestMetadata.Net451.SystemCore; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); solution = solution.AddMetadataReference(project1, mefReference); var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None); var foundSymbol = from symbol in namespacesAndTypes where symbol.Name.Equals("Enumerable") select symbol; Assert.Equal(1, foundSymbol.Count()); solution = solution.RemoveMetadataReference(project1, mefReference); assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); Assert.Null(assemblyReference); await ValidateSolutionAndCompilationsAsync(solution); } private class MockDiagnosticAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext analysisContext) { } } [Fact] public void TestProjectDiagnosticAnalyzers() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); Assert.Empty(solution.Projects.Single().AnalyzerReferences); DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer(); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); // Test AddAnalyzer var newSolution = solution.AddAnalyzerReference(project1, analyzerReference); var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages(); Assert.Equal(1, actualAnalyzers.Length); Assert.Equal(analyzer, actualAnalyzers[0]); // Test ProjectChanges var changes = newSolution.GetChanges(solution).GetProjectChanges().Single(); var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single(); Assert.Equal(analyzerReference, addedAnalyzerReference); var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences(); Assert.Empty(removedAnalyzerReferences); solution = newSolution; // Test RemoveAnalyzer solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Empty(actualAnalyzerReferences); // Test AddAnalyzers analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer(); var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer)); var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference }; solution = solution.AddAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]); // Test WithAnalyzers solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); } [Fact] public void TestProjectParseOptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); // Parse Options var oldParseOptions = solution.GetProject(project1).ParseOptions; var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" }); solution = solution.WithProjectParseOptions(project1, newParseOptions); var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions; Assert.NotEqual(oldParseOptions, newUpdatedParseOptions); Assert.Same(newParseOptions, newUpdatedParseOptions); } [Fact] public async Task TestRemoveProjectAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = sol.GetProject(pid); Assert.False(project.HasDocuments); var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ProjectIds.Any()); await ValidateSolutionAndCompilationsAsync(sol); } [Fact] public async Task TestRemoveProjectWithReferencesAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced // this should leave a dangling reference var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid); await ValidateSolutionAndCompilationsAsync(sol2); } [Fact] public async Task TestRemoveProjectWithReferencesAndAddItBackAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid); var sol3 = sol2.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid); Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2); Assert.Equal(2, sol3.Projects.Count()); await ValidateSolutionAndCompilationsAsync(sol3); } [Fact] public async Task TestGetSyntaxRootAsync() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); Assert.False(document.TryGetSyntaxRoot(out _)); var root = await document.GetSyntaxRootAsync(); Assert.NotNull(root); Assert.Equal(text, root.ToString()); Assert.True(document.TryGetSyntaxRoot(out root)); Assert.NotNull(root); } [Fact] public async Task TestUpdateDocumentAsync() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); using var workspace = CreateWorkspace(); var solution1 = workspace.CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", SourceText.From("class Class{}")); var document = solution1.GetDocument(documentId); var newRoot = await Formatter.FormatAsync(document).Result.GetSyntaxRootAsync(); var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot); Assert.NotEqual(solution1, solution2); var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString(); Assert.Equal("class Class { }", newText); } [Fact] public void TestUpdateSyntaxTreeWithAnnotations() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); var tree = document.GetSyntaxTreeAsync().Result; var root = tree.GetRoot(); var annotation = new SyntaxAnnotation(); var annotatedRoot = root.WithAdditionalAnnotations(annotation); var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot); var doc2 = sol2.GetDocument(did); var tree2 = doc2.GetSyntaxTreeAsync().Result; var root2 = tree2.GetRoot(); // text should not be available yet (it should be defer created from the node) // and getting the document or root should not cause it to be created. Assert.False(tree2.TryGetText(out _)); var text2 = tree2.GetText(); Assert.NotNull(text2); Assert.NotSame(tree, tree2); Assert.NotSame(annotatedRoot, root2); Assert.True(annotatedRoot.IsEquivalentTo(root2)); Assert.True(root2.HasAnnotation(annotation)); } [Fact] public void TestUpdatingFilePathUpdatesSyntaxTree() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); const string OldFilePath = @"Z:\OldFilePath.cs"; const string NewFilePath = @"Z:\NewFilePath.cs"; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(documentId, "OldFilePath.cs", "public class Goo { }", filePath: OldFilePath); // scope so later asserts don't accidentally use oldDocument { var oldDocument = solution.GetDocument(documentId); Assert.Equal(OldFilePath, oldDocument.FilePath); Assert.Equal(OldFilePath, oldDocument.GetSyntaxTreeAsync().Result.FilePath); } solution = solution.WithDocumentFilePath(documentId, NewFilePath); { var newDocument = solution.GetDocument(documentId); Assert.Equal(NewFilePath, newDocument.FilePath); Assert.Equal(NewFilePath, newDocument.GetSyntaxTreeAsync().Result.FilePath); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestSyntaxRootNotKeptAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); var observedRoot = GetObservedSyntaxTreeRoot(sol, did); observedRoot.AssertReleased(); // re-get the tree (should recover from storage, not reparse) _ = sol.GetDocument(did).GetSyntaxRootAsync().Result; } [MethodImpl(MethodImplOptions.NoInlining)] [Fact] [WorkItem(542736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542736")] public void TestDocumentChangedOnDiskIsNotObserved() { var text1 = "public class A {}"; var text2 = "public class B {}"; var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8); // create a solution that evicts from the cache immediately. using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var observedText = GetObservedText(sol, did, text1); // change text on disk & verify it is changed file.WriteAllText(text2); var textOnDisk = file.ReadAllText(); Assert.Equal(text2, textOnDisk); // stop observing it and let GC reclaim it observedText.AssertReleased(); // if we ask for the same text again we should get the original content var observedText2 = sol.GetDocument(did).GetTextAsync().Result; Assert.Equal(text1, observedText2.ToString()); } [Fact] public void TestGetTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19427")] public void TestGetRecoveredTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); // get it async and force it to recover from temporary storage var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetSyntaxTreeAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromAddedTree() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None); tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test")); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", tree); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docTree); Assert.True(tree.IsEquivalentTo(docTree)); Assert.NotNull(docTree.GetAnnotatedNodes("test").Single()); } [Fact] public async Task TestGetSyntaxRootAsync2Async() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docRoot = await doc.GetSyntaxRootAsync(); Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14954")] public void TestGetRecoveredSyntaxRootAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the syntax tree root and wait for the references to be GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); // get it async and force it to be recovered from storage var doc = sol.GetDocument(did); var docRoot = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact] public void TestGetCompilationAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var proj = sol.GetProject(pid); var compilation = proj.GetCompilationAsync().Result; Assert.NotNull(compilation); Assert.Equal(1, compilation.SyntaxTrees.Count()); } [Fact] public void TestGetSemanticModelAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docModel = doc.GetSemanticModelAsync().Result; Assert.NotNull(docModel); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextAsyncDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedTextAsync(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13506")] [WorkItem(13506, "https://github.com/dotnet/roslyn/issues/13506")] public void TestRecoverableSyntaxTreeCSharp() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"public class C { public void Method1() {} public void Method2() {} public void Method3() {} public void Method4() {} public void Method5() {} public void Method6() {} }"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); TestRecoverableSyntaxTree(sol, did); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestRecoverableSyntaxTreeVisualBasic() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"Public Class C Sub Method1() End Sub Sub Method2() End Sub Sub Method3() End Sub Sub Method4() End Sub Sub Method5() End Sub Sub Method6() End Sub End Class"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.VisualBasic) .AddDocument(did, "goo.vb", text); TestRecoverableSyntaxTree(sol, did); } private static void TestRecoverableSyntaxTree(Solution sol, DocumentId did) { // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); var doc = sol.GetDocument(did); // access the tree & root again (recover it) var tree = doc.GetSyntaxTreeAsync().Result; // this should cause reparsing var root = tree.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree, root.SyntaxTree); // reset the syntax root, to make it 'refactored' by adding an attribute var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation); var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id); // get it async and wait for it to get GC'd var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did); observed2.AssertReleased(); // access the tree & root again (recover it) var tree2 = doc2.GetSyntaxTreeAsync().Result; // this should cause deserialization var root2 = tree2.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree2, root2.SyntaxTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationAsyncDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilationAsync(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilationAsync(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilation(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilation(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [Fact] public void TestWorkspaceLanguageServiceOverride() { var hostServices = FeaturesTestCompositions.Features.AddParts(new[] { typeof(TestLanguageServiceA), typeof(TestLanguageServiceB), }).GetHostServices(); var ws = new AdhocWorkspace(hostServices, ServiceLayer.Host); var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service as TestLanguageServiceA); var ws2 = new AdhocWorkspace(hostServices, "Quasimodo"); var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service2 as TestLanguageServiceB); } #if false [Fact] public void TestSolutionInfo() { var oldSolutionId = SolutionId.CreateNewId("oldId"); var oldVersion = VersionStamp.Create(); var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null); var newSolutionId = SolutionId.CreateNewId("newId"); solutionInfo = solutionInfo.WithId(newSolutionId); Assert.NotEqual(oldSolutionId, solutionInfo.Id); Assert.Equal(newSolutionId, solutionInfo.Id); var newVersion = oldVersion.GetNewerVersion(); solutionInfo = solutionInfo.WithVersion(newVersion); Assert.NotEqual(oldVersion, solutionInfo.Version); Assert.Equal(newVersion, solutionInfo.Version); Assert.Null(solutionInfo.FilePath); var newFilePath = @"C:\test\fake.sln"; solutionInfo = solutionInfo.WithFilePath(newFilePath); Assert.Equal(newFilePath, solutionInfo.FilePath); Assert.Equal(0, solutionInfo.Projects.Count()); } #endif private interface ITestLanguageService : ILanguageService { } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared, PartNotDiscoverable] private class TestLanguageServiceA : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceA() { } } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared, PartNotDiscoverable] private class TestLanguageServiceB : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceB() { } } [Fact] [WorkItem(666263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666263")] public async Task TestDocumentFileAccessFailureMissingFile() { var workspace = new AdhocWorkspace(); var solution = workspace.CurrentSolution; WorkspaceDiagnostic diagnosticFromEvent = null; solution.Workspace.WorkspaceFailed += (sender, args) => { diagnosticFromEvent = args.Diagnostic; }; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); solution = solution.AddProject(pid, "goo", "goo", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8)) .WithDocumentFilePath(did, "document path"); var doc = solution.GetDocument(did); var text = await doc.GetTextAsync().ConfigureAwait(false); var diagnostic = await doc.State.GetLoadDiagnosticAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(@"C:\doesnotexist.cs: (0,0)-(0,0)", diagnostic.Location.GetLineSpan().ToString()); Assert.Equal(WorkspaceDiagnosticKind.Failure, diagnosticFromEvent.Kind); Assert.Equal("", text.ToString()); // Verify invariant: The compilation is guaranteed to have a syntax tree for each document of the project (even if the contnet fails to load). var compilation = await solution.State.GetCompilationAsync(doc.Project.State, CancellationToken.None).ConfigureAwait(false); var syntaxTree = compilation.SyntaxTrees.Single(); Assert.Equal("", syntaxTree.ToString()); } [Fact] public void TestGetProjectForAssemblySymbol() { var pid1 = ProjectId.CreateNewId("p1"); var pid2 = ProjectId.CreateNewId("p2"); var pid3 = ProjectId.CreateNewId("p3"); var did1 = DocumentId.CreateNewId(pid1); var did2 = DocumentId.CreateNewId(pid2); var did3 = DocumentId.CreateNewId(pid3); var text1 = @" Public Class A End Class"; var text2 = @" Public Class B End Class "; var text3 = @" public class C : B { } "; var text4 = @" public class C : A { } "; var solution = new AdhocWorkspace().CurrentSolution .AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic) .AddDocument(did1, "A.vb", text1) .AddMetadataReference(pid1, s_mscorlib) .AddProject(pid2, "GooB", "Goo2.dll", LanguageNames.VisualBasic) .AddDocument(did2, "B.vb", text2) .AddMetadataReference(pid2, s_mscorlib) .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp) .AddDocument(did3, "C.cs", text3) .AddMetadataReference(pid3, s_mscorlib) .AddProjectReference(pid3, new ProjectReference(pid1)) .AddProjectReference(pid3, new ProjectReference(pid2)); var project3 = solution.GetProject(pid3); var comp3 = project3.GetCompilationAsync().Result; var classC = comp3.GetTypeByMetadataName("C"); var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid2, projectForBaseType.Id); // switch base type to A then try again var solution2 = solution.WithDocumentText(did3, SourceText.From(text4)); project3 = solution2.GetProject(pid3); comp3 = project3.GetCompilationAsync().Result; classC = comp3.GetTypeByMetadataName("C"); projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid1, projectForBaseType.Id); } [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] [Fact] public void TestEncodingRetainedAfterTreeChanged() { var ws = new AdhocWorkspace(); var proj = ws.AddProject("proj", LanguageNames.CSharp); var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32)); Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding); // updating root doesn't change original encoding var root = doc.GetSyntaxRootAsync().Result; var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace(" "))); var newDoc = doc.WithSyntaxRoot(newRoot); Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding); } [Fact] public void TestProjectWithNoBrokenReferencesHasNoIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); // Nothing should have incomplete references, and everything should build Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.True(project2.HasSuccessfullyLoadedAsync().Result); Assert.Single(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class ")); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.False(project2.HasSuccessfullyLoadedAsync().Result); Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public async Task TestFrozenPartialProjectHasDifferentSemanticVersions() { using var workspace = CreateWorkspaceWithPartalSemantics(); var project = workspace.CurrentSolution.AddProject("CSharpProject", "CSharpProject", LanguageNames.CSharp); project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project; var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From("")); var frozenDocument = documentToFreeze.WithFrozenPartialSemantics(CancellationToken.None); // Because we had no compilation produced yet, we expect that only the DocumentToFreeze is in the compilation Assert.NotSame(frozenDocument, documentToFreeze); var tree = Assert.Single((await frozenDocument.Project.GetCompilationAsync()).SyntaxTrees); Assert.Equal("DocumentToFreeze.cs", tree.FilePath); // Versions should be different Assert.NotEqual( await documentToFreeze.Project.GetDependentSemanticVersionAsync(), await frozenDocument.Project.GetDependentSemanticVersionAsync()); Assert.NotEqual( await documentToFreeze.Project.GetSemanticVersionAsync(), await frozenDocument.Project.GetSemanticVersionAsync()); } [Fact] public void TestFrozenPartialProjectAlwaysIsIncomplete() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From("")); // Nothing should have incomplete references, and everything should build var frozenSolution = document.WithFrozenPartialSemantics(CancellationToken.None).Project.Solution; Assert.True(frozenSolution.GetProject(project1.Id).HasSuccessfullyLoadedAsync().Result); Assert.True(frozenSolution.GetProject(project2.Id).HasSuccessfullyLoadedAsync().Result); } [Fact] public void TestProjectCompletenessWithMultipleProjects() { GetMultipleProjects(out var csBrokenProject, out var vbNormalProject, out var dependsOnBrokenProject, out var dependsOnVbNormalProject, out var transitivelyDependsOnBrokenProjects, out var transitivelyDependsOnNormalProjects); // check flag for a broken project itself Assert.False(csBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for a normal project itself Assert.True(vbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference a broken project Assert.True(dependsOnBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference only normal project Assert.True(dependsOnVbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference a borken project // normal project -> normal project -> broken project Assert.True(transitivelyDependsOnBrokenProjects.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference only normal project // normal project -> normal project -> normal project Assert.True(transitivelyDependsOnNormalProjects.HasSuccessfullyLoadedAsync().Result); } [Fact] public async Task TestMassiveFileSize() { // set max file length to 1 bytes var maxLength = 1; var workspace = new AdhocWorkspace(); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FileTextLoaderOptions.FileLengthThreshold, maxLength))); using var root = new TempRoot(); var file = root.CreateFile(prefix: "massiveFile", extension: ".cs").WriteAllText("hello"); var loader = new FileTextLoader(file.Path, Encoding.UTF8); var textLength = FileUtilities.GetFileLength(file.Path); var expected = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, file.Path, textLength, maxLength); var exceptionThrown = false; try { // test async one var unused = await loader.LoadTextAndVersionAsync(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); exceptionThrown = false; try { // test sync one var unused = loader.LoadTextAndVersionSynchronously(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); } [Fact] [WorkItem(18697, "https://github.com/dotnet/roslyn/issues/18697")] public void TestWithSyntaxTree() { // get one to get to syntax tree factory using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var dummyProject = solution.AddProject("dummy", "dummy", LanguageNames.CSharp); var factory = dummyProject.LanguageServices.SyntaxTreeFactory; // create the origin tree var strongTree = factory.ParseSyntaxTree("dummy", dummyProject.ParseOptions, SourceText.From("// emtpy"), CancellationToken.None); // create recoverable tree off the original tree var recoverableTree = factory.CreateRecoverableTree( dummyProject.Id, strongTree.FilePath, strongTree.Options, new ConstantValueSource<TextAndVersion>(TextAndVersion.Create(strongTree.GetText(), VersionStamp.Create(), strongTree.FilePath)), strongTree.GetText().Encoding, strongTree.GetRoot()); // create new tree before it ever getting root node var newTree = recoverableTree.WithFilePath("different/dummy"); // this shouldn't throw _ = newTree.GetRoot(); } [Fact] public void TestUpdateDocumentsOrder() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); VersionStamp GetVersion() => solution.GetProject(pid).Version; ImmutableArray<DocumentId> GetDocumentIds() => solution.GetProject(pid).DocumentIds.ToImmutableArray(); ImmutableArray<SyntaxTree> GetSyntaxTrees() { return solution.GetProject(pid).GetCompilationAsync().Result.SyntaxTrees.ToImmutableArray(); } solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); var oldVersion = GetVersion(); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newVersion = GetVersion(); // Make sure we have a new version because the order changed. Assert.NotEqual(oldVersion, newVersion); var documentIds = GetDocumentIds(); Assert.Equal(did5, documentIds[0]); Assert.Equal(did4, documentIds[1]); Assert.Equal(did3, documentIds[2]); Assert.Equal(did2, documentIds[3]); Assert.Equal(did1, documentIds[4]); var syntaxTrees = GetSyntaxTrees(); Assert.Equal(documentIds.Count(), syntaxTrees.Count()); Assert.Equal("test5.cs", syntaxTrees[0].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test4.cs", syntaxTrees[1].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test3.cs", syntaxTrees[2].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test2.cs", syntaxTrees[3].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test1.cs", syntaxTrees[4].FilePath, StringComparer.OrdinalIgnoreCase); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newSameVersion = GetVersion(); // Make sure we have the same new version because the order hasn't changed. Assert.Equal(newVersion, newSameVersion); } [Fact] public void TestUpdateDocumentsOrderExceptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); solution = solution.RemoveDocument(did5); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.Create<DocumentId>())); Assert.Throws<ArgumentNullException>(() => solution = solution.WithProjectDocumentsOrder(pid, null)); Assert.Throws<InvalidOperationException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did3, did2, did1 }))); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did3, did2, did1 }))); } [Theory] [CombinatorialData] public async Task TestAddingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var newCompilation = await project.GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(newSyntaxTree, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); } [Theory] [CombinatorialData] public async Task TestAddingAndRemovingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeAfterAddingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); project = solution.GetProject(projectId); var syntaxTreeAfterRemovingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out _)); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterRemovingEditorConfig)); } [Theory] [CombinatorialData] public async Task TestChangingAnEditorConfigFile([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName, bool useRecoverableTrees) { using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeBeforeEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.WithAnalyzerConfigDocumentTextLoader( editorConfigDocumentId, TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)), PreservationMode.PreserveValue); var syntaxTreeAfterEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); project = solution.GetProject(projectId); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA6789", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Error, severity); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterEditorConfigChange)); } [Fact] public void TestAddingAndRemovingGlobalEditorConfigFileWithDiagnosticSeverity() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp); solution = solution.AddDocument(sourceDocumentId, "Test.cs", "", filePath: @"Z:\Test.cs"); var originalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(originalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".globalconfig", filePath: @"Z:\.globalconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(newProvider.TryGetGlobalDiagnosticValue("CA1234", default, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); var finalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(finalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp) .WithProjectMetadataReferences(projectId, new[] { TestMetadata.Net451.mscorlib }) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)); var src = @" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"; solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs"); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); // warning CS8602: Dereference of a possibly null reference. var diagnostics = originalCompilation.GetDiagnostics(); var diagnostic = Assert.Single(diagnostics); Assert.Equal("CS8602", diagnostic.Id); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var newCompilation = await solution.GetProject(projectId).GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // Auto-generated code requires an explicit '#nullable' directive in source. diagnostics = newCompilation.GetDiagnostics(); diagnostic = Assert.Single(diagnostics); Assert.Contains("CS8669", diagnostic.Id); } [Fact] public void NoCompilationProjectsHaveNullSyntaxTreesAndSemanticModels() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); var document = solution.GetDocument(documentId)!; Assert.False(document.TryGetSyntaxTree(out _)); Assert.Null(document.GetSyntaxTreeAsync().Result); Assert.Null(document.GetSyntaxTreeSynchronously(CancellationToken.None)); Assert.False(document.TryGetSemanticModel(out _)); Assert.Null(document.GetSemanticModelAsync().Result); } [Fact] public void ChangingFilePathOfFileInNoCompilationProjectWorks() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); solution = solution.WithDocumentFilePath(documentId, @"Z:\NewPath.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); } [Fact] public void AddingAndRemovingProjectsUpdatesFilePathMap() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); const string editorConfigFilePath = @"Z:\.editorconfig"; var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, "Test", "Test", LanguageNames.CSharp) .WithAnalyzerConfigDocuments(new[] { DocumentInfo.Create(editorConfigDocumentId, ".editorconfig", filePath: editorConfigFilePath) }); solution = solution.AddProject(projectInfo); Assert.Equal(editorConfigDocumentId, Assert.Single(solution.GetDocumentIdsWithFilePath(editorConfigFilePath))); solution = solution.RemoveProject(projectId); Assert.Empty(solution.GetDocumentIdsWithFilePath(editorConfigFilePath)); } private static void GetMultipleProjects( out Project csBrokenProject, out Project vbNormalProject, out Project dependsOnBrokenProject, out Project dependsOnVbNormalProject, out Project transitivelyDependsOnBrokenProjects, out Project transitivelyDependsOnNormalProjects) { var workspace = new AdhocWorkspace(); csBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false)); vbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic)); dependsOnBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(csBrokenProject.Id), new ProjectReference(vbNormalProject.Id) })); dependsOnVbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(vbNormalProject.Id) })); transitivelyDependsOnBrokenProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(dependsOnBrokenProject.Id) })); transitivelyDependsOnNormalProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(dependsOnVbNormalProject.Id) })); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestOptionChangesForLanguagesNotInSolution() { // Create an empty solution with no projects. using var workspace = CreateWorkspace(); var s0 = workspace.CurrentSolution; var optionService = workspace.Services.GetRequiredService<IOptionService>(); // Apply an option change to a C# option. var option = GenerationOptions.PlaceSystemNamespaceFirst; var defaultValue = option.DefaultValue; var changedValue = !defaultValue; var options = s0.Options.WithChangedOption(option, LanguageNames.CSharp, changedValue); // Verify option change is preserved even if the solution has no project with that language. var s1 = s0.WithOptions(options); VerifyOptionSet(s1.Options); // Verify option value is preserved on adding a project for a different language. var s2 = s1.AddProject("P1", "A1", LanguageNames.VisualBasic).Solution; VerifyOptionSet(s2.Options); // Verify option value is preserved on roundtriping the option set (serialize and deserialize). var s3 = s2.AddProject("P2", "A2", LanguageNames.CSharp).Solution; var roundTripOptionSet = SerializeAndDeserialize((SerializableOptionSet)s3.Options, optionService); VerifyOptionSet(roundTripOptionSet); // Verify option value is preserved on removing a project. var s4 = s3.RemoveProject(s3.Projects.Single(p => p.Name == "P2").Id); VerifyOptionSet(s4.Options); return; void VerifyOptionSet(OptionSet optionSet) { Assert.Equal(changedValue, optionSet.GetOption(option, LanguageNames.CSharp)); Assert.Equal(defaultValue, optionSet.GetOption(option, LanguageNames.VisualBasic)); } static SerializableOptionSet SerializeAndDeserialize(SerializableOptionSet optionSet, IOptionService optionService) { using var stream = new MemoryStream(); using var writer = new ObjectWriter(stream); optionSet.Serialize(writer, CancellationToken.None); stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); return SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None); } } [Theory] [CombinatorialData] public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable) { using var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var pid = ProjectId.CreateNewId(); var text = SourceText.From("public class C { }"); var version = VersionStamp.Create(); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version))); var projInfo = ProjectInfo.Create( pid, version: VersionStamp.Default, name: "TestProject", assemblyName: "TestProject.dll", language: LanguageNames.CSharp, documents: new[] { docInfo }); var solution = workspace.CurrentSolution.AddProject(projInfo); var doc = solution.GetDocument(docInfo.Id); // change document var root = await doc.GetSyntaxRootAsync(); var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation()); Assert.NotSame(root, newRoot); var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id); Assert.NotSame(doc, newDoc); var newDocText = await newDoc.GetTextAsync(); var sameText = await newDoc.GetTextAsync(); Assert.Same(newDocText, sameText); var newDocTree = await newDoc.GetSyntaxTreeAsync(); var treeText = newDocTree.GetText(); Assert.Same(newDocText, treeText); } [Fact] public async Task ReplacingTextMultipleTimesDoesNotRootIntermediateCopiesIfCompilationNotAskedFor() { // This test replicates the pattern of some operation changing a bunch of files, but the files aren't kept open. // In Visual Studio we do large refactorings by opening files with an invisible editor, making changes, and closing // again. This process means we'll queue up intermediate changes to those files, but we don't want to hold onto // the intermediate edits when we don't really need to since the final version will be all that matters. using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); // Fetch the compilation, so further edits are going to be incremental updates of this one var originalCompilation = await solution.Projects.Single().GetCompilationAsync(); // Create a source text we'll release and ensure it disappears. We'll also make sure we don't accidentally root // that solution in the middle. var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString())); var solutionWithSourceTextToRelease = sourceTextToRelease.GetObjectReference( static (sourceText, document) => document.Project.Solution.WithDocumentText(document.Id, sourceText, PreservationMode.PreserveIdentity), solution.GetDocument(documentId)); // Change it again, this time by editing the text loader; this replicates us closing a file, and we don't want to pin the changes from the // prior change. var finalSolution = solutionWithSourceTextToRelease.GetObjectReference( static (s, documentId) => s.WithDocumentTextLoader(documentId, new TestTextLoader(Guid.NewGuid().ToString()), PreservationMode.PreserveValue), documentId).GetReference(); // The text in the middle shouldn't be held at all, since we replaced it. solutionWithSourceTextToRelease.ReleaseStrongReference(); sourceTextToRelease.AssertReleased(); GC.KeepAlive(finalSolution); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Microsoft.CodeAnalysis.VisualBasic; using Microsoft.VisualStudio.Threading; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using static Microsoft.CodeAnalysis.UnitTests.SolutionTestHelpers; namespace Microsoft.CodeAnalysis.UnitTests { [UseExportProvider] [Trait(Traits.Feature, Traits.Features.Workspace)] public class SolutionTests : TestBase { #nullable enable private static readonly MetadataReference s_mscorlib = TestMetadata.Net451.mscorlib; private static readonly DocumentId s_unrelatedDocumentId = DocumentId.CreateNewId(ProjectId.CreateNewId()); private static Workspace CreateWorkspaceWithProjectAndDocuments() { var projectId = ProjectId.CreateNewId(); var workspace = CreateWorkspace(); Assert.True(workspace.TryApplyChanges(workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAdditionalDocument(DocumentId.CreateNewId(projectId), "add.txt", "text") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config"), filePath: "/a/b"))); return workspace; } private static IEnumerable<T> EmptyEnumerable<T>() { yield break; } // Returns an enumerable that can only be enumerated once. private static IEnumerable<T> OnceEnumerable<T>(params T[] items) => OnceEnumerableImpl(new StrongBox<int>(), items); private static IEnumerable<T> OnceEnumerableImpl<T>(StrongBox<int> counter, T[] items) { Assert.Equal(0, counter.Value); counter.Value++; foreach (var item in items) { yield return item; } } [Fact] public void RemoveDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAdditionalDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAdditionalDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAdditionalDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void RemoveAnalyzerConfigDocument_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocument(null!)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocument(s_unrelatedDocumentId)); } [Fact] public void RemoveAnalyzerConfigDocuments_Errors() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(default)); Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create(s_unrelatedDocumentId))); Assert.Throws<ArgumentNullException>(() => solution.RemoveAnalyzerConfigDocuments(ImmutableArray.Create((DocumentId)null!))); } [Fact] public void WithDocumentName() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var name = "new name"; var newSolution1 = solution.WithDocumentName(documentId, name); Assert.Equal(name, newSolution1.GetDocument(documentId)!.Name); var newSolution2 = newSolution1.WithDocumentName(documentId, name); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(documentId, name: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentName(null!, name)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentName(s_unrelatedDocumentId, name)); } [Fact] public void WithDocumentFolders() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var folders = new[] { "folder1", "folder2" }; var newSolution1 = solution.WithDocumentFolders(documentId, folders); Assert.Equal(folders, newSolution1.GetDocument(documentId)!.Folders); var newSolution2 = newSolution1.WithDocumentFolders(documentId, folders); Assert.Same(newSolution2, newSolution1); // empty: var newSolution3 = solution.WithDocumentFolders(documentId, new string[0]); Assert.Equal(new string[0], newSolution3.GetDocument(documentId)!.Folders); var newSolution4 = solution.WithDocumentFolders(documentId, ImmutableArray<string>.Empty); Assert.Same(newSolution3, newSolution4); var newSolution5 = solution.WithDocumentFolders(documentId, null); Assert.Same(newSolution3, newSolution5); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(documentId, folders: new string[] { null! })); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFolders(null!, folders)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFolders(s_unrelatedDocumentId, folders)); } [Fact] [WorkItem(34837, "https://github.com/dotnet/roslyn/issues/34837")] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/37125")] public void WithDocumentFilePath() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var path = "new path"; var newSolution1 = solution.WithDocumentFilePath(documentId, path); Assert.Equal(path, newSolution1.GetDocument(documentId)!.FilePath); AssertEx.Equal(new[] { documentId }, newSolution1.GetDocumentIdsWithFilePath(path)); var newSolution2 = newSolution1.WithDocumentFilePath(documentId, path); Assert.Same(newSolution1, newSolution2); // empty path (TODO https://github.com/dotnet/roslyn/issues/37125): var newSolution3 = solution.WithDocumentFilePath(documentId, ""); Assert.Equal("", newSolution3.GetDocument(documentId)!.FilePath); Assert.Empty(newSolution3.GetDocumentIdsWithFilePath("")); // TODO: https://github.com/dotnet/roslyn/issues/37125 Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(documentId, filePath: null!)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentFilePath(null!, path)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentFilePath(s_unrelatedDocumentId, path)); } [Fact] public void WithSourceCodeKind() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); Assert.Same(solution, solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Regular)); var newSolution1 = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, newSolution1.GetDocument(documentId)!.SourceCodeKind); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSourceCodeKind(documentId, (SourceCodeKind)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSourceCodeKind(null!, SourceCodeKind.Script)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSourceCodeKind(s_unrelatedDocumentId, SourceCodeKind.Script)); } [Fact, Obsolete] public void WithSourceCodeKind_Obsolete() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var newSolution = solution.WithDocumentSourceCodeKind(documentId, SourceCodeKind.Interactive); Assert.Equal(SourceCodeKind.Script, newSolution.GetDocument(documentId)!.SourceCodeKind); } [Fact] public void WithDocumentSyntaxRoot() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var root = CS.SyntaxFactory.ParseSyntaxTree("class NewClass {}").GetRoot(); var newSolution1 = solution.WithDocumentSyntaxRoot(documentId, root, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetSyntaxRoot(out var actualRoot)); Assert.Equal(root.ToString(), actualRoot!.ToString()); // the actual root has a new parent SyntaxTree: Assert.NotSame(root, actualRoot); var newSolution2 = newSolution1.WithDocumentSyntaxRoot(documentId, actualRoot); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentSyntaxRoot(documentId, root, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentSyntaxRoot(null!, root)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentSyntaxRoot(s_unrelatedDocumentId, root)); } [Fact] [WorkItem(37125, "https://github.com/dotnet/roslyn/issues/41940")] public async Task WithDocumentSyntaxRoot_AnalyzerConfigWithoutFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(DocumentId.CreateNewId(projectId), "goo.cs", "public class Goo { }") .AddAnalyzerConfigDocument(DocumentId.CreateNewId(projectId), "editorcfg", SourceText.From("config")); var project = solution.GetProject(projectId)!; var compilation = (await project.GetCompilationAsync())!; var tree = compilation.SyntaxTrees.Single(); var provider = compilation.Options.SyntaxTreeOptionsProvider!; Assert.Throws<ArgumentException>(() => provider.TryGetDiagnosticValue(tree, "CA1234", CancellationToken.None, out _)); } [Fact] public void WithDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentText_MultipleDocuments() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithDocumentText(new[] { documentId }, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); // documents not in solution are skipped: https://github.com/dotnet/roslyn/issues/42029 Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { null! }, text)); Assert.Same(solution, solution.WithDocumentText(new DocumentId[] { s_unrelatedDocumentId }, text)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText((DocumentId[])null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentText(new[] { documentId }, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentText(new[] { documentId }, text, (PreservationMode)(-1))); } [Fact] public void WithAdditionalDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAdditionalDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAdditionalDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_SourceText() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var text = SourceText.From("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.Same(text, actualText); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, text, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, text, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, text, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, text, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentText_TextAndVersion() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var textAndVersion = TextAndVersion.Create(SourceText.From("new text"), VersionStamp.Default); var newSolution1 = solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetText(out var actualText)); Assert.True(newSolution1.GetAnalyzerConfigDocument(documentId)!.TryGetTextVersion(out var actualVersion)); Assert.Same(textAndVersion.Text, actualText); Assert.Equal(textAndVersion.Version, actualVersion); var newSolution2 = newSolution1.WithAnalyzerConfigDocumentText(documentId, textAndVersion, PreservationMode.PreserveIdentity); Assert.Same(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText(documentId, (SourceText)null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentText(documentId, textAndVersion, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentText((DocumentId)null!, textAndVersion, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentText(s_unrelatedDocumentId, textAndVersion, PreservationMode.PreserveIdentity)); } [Fact] public void WithDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAdditionalDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AdditionalDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAdditionalDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAdditionalDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAdditionalDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAdditionalDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAdditionalDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithAnalyzerConfigDocumentTextLoader() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().AnalyzerConfigDocumentIds.Single(); var loader = new TestTextLoader("new text"); var newSolution1 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.Equal("new text", newSolution1.GetAnalyzerConfigDocument(documentId)!.GetTextSynchronously(CancellationToken.None).ToString()); // Reusal is not currently implemented: https://github.com/dotnet/roslyn/issues/42028 var newSolution2 = solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, PreservationMode.PreserveIdentity); Assert.NotSame(newSolution1, newSolution2); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, null!, PreservationMode.PreserveIdentity)); Assert.Throws<ArgumentOutOfRangeException>(() => solution.WithAnalyzerConfigDocumentTextLoader(documentId, loader, (PreservationMode)(-1))); Assert.Throws<ArgumentNullException>(() => solution.WithAnalyzerConfigDocumentTextLoader(null!, loader, PreservationMode.PreserveIdentity)); Assert.Throws<InvalidOperationException>(() => solution.WithAnalyzerConfigDocumentTextLoader(s_unrelatedDocumentId, loader, PreservationMode.PreserveIdentity)); } [Fact] public void WithProjectAssemblyName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var assemblyName = "\0<>a/b/*.dll"; var newSolution = solution.WithProjectAssemblyName(projectId, assemblyName); Assert.Equal(assemblyName, newSolution.GetProject(projectId)!.AssemblyName); Assert.Same(newSolution, newSolution.WithProjectAssemblyName(projectId, assemblyName)); Assert.Throws<ArgumentNullException>("assemblyName", () => solution.WithProjectAssemblyName(projectId, null!)); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAssemblyName(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAssemblyName(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputFilePath(projectId, value), s => s.GetProject(projectId)!.OutputFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectOutputRefFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectOutputRefFilePath(projectId, value), s => s.GetProject(projectId)!.OutputRefFilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectOutputRefFilePath(null!, "x.dll")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectOutputRefFilePath(ProjectId.CreateNewId(), "x.dll")); } [Fact] public void WithProjectCompilationOutputInfo() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.dll"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectCompilationOutputInfo(projectId, value), s => s.GetProject(projectId)!.CompilationOutputInfo, new CompilationOutputInfo(path), defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOutputInfo(null!, new CompilationOutputInfo("x.dll"))); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOutputInfo(ProjectId.CreateNewId(), new CompilationOutputInfo("x.dll"))); } [Fact] public void WithProjectDefaultNamespace() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var defaultNamespace = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectDefaultNamespace(projectId, value), s => s.GetProject(projectId)!.DefaultNamespace, (string?)defaultNamespace, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectDefaultNamespace(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectDefaultNamespace(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectName() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var projectName = "\0<>a/b/*"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectName(projectId, value), s => s.GetProject(projectId)!.Name, projectName, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectName(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectName(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectFilePath() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); // any character is allowed var path = "\0<>a/b/*.csproj"; SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectFilePath(projectId, value), s => s.GetProject(projectId)!.FilePath, (string?)path, defaultThrows: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectFilePath(null!, "x")); Assert.Throws<InvalidOperationException>(() => solution.WithProjectFilePath(ProjectId.CreateNewId(), "x")); } [Fact] public void WithProjectCompilationOptionsExceptionHandling() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpCompilationOptions(OutputKind.NetModule); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectCompilationOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectCompilationOptions(ProjectId.CreateNewId(), options)); } [Theory] [CombinatorialData] public void WithProjectCompilationOptionsReplacesSyntaxTreeOptionProvider([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", languageName); // We always have a non-null SyntaxTreeOptionsProvider for C# and VB projects var originalSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(originalSyntaxTreeOptionsProvider); var defaultOptions = solution.Projects.Single().LanguageServices.GetRequiredService<ICompilationFactoryService>().GetDefaultCompilationOptions(); Assert.Null(defaultOptions.SyntaxTreeOptionsProvider); solution = solution.WithProjectCompilationOptions(projectId, defaultOptions); // The CompilationOptions we replaced with didn't have a SyntaxTreeOptionsProvider, but we would have placed it // back. The SyntaxTreeOptionsProvider should behave the same as the prior one and thus should be equal. var newSyntaxTreeOptionsProvider = solution.Projects.Single().CompilationOptions!.SyntaxTreeOptionsProvider; Assert.NotNull(newSyntaxTreeOptionsProvider); Assert.Equal(originalSyntaxTreeOptionsProvider, newSyntaxTreeOptionsProvider); } [Fact] public void WithProjectParseOptions() { var projectId = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "proj1", "proj1.dll", LanguageNames.CSharp); var options = new CSharpParseOptions(CS.LanguageVersion.CSharp1); SolutionTestHelpers.TestProperty( solution, (s, value) => s.WithProjectParseOptions(projectId, value), s => s.GetProject(projectId)!.ParseOptions!, (ParseOptions)options, defaultThrows: true); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectParseOptions(null!, options)); Assert.Throws<InvalidOperationException>(() => solution.WithProjectParseOptions(ProjectId.CreateNewId(), options)); } [Fact] public void WithProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef = new ProjectReference(projectId2); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectReferences(projectId, value), opt => opt.GetProject(projectId)!.AllProjectReferences, projectRef, allowDuplicates: false); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create( new ProjectReference(projectId2), new ProjectReference(projectId2, ImmutableArray.Create("alias")), new ProjectReference(projectId2, embedInteropTypes: true)); var solution2 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, solution2.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectReferences(null!, new[] { projectRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(ProjectId.CreateNewId(), new[] { projectRef })); // cycles: Assert.Throws<InvalidOperationException>(() => solution2.WithProjectReferences(projectId2, new[] { new ProjectReference(projectId) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] [WorkItem(42406, "https://github.com/dotnet/roslyn/issues/42406")] public void WithProjectReferences_ProjectNotInSolution() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); var projectRefs = (IEnumerable<ProjectReference>)ImmutableArray.Create(externalProjectRef); var newSolution1 = solution.WithProjectReferences(projectId, projectRefs); Assert.Same(projectRefs, newSolution1.GetProject(projectId)!.AllProjectReferences); // project reference is not included: Assert.Empty(newSolution1.GetProject(projectId)!.ProjectReferences); } [Fact] public void AddProjectReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp) .AddProject(projectId3, "proj3", "proj3.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var projectRef3 = new ProjectReference(projectId3); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.AddProjectReference(projectId3, projectRef2); var solution2 = solution.AddProjectReferences(projectId, EmptyEnumerable<ProjectReference>()); Assert.Same(solution, solution2); var e = OnceEnumerable(projectRef2, externalProjectRef); var solution3 = solution.AddProjectReferences(projectId, e); AssertEx.Equal(new[] { projectRef2 }, solution3.GetProject(projectId)!.ProjectReferences); AssertEx.Equal(new[] { projectRef2, externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddProjectReferences(null!, new[] { projectRef2 })); Assert.Throws<ArgumentNullException>("projectReferences", () => solution.AddProjectReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("projectReferences[0]", () => solution.AddProjectReferences(projectId, new ProjectReference[] { null! })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { projectRef2, projectRef2 })); Assert.Throws<ArgumentException>("projectReferences[1]", () => solution.AddProjectReferences(projectId, new[] { new ProjectReference(projectId2), new ProjectReference(projectId2) })); // dup: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId3, new[] { projectRef2 })); // cycles: Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId2, new[] { projectRef3 })); Assert.Throws<InvalidOperationException>(() => solution3.AddProjectReferences(projectId, new[] { new ProjectReference(projectId) })); } [Fact] public void RemoveProjectReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var projectId2 = ProjectId.CreateNewId(); solution = solution.AddProject(projectId2, "proj2", "proj2.dll", LanguageNames.CSharp); var projectRef2 = new ProjectReference(projectId2); var externalProjectRef = new ProjectReference(ProjectId.CreateNewId()); solution = solution.WithProjectReferences(projectId, new[] { projectRef2, externalProjectRef }); // remove reference to a project that's not part of the solution: var solution2 = solution.RemoveProjectReference(projectId, externalProjectRef); AssertEx.Equal(new[] { projectRef2 }, solution2.GetProject(projectId)!.AllProjectReferences); // remove reference to a project that's part of the solution: var solution3 = solution.RemoveProjectReference(projectId, projectRef2); AssertEx.Equal(new[] { externalProjectRef }, solution3.GetProject(projectId)!.AllProjectReferences); var solution4 = solution3.RemoveProjectReference(projectId, externalProjectRef); Assert.Empty(solution4.GetProject(projectId)!.AllProjectReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveProjectReference(null!, projectRef2)); Assert.Throws<ArgumentNullException>("projectReference", () => solution.RemoveProjectReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<ArgumentException>("projectReference", () => solution.RemoveProjectReference(projectId, new ProjectReference(ProjectId.CreateNewId()))); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveProjectReference(ProjectId.CreateNewId(), projectRef2)); } [Fact] public void ProjectReferences_Submissions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId0 = ProjectId.CreateNewId(); var submissionId1 = ProjectId.CreateNewId(); var submissionId2 = ProjectId.CreateNewId(); var submissionId3 = ProjectId.CreateNewId(); solution = solution .AddProject(projectId0, "non-submission", "non-submission.dll", LanguageNames.CSharp) .AddProject(ProjectInfo.Create(submissionId1, VersionStamp.Default, name: "submission1", assemblyName: "submission1.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId2, VersionStamp.Default, name: "submission2", assemblyName: "submission2.dll", LanguageNames.CSharp, isSubmission: true)) .AddProject(ProjectInfo.Create(submissionId3, VersionStamp.Default, name: "submission3", assemblyName: "submission3.dll", LanguageNames.CSharp, isSubmission: true)) .AddProjectReference(submissionId2, new ProjectReference(submissionId1)) .WithProjectReferences(submissionId2, new[] { new ProjectReference(submissionId1) }); // submission may be referenced from multiple submissions (forming a tree): _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(submissionId1) }); // submission may reference a non-submission project: _ = solution.AddProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); _ = solution.WithProjectReferences(submissionId3, new[] { new ProjectReference(projectId0) }); // submission can't reference multiple submissions: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(submissionId2, new[] { new ProjectReference(submissionId3) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(submissionId1, new[] { new ProjectReference(submissionId2), new ProjectReference(submissionId3) })); // non-submission project can't reference a submission: Assert.Throws<InvalidOperationException>(() => solution.AddProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectReferences(projectId0, new[] { new ProjectReference(submissionId1) })); } [Fact] public void WithProjectMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef = (MetadataReference)new TestMetadataReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectMetadataReferences(projectId, value), opt => opt.GetProject(projectId)!.MetadataReferences, metadataRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectMetadataReferences(null!, new[] { metadataRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectMetadataReferences(ProjectId.CreateNewId(), new[] { metadataRef })); } [Fact] public void AddMetadataReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddMetadataReferences(projectId, EmptyEnumerable<MetadataReference>()); Assert.Same(solution, solution2); var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); var solution3 = solution.AddMetadataReferences(projectId, OnceEnumerable(metadataRef1, metadataRef2)); AssertEx.Equal(new[] { metadataRef1, metadataRef2 }, solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddMetadataReferences(null!, new[] { metadataRef1 })); Assert.Throws<ArgumentNullException>("metadataReferences", () => solution.AddMetadataReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("metadataReferences[0]", () => solution.AddMetadataReferences(projectId, new MetadataReference[] { null! })); Assert.Throws<ArgumentException>("metadataReferences[1]", () => solution.AddMetadataReferences(projectId, new[] { metadataRef1, metadataRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddMetadataReferences(projectId, new[] { metadataRef1 })); } [Fact] public void RemoveMetadataReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var metadataRef1 = new TestMetadataReference(); var metadataRef2 = new TestMetadataReference(); solution = solution.WithProjectMetadataReferences(projectId, new[] { metadataRef1, metadataRef2 }); var solution2 = solution.RemoveMetadataReference(projectId, metadataRef1); AssertEx.Equal(new[] { metadataRef2 }, solution2.GetProject(projectId)!.MetadataReferences); var solution3 = solution2.RemoveMetadataReference(projectId, metadataRef2); Assert.Empty(solution3.GetProject(projectId)!.MetadataReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveMetadataReference(null!, metadataRef1)); Assert.Throws<ArgumentNullException>("metadataReference", () => solution.RemoveMetadataReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(projectId, new TestMetadataReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveMetadataReference(ProjectId.CreateNewId(), metadataRef1)); } [Fact] public void WithProjectAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithProjectAnalyzerReferences(projectId, value), opt => opt.GetProject(projectId)!.AnalyzerReferences, analyzerRef, allowDuplicates: false); Assert.Throws<ArgumentNullException>("projectId", () => solution.WithProjectAnalyzerReferences(null!, new[] { analyzerRef })); Assert.Throws<InvalidOperationException>(() => solution.WithProjectAnalyzerReferences(ProjectId.CreateNewId(), new[] { analyzerRef })); } [Fact] public void AddAnalyzerReferences_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var solution2 = solution.AddAnalyzerReferences(projectId, EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(projectId, OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.GetProject(projectId)!.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(projectId, new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("projectId", () => solution.AddAnalyzerReferences(null!, new[] { analyzerRef1 })); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(projectId, null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(projectId, new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(projectId, new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference_Project() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var projectId = solution.Projects.Single().Id; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithProjectAnalyzerReferences(projectId, new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(projectId, analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.GetProject(projectId)!.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(projectId, analyzerRef2); Assert.Empty(solution3.GetProject(projectId)!.AnalyzerReferences); Assert.Throws<ArgumentNullException>("projectId", () => solution.RemoveAnalyzerReference(null!, analyzerRef1)); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(projectId, null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(projectId, new TestAnalyzerReference())); // project not in solution: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(ProjectId.CreateNewId(), analyzerRef1)); } [Fact] public void WithAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef = (AnalyzerReference)new TestAnalyzerReference(); SolutionTestHelpers.TestListProperty(solution, (old, value) => old.WithAnalyzerReferences(value), opt => opt.AnalyzerReferences, analyzerRef, allowDuplicates: false); } [Fact] public void AddAnalyzerReferences() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var solution2 = solution.AddAnalyzerReferences(EmptyEnumerable<AnalyzerReference>()); Assert.Same(solution, solution2); var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); var solution3 = solution.AddAnalyzerReferences(OnceEnumerable(analyzerRef1, analyzerRef2)); AssertEx.Equal(new[] { analyzerRef1, analyzerRef2 }, solution3.AnalyzerReferences); var solution4 = solution3.AddAnalyzerReferences(new AnalyzerReference[0]); Assert.Same(solution, solution2); Assert.Throws<ArgumentNullException>("analyzerReferences", () => solution.AddAnalyzerReferences(null!)); Assert.Throws<ArgumentNullException>("analyzerReferences[0]", () => solution.AddAnalyzerReferences(new AnalyzerReference[] { null! })); Assert.Throws<ArgumentException>("analyzerReferences[1]", () => solution.AddAnalyzerReferences(new[] { analyzerRef1, analyzerRef1 })); // dup: Assert.Throws<InvalidOperationException>(() => solution3.AddAnalyzerReferences(new[] { analyzerRef1 })); } [Fact] public void RemoveAnalyzerReference() { using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var analyzerRef1 = new TestAnalyzerReference(); var analyzerRef2 = new TestAnalyzerReference(); solution = solution.WithAnalyzerReferences(new[] { analyzerRef1, analyzerRef2 }); var solution2 = solution.RemoveAnalyzerReference(analyzerRef1); AssertEx.Equal(new[] { analyzerRef2 }, solution2.AnalyzerReferences); var solution3 = solution2.RemoveAnalyzerReference(analyzerRef2); Assert.Empty(solution3.AnalyzerReferences); Assert.Throws<ArgumentNullException>("analyzerReference", () => solution.RemoveAnalyzerReference(null!)); // removing a reference that's not in the list: Assert.Throws<InvalidOperationException>(() => solution.RemoveAnalyzerReference(new TestAnalyzerReference())); } #nullable disable [Fact] public void TestAddProject() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(solution.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.False(project.HasDocuments); } [Fact] public void TestUpdateAssemblyName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.WithProjectAssemblyName(project1, "bar"); var project = solution.GetProject(project1); Assert.Equal("bar", project.AssemblyName); } [Fact] [WorkItem(543964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543964")] public void MultipleProjectsWithSameDisplayName() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); var project2 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "name", "assemblyName", LanguageNames.CSharp); solution = solution.AddProject(project2, "name", "assemblyName", LanguageNames.CSharp); Assert.Equal(2, solution.GetProjectsByName("name").Count()); } [Fact] public async Task TestAddFirstDocumentAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); // verify project & document Assert.NotNull(pid); var project = solution.GetProject(pid); Assert.NotNull(project); Assert.True(solution.ContainsProject(pid), "Solution was expected to have project " + pid); Assert.True(project.HasDocuments, "Project was expected to have documents"); Assert.Equal(project, solution.GetProject(pid)); Assert.NotNull(did); var document = solution.GetDocument(did); Assert.True(project.ContainsDocument(did), "Project was expected to have document " + did); Assert.Equal(document, project.GetDocument(did)); Assert.Equal(document, solution.GetDocument(did)); var semantics = await document.GetSemanticModelAsync(); Assert.NotNull(semantics); await ValidateSolutionAndCompilationsAsync(solution); var pid2 = solution.Projects.Single().Id; var did2 = DocumentId.CreateNewId(pid2); solution = solution.AddDocument(did2, "bar.cs", "public class Bar { }"); // verify project & document var project2 = solution.GetProject(pid2); Assert.NotNull(project2); Assert.NotNull(did2); var document2 = solution.GetDocument(did2); Assert.True(project2.ContainsDocument(did2), "Project was expected to have document " + did2); Assert.Equal(document2, project2.GetDocument(did2)); Assert.Equal(document2, solution.GetDocument(did2)); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForSingleProject() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project = Assert.Single(solution.Projects); var document1 = project.GetDocument(documentInfo1.Id); var document2 = project.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task AddTwoDocumentsForTwoProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); var project1 = solution.GetProject(projectId1); var project2 = solution.GetProject(projectId2); var document1 = project1.GetDocument(documentInfo1.Id); var document2 = project2.GetDocument(documentInfo2.Id); Assert.NotSame(document1, document2); Assert.NotSame(document1.Project, document2.Project); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public void AddTwoDocumentsWithMissingProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); // We're only adding the first project, but not the second one using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp); Assert.ThrowsAny<InvalidOperationException>(() => solution.AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2))); } [Fact] public void RemoveZeroDocuments() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; Assert.Same(solution, solution.RemoveDocuments(ImmutableArray<DocumentId>.Empty)); } [Fact] public async Task RemoveTwoDocuments() { var projectId = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "project1", "project1.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); var finalProject = solution.Projects.Single(); Assert.Empty(finalProject.Documents); Assert.Empty((await finalProject.GetCompilationAsync()).SyntaxTrees); } [Fact] public void RemoveTwoDocumentsFromDifferentProjects() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); var documentInfo2 = DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "file2.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocuments(ImmutableArray.Create(documentInfo1, documentInfo2)); Assert.All(solution.Projects, p => Assert.Single(p.Documents)); solution = solution.RemoveDocuments(ImmutableArray.Create(documentInfo1.Id, documentInfo2.Id)); Assert.All(solution.Projects, p => Assert.Empty(p.Documents)); } [Fact] public void RemoveDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.cs"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAdditionalDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "file1.txt"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAdditionalDocument(documentInfo1); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAdditionalDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public void RemoveAnalyzerConfigDocumentFromUnrelatedProject() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var documentInfo1 = DocumentInfo.Create(DocumentId.CreateNewId(projectId1), ".editorconfig"); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId1, "project1", "project1.dll", LanguageNames.CSharp) .AddProject(projectId2, "project2", "project2.dll", LanguageNames.CSharp) .AddAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1)); // This should throw if we're removing one document from the wrong project. Right now we don't test the RemoveAdditionalDocument // API due to https://github.com/dotnet/roslyn/issues/41211. Assert.Throws<ArgumentException>(() => solution.GetProject(projectId2).RemoveAnalyzerConfigDocuments(ImmutableArray.Create(documentInfo1.Id))); } [Fact] public async Task TestOneCSharpProjectAsync() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject("goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(s_mscorlib) .AddDocument("goo.cs", "public class Goo { }") .Project.Solution; await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestTwoCSharpProjectsAsync() { using var workspace = CreateWorkspace(); var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); var doc1 = DocumentId.CreateNewId(pm1); var doc2 = DocumentId.CreateNewId(pm2); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pm2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(doc1, "goo.cs", "public class Goo { }") .AddDocument(doc2, "bar.cs", "public class Bar : Goo { }"); await ValidateSolutionAndCompilationsAsync(solution); } [Fact] public async Task TestCrossLanguageProjectsAsync() { var pm1 = ProjectId.CreateNewId(); var pm2 = ProjectId.CreateNewId(); using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(pm1, "goo", "goo.dll", LanguageNames.CSharp) .AddMetadataReference(pm1, s_mscorlib) .AddProject(pm2, "bar", "bar.dll", LanguageNames.VisualBasic) .AddMetadataReference(pm2, s_mscorlib) .AddProjectReference(pm2, new ProjectReference(pm1)) .AddDocument(DocumentId.CreateNewId(pm1), "goo.cs", "public class X { }") .AddDocument(DocumentId.CreateNewId(pm2), "bar.vb", "Public Class Y\r\nInherits X\r\nEnd Class"); await ValidateSolutionAndCompilationsAsync(solution); } private static async Task ValidateSolutionAndCompilationsAsync(Solution solution) { foreach (var project in solution.Projects) { Assert.True(solution.ContainsProject(project.Id), "Solution was expected to have project " + project.Id); Assert.Equal(project, solution.GetProject(project.Id)); // these won't always be unique in real-world but should be for these tests Assert.Equal(project, solution.GetProjectsByName(project.Name).FirstOrDefault()); var compilation = await project.GetCompilationAsync(); Assert.NotNull(compilation); // check that the options are the same Assert.Equal(project.CompilationOptions, compilation.Options); // check that all known metadata references are present in the compilation foreach (var meta in project.MetadataReferences) { Assert.True(compilation.References.Contains(meta), "Compilation references were expected to contain " + meta); } // check that all project-to-project reference metadata is present in the compilation foreach (var referenced in project.ProjectReferences) { if (solution.ContainsProject(referenced.ProjectId)) { var referencedMetadata = await solution.State.GetMetadataReferenceAsync(referenced, solution.GetProjectState(project.Id), CancellationToken.None); Assert.NotNull(referencedMetadata); if (referencedMetadata is CompilationReference compilationReference) { compilation.References.Single(r => { var cr = r as CompilationReference; return cr != null && cr.Compilation == compilationReference.Compilation; }); } } } // check that the syntax trees are the same var docs = project.Documents.ToList(); var trees = compilation.SyntaxTrees.ToList(); Assert.Equal(docs.Count, trees.Count); foreach (var doc in docs) { Assert.True(trees.Contains(await doc.GetSyntaxTreeAsync()), "trees list was expected to contain the syntax tree of doc"); } } } #if false [Fact(Skip = "641963")] public void TestDeepProjectReferenceTree() { int projectCount = 5; var solution = CreateSolutionWithProjectDependencyChain(projectCount); ProjectId[] projectIds = solution.ProjectIds.ToArray(); Compilation compilation; for (int i = 0; i < projectCount; i++) { Assert.False(solution.GetProject(projectIds[i]).TryGetCompilation(out compilation)); } var top = solution.GetCompilationAsync(projectIds.Last(), CancellationToken.None).Result; var partialSolution = solution.GetPartialSolution(); for (int i = 0; i < projectCount; i++) { // While holding a compilation, we also hold its references, plus one further level // of references alive. However, the references are only partial Declaration // compilations var isPartialAvailable = i >= projectCount - 3; var isFinalAvailable = i == projectCount - 1; var projectId = projectIds[i]; Assert.Equal(isFinalAvailable, solution.GetProject(projectId).TryGetCompilation(out compilation)); Assert.Equal(isPartialAvailable, partialSolution.ProjectIds.Contains(projectId) && partialSolution.GetProject(projectId).TryGetCompilation(out compilation)); } } #endif [WorkItem(636431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636431")] [Fact] public async Task TestProjectDependencyLoadingAsync() { using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var projectIds = Enumerable.Range(0, 5).Select(i => ProjectId.CreateNewId()).ToArray(); for (var i = 0; i < projectIds.Length; i++) { solution = solution.AddProject(projectIds[i], i.ToString(), i.ToString(), LanguageNames.CSharp); if (i >= 1) { solution = solution.AddProjectReference(projectIds[i], new ProjectReference(projectIds[i - 1])); } } await solution.GetProject(projectIds[0]).GetCompilationAsync(CancellationToken.None); await solution.GetProject(projectIds[2]).GetCompilationAsync(CancellationToken.None); } [Fact] public async Task TestAddMetadataReferencesAsync() { var mefReference = TestMetadata.Net451.SystemCore; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); solution = solution.AddMetadataReference(project1, mefReference); var assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); var namespacesAndTypes = assemblyReference.GlobalNamespace.GetAllNamespacesAndTypes(CancellationToken.None); var foundSymbol = from symbol in namespacesAndTypes where symbol.Name.Equals("Enumerable") select symbol; Assert.Equal(1, foundSymbol.Count()); solution = solution.RemoveMetadataReference(project1, mefReference); assemblyReference = (IAssemblySymbol)solution.GetProject(project1).GetCompilationAsync().Result.GetAssemblyOrModuleSymbol(mefReference); Assert.Null(assemblyReference); await ValidateSolutionAndCompilationsAsync(solution); } private class MockDiagnosticAnalyzer : DiagnosticAnalyzer { public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { throw new NotImplementedException(); } } public override void Initialize(AnalysisContext analysisContext) { } } [Fact] public void TestProjectDiagnosticAnalyzers() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); Assert.Empty(solution.Projects.Single().AnalyzerReferences); DiagnosticAnalyzer analyzer = new MockDiagnosticAnalyzer(); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); // Test AddAnalyzer var newSolution = solution.AddAnalyzerReference(project1, analyzerReference); var actualAnalyzerReferences = newSolution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); var actualAnalyzers = actualAnalyzerReferences[0].GetAnalyzersForAllLanguages(); Assert.Equal(1, actualAnalyzers.Length); Assert.Equal(analyzer, actualAnalyzers[0]); // Test ProjectChanges var changes = newSolution.GetChanges(solution).GetProjectChanges().Single(); var addedAnalyzerReference = changes.GetAddedAnalyzerReferences().Single(); Assert.Equal(analyzerReference, addedAnalyzerReference); var removedAnalyzerReferences = changes.GetRemovedAnalyzerReferences(); Assert.Empty(removedAnalyzerReferences); solution = newSolution; // Test RemoveAnalyzer solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Empty(actualAnalyzerReferences); // Test AddAnalyzers analyzerReference = new AnalyzerImageReference(ImmutableArray.Create(analyzer)); DiagnosticAnalyzer secondAnalyzer = new MockDiagnosticAnalyzer(); var secondAnalyzerReference = new AnalyzerImageReference(ImmutableArray.Create(secondAnalyzer)); var analyzerReferences = new[] { analyzerReference, secondAnalyzerReference }; solution = solution.AddAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); solution = solution.RemoveAnalyzerReference(project1, analyzerReference); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(1, actualAnalyzerReferences.Count); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[0]); // Test WithAnalyzers solution = solution.WithProjectAnalyzerReferences(project1, analyzerReferences); actualAnalyzerReferences = solution.Projects.Single().AnalyzerReferences; Assert.Equal(2, actualAnalyzerReferences.Count); Assert.Equal(analyzerReference, actualAnalyzerReferences[0]); Assert.Equal(secondAnalyzerReference, actualAnalyzerReferences[1]); } [Fact] public void TestProjectParseOptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var project1 = ProjectId.CreateNewId(); solution = solution.AddProject(project1, "goo", "goo.dll", LanguageNames.CSharp); solution = solution.AddMetadataReference(project1, s_mscorlib); // Parse Options var oldParseOptions = solution.GetProject(project1).ParseOptions; var newParseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "AFTER" }); solution = solution.WithProjectParseOptions(project1, newParseOptions); var newUpdatedParseOptions = solution.GetProject(project1).ParseOptions; Assert.NotEqual(oldParseOptions, newUpdatedParseOptions); Assert.Same(newParseOptions, newUpdatedParseOptions); } [Fact] public async Task TestRemoveProjectAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol.ProjectIds.Any(), "Solution was expected to have projects"); Assert.NotNull(pid); var project = sol.GetProject(pid); Assert.False(project.HasDocuments); var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ProjectIds.Any()); await ValidateSolutionAndCompilationsAsync(sol); } [Fact] public async Task TestRemoveProjectWithReferencesAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced // this should leave a dangling reference var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 project pid2 was expected to contain project reference " + pid); await ValidateSolutionAndCompilationsAsync(sol2); } [Fact] public async Task TestRemoveProjectWithReferencesAndAddItBackAsync() { using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var pid2 = ProjectId.CreateNewId(); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddProject(pid2, "bar", "bar.dll", LanguageNames.CSharp) .AddProjectReference(pid2, new ProjectReference(pid)); Assert.Equal(2, sol.Projects.Count()); // remove the project that is being referenced var sol2 = sol.RemoveProject(pid); Assert.False(sol2.ContainsProject(pid)); Assert.True(sol2.ContainsProject(pid2), "sol2 was expected to contain project " + pid2); Assert.Equal(1, sol2.Projects.Count()); Assert.True(sol2.GetProject(pid2).AllProjectReferences.Any(r => r.ProjectId == pid), "sol2 pid2 was expected to contain " + pid); var sol3 = sol2.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp); Assert.True(sol3.ContainsProject(pid), "sol3 was expected to contain " + pid); Assert.True(sol3.ContainsProject(pid2), "sol3 was expected to contain " + pid2); Assert.Equal(2, sol3.Projects.Count()); await ValidateSolutionAndCompilationsAsync(sol3); } [Fact] public async Task TestGetSyntaxRootAsync() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); Assert.False(document.TryGetSyntaxRoot(out _)); var root = await document.GetSyntaxRootAsync(); Assert.NotNull(root); Assert.Equal(text, root.ToString()); Assert.True(document.TryGetSyntaxRoot(out root)); Assert.NotNull(root); } [Fact] public async Task TestUpdateDocumentAsync() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); using var workspace = CreateWorkspace(); var solution1 = workspace.CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", SourceText.From("class Class{}")); var document = solution1.GetDocument(documentId); var newRoot = await Formatter.FormatAsync(document).Result.GetSyntaxRootAsync(); var solution2 = solution1.WithDocumentSyntaxRoot(documentId, newRoot); Assert.NotEqual(solution1, solution2); var newText = solution2.GetDocument(documentId).GetTextAsync().Result.ToString(); Assert.Equal("class Class { }", newText); } [Fact] public void TestUpdateSyntaxTreeWithAnnotations() { var text = "public class Goo { }"; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var document = sol.GetDocument(did); var tree = document.GetSyntaxTreeAsync().Result; var root = tree.GetRoot(); var annotation = new SyntaxAnnotation(); var annotatedRoot = root.WithAdditionalAnnotations(annotation); var sol2 = sol.WithDocumentSyntaxRoot(did, annotatedRoot); var doc2 = sol2.GetDocument(did); var tree2 = doc2.GetSyntaxTreeAsync().Result; var root2 = tree2.GetRoot(); // text should not be available yet (it should be defer created from the node) // and getting the document or root should not cause it to be created. Assert.False(tree2.TryGetText(out _)); var text2 = tree2.GetText(); Assert.NotNull(text2); Assert.NotSame(tree, tree2); Assert.NotSame(annotatedRoot, root2); Assert.True(annotatedRoot.IsEquivalentTo(root2)); Assert.True(root2.HasAnnotation(annotation)); } [Fact] public void TestUpdatingFilePathUpdatesSyntaxTree() { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); const string OldFilePath = @"Z:\OldFilePath.cs"; const string NewFilePath = @"Z:\NewFilePath.cs"; using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution .AddProject(projectId, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(documentId, "OldFilePath.cs", "public class Goo { }", filePath: OldFilePath); // scope so later asserts don't accidentally use oldDocument { var oldDocument = solution.GetDocument(documentId); Assert.Equal(OldFilePath, oldDocument.FilePath); Assert.Equal(OldFilePath, oldDocument.GetSyntaxTreeAsync().Result.FilePath); } solution = solution.WithDocumentFilePath(documentId, NewFilePath); { var newDocument = solution.GetDocument(documentId); Assert.Equal(NewFilePath, newDocument.FilePath); Assert.Equal(NewFilePath, newDocument.GetSyntaxTreeAsync().Result.FilePath); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestSyntaxRootNotKeptAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", "public class Goo { }"); var observedRoot = GetObservedSyntaxTreeRoot(sol, did); observedRoot.AssertReleased(); // re-get the tree (should recover from storage, not reparse) _ = sol.GetDocument(did).GetSyntaxRootAsync().Result; } [MethodImpl(MethodImplOptions.NoInlining)] [Fact] [WorkItem(542736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542736")] public void TestDocumentChangedOnDiskIsNotObserved() { var text1 = "public class A {}"; var text2 = "public class B {}"; var file = Temp.CreateFile().WriteAllText(text1, Encoding.UTF8); // create a solution that evicts from the cache immediately. using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); sol = sol.AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var observedText = GetObservedText(sol, did, text1); // change text on disk & verify it is changed file.WriteAllText(text2); var textOnDisk = file.ReadAllText(); Assert.Equal(text2, textOnDisk); // stop observing it and let GC reclaim it observedText.AssertReleased(); // if we ask for the same text again we should get the original content var observedText2 = sol.GetDocument(did).GetTextAsync().Result; Assert.Equal(text1, observedText2.ToString()); } [Fact] public void TestGetTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19427")] public void TestGetRecoveredTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); // get it async and force it to recover from temporary storage var doc = sol.GetDocument(did); var docText = doc.GetTextAsync().Result; Assert.NotNull(docText); Assert.Equal(text, docText.ToString()); } [Fact] public void TestGetSyntaxTreeAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromLoadedTextAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; var file = Temp.CreateFile().WriteAllText(text, Encoding.UTF8); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(file.Path, Encoding.UTF8)); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxTreeAsync().Result; Assert.NotNull(docTree); Assert.Equal(text, docTree.GetRoot().ToString()); } [Fact] public void TestGetSyntaxTreeFromAddedTree() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var tree = CSharp.SyntaxFactory.ParseSyntaxTree("public class C {}").GetRoot(CancellationToken.None); tree = tree.WithAdditionalAnnotations(new SyntaxAnnotation("test")); using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "x", tree); var doc = sol.GetDocument(did); var docTree = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docTree); Assert.True(tree.IsEquivalentTo(docTree)); Assert.NotNull(docTree.GetAnnotatedNodes("test").Single()); } [Fact] public async Task TestGetSyntaxRootAsync2Async() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docRoot = await doc.GetSyntaxRootAsync(); Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14954")] public void TestGetRecoveredSyntaxRootAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the syntax tree root and wait for the references to be GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); // get it async and force it to be recovered from storage var doc = sol.GetDocument(did); var docRoot = doc.GetSyntaxRootAsync().Result; Assert.NotNull(docRoot); Assert.Equal(text, docRoot.ToString()); } [Fact] public void TestGetCompilationAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var proj = sol.GetProject(pid); var compilation = proj.GetCompilationAsync().Result; Assert.NotNull(compilation); Assert.Equal(1, compilation.SyntaxTrees.Count()); } [Fact] public void TestGetSemanticModelAsync() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspace(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); var doc = sol.GetDocument(did); var docModel = doc.GetSemanticModelAsync().Result; Assert.NotNull(docModel); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedText(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedText(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetTextAsyncDoesNotKeepTextAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // observe the text and then wait for the references to be GC'd var observed = GetObservedTextAsync(sol, did, text); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SourceText> GetObservedTextAsync(Solution solution, DocumentId documentId, string expectedText = null) { var observedText = solution.GetDocument(documentId).GetTextAsync().Result; if (expectedText != null) { Assert.Equal(expectedText, observedText.ToString()); } return new ObjectReference<SourceText>(observedText); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRoot(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRoot(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetSyntaxRootAsyncDoesNotKeepRootAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<SyntaxNode> GetObservedSyntaxTreeRootAsync(Solution solution, DocumentId documentId) { var observedTree = solution.GetDocument(documentId).GetSyntaxRootAsync().Result; return new ObjectReference<SyntaxNode>(observedTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13506")] [WorkItem(13506, "https://github.com/dotnet/roslyn/issues/13506")] public void TestRecoverableSyntaxTreeCSharp() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"public class C { public void Method1() {} public void Method2() {} public void Method3() {} public void Method4() {} public void Method5() {} public void Method6() {} }"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); TestRecoverableSyntaxTree(sol, did); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestRecoverableSyntaxTreeVisualBasic() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = @"Public Class C Sub Method1() End Sub Sub Method2() End Sub Sub Method3() End Sub Sub Method4() End Sub Sub Method5() End Sub Sub Method6() End Sub End Class"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.VisualBasic) .AddDocument(did, "goo.vb", text); TestRecoverableSyntaxTree(sol, did); } private static void TestRecoverableSyntaxTree(Solution sol, DocumentId did) { // get it async and wait for it to get GC'd var observed = GetObservedSyntaxTreeRootAsync(sol, did); observed.AssertReleased(); var doc = sol.GetDocument(did); // access the tree & root again (recover it) var tree = doc.GetSyntaxTreeAsync().Result; // this should cause reparsing var root = tree.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree, root.SyntaxTree); // reset the syntax root, to make it 'refactored' by adding an attribute var newRoot = doc.GetSyntaxRootAsync().Result.WithAdditionalAnnotations(SyntaxAnnotation.ElasticAnnotation); var doc2 = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot, PreservationMode.PreserveValue).GetDocument(doc.Id); // get it async and wait for it to get GC'd var observed2 = GetObservedSyntaxTreeRootAsync(doc2.Project.Solution, did); observed2.AssertReleased(); // access the tree & root again (recover it) var tree2 = doc2.GetSyntaxTreeAsync().Result; // this should cause deserialization var root2 = tree2.GetRoot(); // prove that the new root is correctly associated with the tree Assert.Equal(tree2, root2.SyntaxTree); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationAsyncDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilationAsync(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilationAsync(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [MethodImpl(MethodImplOptions.NoInlining)] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/13433")] public void TestGetCompilationDoesNotKeepCompilationAlive() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var text = "public class C {}"; using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var sol = workspace.CurrentSolution .AddProject(pid, "goo", "goo.dll", LanguageNames.CSharp) .AddDocument(did, "goo.cs", text); // get it async and wait for it to get GC'd var observed = GetObservedCompilation(sol, pid); observed.AssertReleased(); } [MethodImpl(MethodImplOptions.NoInlining)] private static ObjectReference<Compilation> GetObservedCompilation(Solution solution, ProjectId projectId) { var observed = solution.GetProject(projectId).GetCompilationAsync().Result; return new ObjectReference<Compilation>(observed); } [Fact] public void TestWorkspaceLanguageServiceOverride() { var hostServices = FeaturesTestCompositions.Features.AddParts(new[] { typeof(TestLanguageServiceA), typeof(TestLanguageServiceB), }).GetHostServices(); var ws = new AdhocWorkspace(hostServices, ServiceLayer.Host); var service = ws.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service as TestLanguageServiceA); var ws2 = new AdhocWorkspace(hostServices, "Quasimodo"); var service2 = ws2.Services.GetLanguageServices(LanguageNames.CSharp).GetService<ITestLanguageService>(); Assert.NotNull(service2 as TestLanguageServiceB); } #if false [Fact] public void TestSolutionInfo() { var oldSolutionId = SolutionId.CreateNewId("oldId"); var oldVersion = VersionStamp.Create(); var solutionInfo = SolutionInfo.Create(oldSolutionId, oldVersion, null, null); var newSolutionId = SolutionId.CreateNewId("newId"); solutionInfo = solutionInfo.WithId(newSolutionId); Assert.NotEqual(oldSolutionId, solutionInfo.Id); Assert.Equal(newSolutionId, solutionInfo.Id); var newVersion = oldVersion.GetNewerVersion(); solutionInfo = solutionInfo.WithVersion(newVersion); Assert.NotEqual(oldVersion, solutionInfo.Version); Assert.Equal(newVersion, solutionInfo.Version); Assert.Null(solutionInfo.FilePath); var newFilePath = @"C:\test\fake.sln"; solutionInfo = solutionInfo.WithFilePath(newFilePath); Assert.Equal(newFilePath, solutionInfo.FilePath); Assert.Equal(0, solutionInfo.Projects.Count()); } #endif private interface ITestLanguageService : ILanguageService { } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, ServiceLayer.Default), Shared, PartNotDiscoverable] private class TestLanguageServiceA : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceA() { } } [ExportLanguageService(typeof(ITestLanguageService), LanguageNames.CSharp, "Quasimodo"), Shared, PartNotDiscoverable] private class TestLanguageServiceB : ITestLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestLanguageServiceB() { } } [Fact] [WorkItem(666263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666263")] public async Task TestDocumentFileAccessFailureMissingFile() { var workspace = new AdhocWorkspace(); var solution = workspace.CurrentSolution; WorkspaceDiagnostic diagnosticFromEvent = null; solution.Workspace.WorkspaceFailed += (sender, args) => { diagnosticFromEvent = args.Diagnostic; }; var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); solution = solution.AddProject(pid, "goo", "goo", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader(@"C:\doesnotexist.cs", Encoding.UTF8)) .WithDocumentFilePath(did, "document path"); var doc = solution.GetDocument(did); var text = await doc.GetTextAsync().ConfigureAwait(false); var diagnostic = await doc.State.GetLoadDiagnosticAsync(CancellationToken.None).ConfigureAwait(false); Assert.Equal(@"C:\doesnotexist.cs: (0,0)-(0,0)", diagnostic.Location.GetLineSpan().ToString()); Assert.Equal(WorkspaceDiagnosticKind.Failure, diagnosticFromEvent.Kind); Assert.Equal("", text.ToString()); // Verify invariant: The compilation is guaranteed to have a syntax tree for each document of the project (even if the contnet fails to load). var compilation = await solution.State.GetCompilationAsync(doc.Project.State, CancellationToken.None).ConfigureAwait(false); var syntaxTree = compilation.SyntaxTrees.Single(); Assert.Equal("", syntaxTree.ToString()); } [Fact] public void TestGetProjectForAssemblySymbol() { var pid1 = ProjectId.CreateNewId("p1"); var pid2 = ProjectId.CreateNewId("p2"); var pid3 = ProjectId.CreateNewId("p3"); var did1 = DocumentId.CreateNewId(pid1); var did2 = DocumentId.CreateNewId(pid2); var did3 = DocumentId.CreateNewId(pid3); var text1 = @" Public Class A End Class"; var text2 = @" Public Class B End Class "; var text3 = @" public class C : B { } "; var text4 = @" public class C : A { } "; var solution = new AdhocWorkspace().CurrentSolution .AddProject(pid1, "GooA", "Goo.dll", LanguageNames.VisualBasic) .AddDocument(did1, "A.vb", text1) .AddMetadataReference(pid1, s_mscorlib) .AddProject(pid2, "GooB", "Goo2.dll", LanguageNames.VisualBasic) .AddDocument(did2, "B.vb", text2) .AddMetadataReference(pid2, s_mscorlib) .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp) .AddDocument(did3, "C.cs", text3) .AddMetadataReference(pid3, s_mscorlib) .AddProjectReference(pid3, new ProjectReference(pid1)) .AddProjectReference(pid3, new ProjectReference(pid2)); var project3 = solution.GetProject(pid3); var comp3 = project3.GetCompilationAsync().Result; var classC = comp3.GetTypeByMetadataName("C"); var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid2, projectForBaseType.Id); // switch base type to A then try again var solution2 = solution.WithDocumentText(did3, SourceText.From(text4)); project3 = solution2.GetProject(pid3); comp3 = project3.GetCompilationAsync().Result; classC = comp3.GetTypeByMetadataName("C"); projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly); Assert.Equal(pid1, projectForBaseType.Id); } [WorkItem(1088127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088127")] [Fact] public void TestEncodingRetainedAfterTreeChanged() { var ws = new AdhocWorkspace(); var proj = ws.AddProject("proj", LanguageNames.CSharp); var doc = ws.AddDocument(proj.Id, "a.cs", SourceText.From("public class c { }", Encoding.UTF32)); Assert.Equal(Encoding.UTF32, doc.GetTextAsync().Result.Encoding); // updating root doesn't change original encoding var root = doc.GetSyntaxRootAsync().Result; var newRoot = root.WithLeadingTrivia(root.GetLeadingTrivia().Add(CS.SyntaxFactory.Whitespace(" "))); var newDoc = doc.WithSyntaxRoot(newRoot); Assert.Equal(Encoding.UTF32, newDoc.GetTextAsync().Result.Encoding); } [Fact] public void TestProjectWithNoBrokenReferencesHasNoIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); // Nothing should have incomplete references, and everything should build Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.True(project2.HasSuccessfullyLoadedAsync().Result); Assert.Single(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public void TestProjectWithBrokenCrossLanguageReferenceHasIncompleteReferences() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); workspace.AddDocument(project1.Id, "Broken.cs", SourceText.From("class ")); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); Assert.True(project1.HasSuccessfullyLoadedAsync().Result); Assert.False(project2.HasSuccessfullyLoadedAsync().Result); Assert.Empty(project2.GetCompilationAsync().Result.ExternalReferences); } [Fact] public async Task TestFrozenPartialProjectHasDifferentSemanticVersions() { using var workspace = CreateWorkspaceWithPartalSemantics(); var project = workspace.CurrentSolution.AddProject("CSharpProject", "CSharpProject", LanguageNames.CSharp); project = project.AddDocument("Extra.cs", SourceText.From("class Extra { }")).Project; var documentToFreeze = project.AddDocument("DocumentToFreeze.cs", SourceText.From("")); var frozenDocument = documentToFreeze.WithFrozenPartialSemantics(CancellationToken.None); // Because we had no compilation produced yet, we expect that only the DocumentToFreeze is in the compilation Assert.NotSame(frozenDocument, documentToFreeze); var tree = Assert.Single((await frozenDocument.Project.GetCompilationAsync()).SyntaxTrees); Assert.Equal("DocumentToFreeze.cs", tree.FilePath); // Versions should be different Assert.NotEqual( await documentToFreeze.Project.GetDependentSemanticVersionAsync(), await frozenDocument.Project.GetDependentSemanticVersionAsync()); Assert.NotEqual( await documentToFreeze.Project.GetSemanticVersionAsync(), await frozenDocument.Project.GetSemanticVersionAsync()); } [Fact] public void TestFrozenPartialProjectAlwaysIsIncomplete() { var workspace = new AdhocWorkspace(); var project1 = workspace.AddProject("CSharpProject", LanguageNames.CSharp); var project2 = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(project1.Id) })); var document = workspace.AddDocument(project2.Id, "Test.cs", SourceText.From("")); // Nothing should have incomplete references, and everything should build var frozenSolution = document.WithFrozenPartialSemantics(CancellationToken.None).Project.Solution; Assert.True(frozenSolution.GetProject(project1.Id).HasSuccessfullyLoadedAsync().Result); Assert.True(frozenSolution.GetProject(project2.Id).HasSuccessfullyLoadedAsync().Result); } [Fact] public void TestProjectCompletenessWithMultipleProjects() { GetMultipleProjects(out var csBrokenProject, out var vbNormalProject, out var dependsOnBrokenProject, out var dependsOnVbNormalProject, out var transitivelyDependsOnBrokenProjects, out var transitivelyDependsOnNormalProjects); // check flag for a broken project itself Assert.False(csBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for a normal project itself Assert.True(vbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference a broken project Assert.True(dependsOnBrokenProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that directly reference only normal project Assert.True(dependsOnVbNormalProject.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference a borken project // normal project -> normal project -> broken project Assert.True(transitivelyDependsOnBrokenProjects.HasSuccessfullyLoadedAsync().Result); // check flag for normal project that indirectly reference only normal project // normal project -> normal project -> normal project Assert.True(transitivelyDependsOnNormalProjects.HasSuccessfullyLoadedAsync().Result); } [Fact] public async Task TestMassiveFileSize() { // set max file length to 1 bytes var maxLength = 1; var workspace = new AdhocWorkspace(); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(FileTextLoaderOptions.FileLengthThreshold, maxLength))); using var root = new TempRoot(); var file = root.CreateFile(prefix: "massiveFile", extension: ".cs").WriteAllText("hello"); var loader = new FileTextLoader(file.Path, Encoding.UTF8); var textLength = FileUtilities.GetFileLength(file.Path); var expected = string.Format(WorkspacesResources.File_0_size_of_1_exceeds_maximum_allowed_size_of_2, file.Path, textLength, maxLength); var exceptionThrown = false; try { // test async one var unused = await loader.LoadTextAndVersionAsync(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); exceptionThrown = false; try { // test sync one var unused = loader.LoadTextAndVersionSynchronously(workspace, DocumentId.CreateNewId(ProjectId.CreateNewId()), CancellationToken.None); } catch (InvalidDataException ex) { exceptionThrown = true; Assert.Equal(expected, ex.Message); } Assert.True(exceptionThrown); } [Fact] [WorkItem(18697, "https://github.com/dotnet/roslyn/issues/18697")] public void TestWithSyntaxTree() { // get one to get to syntax tree factory using var workspace = CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations(); var solution = workspace.CurrentSolution; var dummyProject = solution.AddProject("dummy", "dummy", LanguageNames.CSharp); var factory = dummyProject.LanguageServices.SyntaxTreeFactory; // create the origin tree var strongTree = factory.ParseSyntaxTree("dummy", dummyProject.ParseOptions, SourceText.From("// emtpy"), CancellationToken.None); // create recoverable tree off the original tree var recoverableTree = factory.CreateRecoverableTree( dummyProject.Id, strongTree.FilePath, strongTree.Options, new ConstantValueSource<TextAndVersion>(TextAndVersion.Create(strongTree.GetText(), VersionStamp.Create(), strongTree.FilePath)), strongTree.GetText().Encoding, strongTree.GetRoot()); // create new tree before it ever getting root node var newTree = recoverableTree.WithFilePath("different/dummy"); // this shouldn't throw _ = newTree.GetRoot(); } [Fact] public void TestUpdateDocumentsOrder() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); VersionStamp GetVersion() => solution.GetProject(pid).Version; ImmutableArray<DocumentId> GetDocumentIds() => solution.GetProject(pid).DocumentIds.ToImmutableArray(); ImmutableArray<SyntaxTree> GetSyntaxTrees() { return solution.GetProject(pid).GetCompilationAsync().Result.SyntaxTrees.ToImmutableArray(); } solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); var oldVersion = GetVersion(); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newVersion = GetVersion(); // Make sure we have a new version because the order changed. Assert.NotEqual(oldVersion, newVersion); var documentIds = GetDocumentIds(); Assert.Equal(did5, documentIds[0]); Assert.Equal(did4, documentIds[1]); Assert.Equal(did3, documentIds[2]); Assert.Equal(did2, documentIds[3]); Assert.Equal(did1, documentIds[4]); var syntaxTrees = GetSyntaxTrees(); Assert.Equal(documentIds.Count(), syntaxTrees.Count()); Assert.Equal("test5.cs", syntaxTrees[0].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test4.cs", syntaxTrees[1].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test3.cs", syntaxTrees[2].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test2.cs", syntaxTrees[3].FilePath, StringComparer.OrdinalIgnoreCase); Assert.Equal("test1.cs", syntaxTrees[4].FilePath, StringComparer.OrdinalIgnoreCase); solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did4, did3, did2, did1 })); var newSameVersion = GetVersion(); // Make sure we have the same new version because the order hasn't changed. Assert.Equal(newVersion, newSameVersion); } [Fact] public void TestUpdateDocumentsOrderExceptions() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var pid = ProjectId.CreateNewId(); solution = solution.AddProject(pid, "test", "test.dll", LanguageNames.CSharp); var text1 = "public class Test1 {}"; var did1 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did1, "test1.cs", text1); var text2 = "public class Test2 {}"; var did2 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did2, "test2.cs", text2); var text3 = "public class Test3 {}"; var did3 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did3, "test3.cs", text3); var text4 = "public class Test4 {}"; var did4 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did4, "test4.cs", text4); var text5 = "public class Test5 {}"; var did5 = DocumentId.CreateNewId(pid); solution = solution.AddDocument(did5, "test5.cs", text5); solution = solution.RemoveDocument(did5); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.Create<DocumentId>())); Assert.Throws<ArgumentNullException>(() => solution = solution.WithProjectDocumentsOrder(pid, null)); Assert.Throws<InvalidOperationException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did5, did3, did2, did1 }))); Assert.Throws<ArgumentException>(() => solution = solution.WithProjectDocumentsOrder(pid, ImmutableList.CreateRange(new[] { did3, did2, did1 }))); } [Theory] [CombinatorialData] public async Task TestAddingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var newCompilation = await project.GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(newSyntaxTree, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); } [Theory] [CombinatorialData] public async Task TestAddingAndRemovingEditorConfigFileWithDiagnosticSeverity([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName) { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeAfterAddingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); project = solution.GetProject(projectId); var syntaxTreeAfterRemovingEditorConfig = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(provider.TryGetDiagnosticValue(syntaxTreeAfterAddingEditorConfig, "CA1234", CancellationToken.None, out _)); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterRemovingEditorConfig)); } [Theory] [CombinatorialData] public async Task TestChangingAnEditorConfigFile([CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic)] string languageName, bool useRecoverableTrees) { using var workspace = useRecoverableTrees ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var solution = workspace.CurrentSolution; var extension = languageName == LanguageNames.CSharp ? ".cs" : ".vb"; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", languageName); solution = solution.AddDocument(sourceDocumentId, "Test" + extension, "", filePath: @"Z:\Test" + extension); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var syntaxTreeBeforeEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var project = solution.GetProject(projectId); var provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA1234", CancellationToken.None, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.WithAnalyzerConfigDocumentTextLoader( editorConfigDocumentId, TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ndotnet_diagnostic.CA6789.severity = error"), VersionStamp.Default)), PreservationMode.PreserveValue); var syntaxTreeAfterEditorConfigChange = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); project = solution.GetProject(projectId); provider = project.CompilationOptions.SyntaxTreeOptionsProvider; Assert.Equal(provider, (await project.GetCompilationAsync()).Options.SyntaxTreeOptionsProvider); Assert.True(provider.TryGetDiagnosticValue(syntaxTreeBeforeEditorConfigChange, "CA6789", CancellationToken.None, out severity)); Assert.Equal(ReportDiagnostic.Error, severity); var finalCompilation = await project.GetCompilationAsync(); Assert.True(finalCompilation.ContainsSyntaxTree(syntaxTreeAfterEditorConfigChange)); } [Fact] public void TestAddingAndRemovingGlobalEditorConfigFileWithDiagnosticSeverity() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp); solution = solution.AddDocument(sourceDocumentId, "Test.cs", "", filePath: @"Z:\Test.cs"); var originalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(originalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".globalconfig", filePath: @"Z:\.globalconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("is_global = true\r\n\r\ndotnet_diagnostic.CA1234.severity = error"), VersionStamp.Default))))); var newProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.True(newProvider.TryGetGlobalDiagnosticValue("CA1234", default, out var severity)); Assert.Equal(ReportDiagnostic.Error, severity); solution = solution.RemoveAnalyzerConfigDocument(editorConfigDocumentId); var finalProvider = solution.GetProject(projectId).CompilationOptions.SyntaxTreeOptionsProvider; Assert.False(finalProvider.TryGetGlobalDiagnosticValue("CA1234", default, out _)); } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public async Task TestAddingEditorConfigFileWithIsGeneratedCodeOption() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var sourceDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", LanguageNames.CSharp) .WithProjectMetadataReferences(projectId, new[] { TestMetadata.Net451.mscorlib }) .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithNullableContextOptions(NullableContextOptions.Enable)); var src = @" class C { void M(C? c) { _ = c.ToString(); // warning CS8602: Dereference of a possibly null reference. } }"; solution = solution.AddDocument(sourceDocumentId, "Test.cs", src, filePath: @"Z:\Test.cs"); var originalSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var originalCompilation = await solution.GetProject(projectId).GetCompilationAsync(); // warning CS8602: Dereference of a possibly null reference. var diagnostics = originalCompilation.GetDiagnostics(); var diagnostic = Assert.Single(diagnostics); Assert.Equal("CS8602", diagnostic.Id); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); solution = solution.AddAnalyzerConfigDocuments(ImmutableArray.Create( DocumentInfo.Create( editorConfigDocumentId, ".editorconfig", filePath: @"Z:\.editorconfig", loader: TextLoader.From(TextAndVersion.Create(SourceText.From("[*.*]\r\n\r\ngenerated_code = true"), VersionStamp.Default))))); var newSyntaxTree = await solution.GetDocument(sourceDocumentId).GetSyntaxTreeAsync(); var newCompilation = await solution.GetProject(projectId).GetCompilationAsync(); Assert.Same(originalSyntaxTree, newSyntaxTree); Assert.NotSame(originalCompilation, newCompilation); Assert.NotEqual(originalCompilation.Options, newCompilation.Options); // warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // Auto-generated code requires an explicit '#nullable' directive in source. diagnostics = newCompilation.GetDiagnostics(); diagnostic = Assert.Single(diagnostics); Assert.Contains("CS8669", diagnostic.Id); } [Fact] public void NoCompilationProjectsHaveNullSyntaxTreesAndSemanticModels() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); var document = solution.GetDocument(documentId)!; Assert.False(document.TryGetSyntaxTree(out _)); Assert.Null(document.GetSyntaxTreeAsync().Result); Assert.Null(document.GetSyntaxTreeSynchronously(CancellationToken.None)); Assert.False(document.TryGetSemanticModel(out _)); Assert.Null(document.GetSemanticModelAsync().Result); } [Fact] public void ChangingFilePathOfFileInNoCompilationProjectWorks() { using var workspace = CreateWorkspace(new[] { typeof(NoCompilationLanguageServiceFactory) }); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); solution = solution.AddProject(projectId, "Test", "Test.dll", NoCompilationConstants.LanguageName); solution = solution.AddDocument(documentId, "Test.cs", "", filePath: @"Z:\Test.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); solution = solution.WithDocumentFilePath(documentId, @"Z:\NewPath.txt"); Assert.Null(solution.GetDocument(documentId)!.GetSyntaxTreeAsync().Result); } [Fact] public void AddingAndRemovingProjectsUpdatesFilePathMap() { using var workspace = CreateWorkspace(); var solution = workspace.CurrentSolution; var projectId = ProjectId.CreateNewId(); var editorConfigDocumentId = DocumentId.CreateNewId(projectId); const string editorConfigFilePath = @"Z:\.editorconfig"; var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Default, "Test", "Test", LanguageNames.CSharp) .WithAnalyzerConfigDocuments(new[] { DocumentInfo.Create(editorConfigDocumentId, ".editorconfig", filePath: editorConfigFilePath) }); solution = solution.AddProject(projectInfo); Assert.Equal(editorConfigDocumentId, Assert.Single(solution.GetDocumentIdsWithFilePath(editorConfigFilePath))); solution = solution.RemoveProject(projectId); Assert.Empty(solution.GetDocumentIdsWithFilePath(editorConfigFilePath)); } private static void GetMultipleProjects( out Project csBrokenProject, out Project vbNormalProject, out Project dependsOnBrokenProject, out Project dependsOnVbNormalProject, out Project transitivelyDependsOnBrokenProjects, out Project transitivelyDependsOnNormalProjects) { var workspace = new AdhocWorkspace(); csBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp).WithHasAllInformation(hasAllInformation: false)); vbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic)); dependsOnBrokenProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(csBrokenProject.Id), new ProjectReference(vbNormalProject.Id) })); dependsOnVbNormalProject = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(vbNormalProject.Id) })); transitivelyDependsOnBrokenProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "CSharpProject", "CSharpProject", LanguageNames.CSharp, projectReferences: new[] { new ProjectReference(dependsOnBrokenProject.Id) })); transitivelyDependsOnNormalProjects = workspace.AddProject( ProjectInfo.Create( ProjectId.CreateNewId(), VersionStamp.Create(), "VisualBasicProject", "VisualBasicProject", LanguageNames.VisualBasic, projectReferences: new[] { new ProjectReference(dependsOnVbNormalProject.Id) })); } [Fact, Trait(Traits.Feature, Traits.Features.Workspace)] public void TestOptionChangesForLanguagesNotInSolution() { // Create an empty solution with no projects. using var workspace = CreateWorkspace(); var s0 = workspace.CurrentSolution; var optionService = workspace.Services.GetRequiredService<IOptionService>(); // Apply an option change to a C# option. var option = GenerationOptions.PlaceSystemNamespaceFirst; var defaultValue = option.DefaultValue; var changedValue = !defaultValue; var options = s0.Options.WithChangedOption(option, LanguageNames.CSharp, changedValue); // Verify option change is preserved even if the solution has no project with that language. var s1 = s0.WithOptions(options); VerifyOptionSet(s1.Options); // Verify option value is preserved on adding a project for a different language. var s2 = s1.AddProject("P1", "A1", LanguageNames.VisualBasic).Solution; VerifyOptionSet(s2.Options); // Verify option value is preserved on roundtriping the option set (serialize and deserialize). var s3 = s2.AddProject("P2", "A2", LanguageNames.CSharp).Solution; var roundTripOptionSet = SerializeAndDeserialize((SerializableOptionSet)s3.Options, optionService); VerifyOptionSet(roundTripOptionSet); // Verify option value is preserved on removing a project. var s4 = s3.RemoveProject(s3.Projects.Single(p => p.Name == "P2").Id); VerifyOptionSet(s4.Options); return; void VerifyOptionSet(OptionSet optionSet) { Assert.Equal(changedValue, optionSet.GetOption(option, LanguageNames.CSharp)); Assert.Equal(defaultValue, optionSet.GetOption(option, LanguageNames.VisualBasic)); } static SerializableOptionSet SerializeAndDeserialize(SerializableOptionSet optionSet, IOptionService optionService) { using var stream = new MemoryStream(); using var writer = new ObjectWriter(stream); optionSet.Serialize(writer, CancellationToken.None); stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); return SerializableOptionSet.Deserialize(reader, optionService, CancellationToken.None); } } [Theory] [CombinatorialData] public async Task TestUpdatedDocumentTextIsObservablyConstantAsync(bool recoverable) { using var workspace = recoverable ? CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() : CreateWorkspace(); var pid = ProjectId.CreateNewId(); var text = SourceText.From("public class C { }"); var version = VersionStamp.Create(); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version))); var projInfo = ProjectInfo.Create( pid, version: VersionStamp.Default, name: "TestProject", assemblyName: "TestProject.dll", language: LanguageNames.CSharp, documents: new[] { docInfo }); var solution = workspace.CurrentSolution.AddProject(projInfo); var doc = solution.GetDocument(docInfo.Id); // change document var root = await doc.GetSyntaxRootAsync(); var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation()); Assert.NotSame(root, newRoot); var newDoc = doc.Project.Solution.WithDocumentSyntaxRoot(doc.Id, newRoot).GetDocument(doc.Id); Assert.NotSame(doc, newDoc); var newDocText = await newDoc.GetTextAsync(); var sameText = await newDoc.GetTextAsync(); Assert.Same(newDocText, sameText); var newDocTree = await newDoc.GetSyntaxTreeAsync(); var treeText = newDocTree.GetText(); Assert.Same(newDocText, treeText); } [Fact] public async Task ReplacingTextMultipleTimesDoesNotRootIntermediateCopiesIfCompilationNotAskedFor() { // This test replicates the pattern of some operation changing a bunch of files, but the files aren't kept open. // In Visual Studio we do large refactorings by opening files with an invisible editor, making changes, and closing // again. This process means we'll queue up intermediate changes to those files, but we don't want to hold onto // the intermediate edits when we don't really need to since the final version will be all that matters. using var workspace = CreateWorkspaceWithProjectAndDocuments(); var solution = workspace.CurrentSolution; var documentId = solution.Projects.Single().DocumentIds.Single(); // Fetch the compilation, so further edits are going to be incremental updates of this one var originalCompilation = await solution.Projects.Single().GetCompilationAsync(); // Create a source text we'll release and ensure it disappears. We'll also make sure we don't accidentally root // that solution in the middle. var sourceTextToRelease = ObjectReference.CreateFromFactory(static () => SourceText.From(Guid.NewGuid().ToString())); var solutionWithSourceTextToRelease = sourceTextToRelease.GetObjectReference( static (sourceText, document) => document.Project.Solution.WithDocumentText(document.Id, sourceText, PreservationMode.PreserveIdentity), solution.GetDocument(documentId)); // Change it again, this time by editing the text loader; this replicates us closing a file, and we don't want to pin the changes from the // prior change. var finalSolution = solutionWithSourceTextToRelease.GetObjectReference( static (s, documentId) => s.WithDocumentTextLoader(documentId, new TestTextLoader(Guid.NewGuid().ToString()), PreservationMode.PreserveValue), documentId).GetReference(); // The text in the middle shouldn't be held at all, since we replaced it. solutionWithSourceTextToRelease.ReleaseStrongReference(); sourceTextToRelease.AssertReleased(); GC.KeepAlive(finalSolution); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/Diagnostics/DiagnosticProviderMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal class DiagnosticProviderMetadata : ILanguageMetadata { public string Name { get; } public string Language { get; } public DiagnosticProviderMetadata(IDictionary<string, object> data) { Name = (string)data.GetValueOrDefault("Name"); Language = (string)data.GetValueOrDefault("Language"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal class DiagnosticProviderMetadata : ILanguageMetadata { public string Name { get; } public string Language { get; } public DiagnosticProviderMetadata(IDictionary<string, object> data) { Name = (string)data.GetValueOrDefault("Name"); Language = (string)data.GetValueOrDefault("Language"); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Analyzers/Core/Analyzers/RemoveUnnecessarySuppressions/AbstractRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { internal abstract class AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer, IPragmaSuppressionsAnalyzer { private static readonly LocalizableResourceString s_localizableRemoveUnnecessarySuppression = new( nameof(AnalyzersResources.Remove_unnecessary_suppression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); internal static readonly DiagnosticDescriptor s_removeUnnecessarySuppressionDescriptor = CreateDescriptor( IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, EnforceOnBuildValues.RemoveUnnecessarySuppression, s_localizableRemoveUnnecessarySuppression, s_localizableRemoveUnnecessarySuppression, isUnnecessary: true); private readonly Lazy<ImmutableHashSet<int>> _lazySupportedCompilerErrorCodes; protected AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer() : base(ImmutableArray.Create(s_removeUnnecessarySuppressionDescriptor), GeneratedCodeAnalysisFlags.None) { _lazySupportedCompilerErrorCodes = new Lazy<ImmutableHashSet<int>>(() => GetSupportedCompilerErrorCodes()); } protected abstract string CompilerErrorCodePrefix { get; } protected abstract int CompilerErrorCodeDigitCount { get; } protected abstract ISyntaxFacts SyntaxFacts { get; } protected abstract ISemanticFacts SemanticFacts { get; } protected abstract (Assembly assembly, string typeName) GetCompilerDiagnosticAnalyzerInfo(); private ImmutableHashSet<int> GetSupportedCompilerErrorCodes() { try { // Use reflection to fetch compiler diagnostic IDs that are supported in IDE live analysis. // Note that the unit test projects have IVT access to compiler layer, and hence can access this API. // We have unit tests that guard this reflection based logic and will fail if the API is changed // without updating the below code. var (assembly, compilerAnalyzerTypeName) = GetCompilerDiagnosticAnalyzerInfo(); var compilerAnalyzerType = assembly.GetType(compilerAnalyzerTypeName)!; var methodInfo = compilerAnalyzerType.GetMethod("GetSupportedErrorCodes", BindingFlags.Instance | BindingFlags.NonPublic)!; var compilerAnalyzerInstance = Activator.CreateInstance(compilerAnalyzerType); var supportedCodes = methodInfo.Invoke(compilerAnalyzerInstance, Array.Empty<object>()) as IEnumerable<int>; return supportedCodes?.ToImmutableHashSet() ?? ImmutableHashSet<int>.Empty; } catch (Exception ex) { Debug.Fail(ex.Message); return ImmutableHashSet<int>.Empty; } } public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) { // We do not register any normal analyzer actions as we need 'CompilationWithAnalyzers' // context to analyze unused suppressions using reported compiler and analyzer diagnostics. // Instead, the analyzer defines a special 'AnalyzeAsync' method that should be invoked // by the host with CompilationWithAnalyzers input to compute unused suppression diagnostics. } public async Task AnalyzeAsync( SemanticModel semanticModel, TextSpan? span, CompilationWithAnalyzers compilationWithAnalyzers, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getSupportedDiagnostics, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { // We need compilation with suppressed diagnostics for this feature. if (!compilationWithAnalyzers.Compilation.Options.ReportSuppressedDiagnostics) { return; } var tree = semanticModel.SyntaxTree; // Bail out if analyzer is suppressed on this file or project. // NOTE: Normally, we would not require this check in the analyzer as the analyzer driver has this optimization. // However, this is a special analyzer that is directly invoked by the analysis host (IDE), so we do this check here. if (compilationWithAnalyzers.Compilation.Options.SyntaxTreeOptionsProvider != null && compilationWithAnalyzers.Compilation.Options.SyntaxTreeOptionsProvider.TryGetDiagnosticValue(tree, IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, cancellationToken, out var severity) || compilationWithAnalyzers.Compilation.Options.SpecificDiagnosticOptions.TryGetValue(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, out severity)) { if (severity == ReportDiagnostic.Suppress) { return; } } // Bail out if analyzer has been turned off through options. var option = compilationWithAnalyzers.AnalysisOptions.Options?.GetOption( CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, tree, cancellationToken).Trim(); var (userIdExclusions, userCategoryExclusions, analyzerDisabled) = ParseUserExclusions(option); if (analyzerDisabled) { return; } // Bail out for generated code. if (tree.IsGeneratedCode(compilationWithAnalyzers.AnalysisOptions.Options, SyntaxFacts, cancellationToken)) { return; } var root = tree.GetRoot(cancellationToken); // Bail out if tree has syntax errors. if (root.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { return; } // Process pragma directives and inline SuppressMessageAttributes in the tree. // The core algorithm is as follows: // 1. Iterate through all the active pragmas and local SuppressMessageAttributes in the source file and // identify the pragmas and local SuppressMessageAttributes // with diagnostics IDs for which we support unnecesary suppression analysis. // 2. Build the following data structures during this loop: // a. A map from diagnostic ID to list of pragmas for the ID. This map tracks supported diagnostic IDs for this tree's pragmas. // b. A array of tuples of candidate pragmas sorted by span, along with associated IDs and enable/disable flag. // This sorted array allows mapping an unnecessary pragma to the corresponding toggling pragma pair for removal. // c. A map from pragmas to a boolean indicating if the pragma was used or not. // d. A map from diagnostic ID to list of SuppressMessageAttribute nodes for the ID. // This map tracks supported diagnostic IDs for this tree's SuppressMessageAttribute nodes. // e. A map from SuppressMessageAttribute nodes to a boolean indicating if the attribute was used or not. // f. A set of supported compiler diagnostic IDs that are used in pragmas or SuppressMessageAttributes in this file. // 3. Map the set of candidate diagnostic IDs to the analyzers that can report diagnostics with these IDs. // 4. Execute these analyzers to compute the diagnostics reported by these analyzers in this file. // 5. Iterate through the suppressed diagnostics from this list and do the following: // a. If the diagnostic was suppressed with a prama, mark the closest preceeeding disable pragma // which suppresses this ID as used/necessary. Also mark the matching restore pragma as used. // b. Otherwise, if the diagnostic was suppressed with SuppressMessageAttribute, mark the attribute as used. // 6. Finally, report a diagostic all the pragmas and SuppressMessageAttributes which have not been marked as used. using var _1 = PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>>.GetInstance(out var idToPragmasMap); using var _2 = ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)>.GetInstance(out var sortedPragmasWithIds); using var _3 = PooledDictionary<SyntaxTrivia, bool>.GetInstance(out var pragmasToIsUsedMap); using var _4 = PooledHashSet<string>.GetInstance(out var compilerDiagnosticIds); var hasPragmaInAnalysisSpan = ProcessPragmaDirectives(root, span, idToPragmasMap, pragmasToIsUsedMap, sortedPragmasWithIds, compilerDiagnosticIds, userIdExclusions); cancellationToken.ThrowIfCancellationRequested(); using var _5 = PooledDictionary<string, List<SyntaxNode>>.GetInstance(out var idToSuppressMessageAttributesMap); using var _6 = PooledDictionary<SyntaxNode, bool>.GetInstance(out var suppressMessageAttributesToIsUsedMap); var hasAttributeInAnalysisSpan = await ProcessSuppressMessageAttributesAsync(root, semanticModel, span, idToSuppressMessageAttributesMap, suppressMessageAttributesToIsUsedMap, userIdExclusions, userCategoryExclusions, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Bail out if we have no pragma directives or SuppressMessageAttributes to analyze. if (!hasPragmaInAnalysisSpan && !hasAttributeInAnalysisSpan) { return; } using var _8 = PooledHashSet<string>.GetInstance(out var idsToAnalyzeBuilder); idsToAnalyzeBuilder.AddAll(idToPragmasMap.Keys); idsToAnalyzeBuilder.AddAll(idToSuppressMessageAttributesMap.Keys); var idsToAnalyze = idsToAnalyzeBuilder.ToImmutableHashSet(); // Compute all the reported compiler and analyzer diagnostics for diagnostic IDs corresponding to pragmas in the tree. var (diagnostics, unhandledIds) = await GetReportedDiagnosticsForIdsAsync( idsToAnalyze, root, semanticModel, compilationWithAnalyzers, getSupportedDiagnostics, compilerDiagnosticIds, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Iterate through reported diagnostics which are suppressed in source through pragmas and mark the corresponding pragmas as used. await ProcessReportedDiagnosticsAsync(diagnostics, tree, compilationWithAnalyzers, idToPragmasMap, pragmasToIsUsedMap, idToSuppressMessageAttributesMap, suppressMessageAttributesToIsUsedMap, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Remove entries for unhandled diagnostic ids. foreach (var id in unhandledIds) { if (idToPragmasMap.TryGetValue(id, out var pragmas)) { foreach (var (pragma, _) in pragmas) { pragmasToIsUsedMap.Remove(pragma); } } if (idToSuppressMessageAttributesMap.TryGetValue(id, out var attributeNodes)) { foreach (var attributeNode in attributeNodes) { suppressMessageAttributesToIsUsedMap.Remove(attributeNode); } idToSuppressMessageAttributesMap.Remove(id); } } // Finally, report the unnecessary suppressions. var effectiveSeverity = severity.ToDiagnosticSeverity() ?? s_removeUnnecessarySuppressionDescriptor.DefaultSeverity; ReportUnnecessarySuppressions(pragmasToIsUsedMap, sortedPragmasWithIds, suppressMessageAttributesToIsUsedMap, reportDiagnostic, effectiveSeverity, compilationWithAnalyzers.Compilation); } private bool ProcessPragmaDirectives( SyntaxNode root, TextSpan? span, PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>> idToPragmasMap, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, PooledHashSet<string> compilerDiagnosticIds, ImmutableArray<string> userExclusions) { if (!root.ContainsDirectives) { return false; } using var _ = ArrayBuilder<string>.GetInstance(out var idsBuilder); var hasPragmaInAnalysisSpan = false; foreach (var trivia in root.DescendantTrivia()) { // Check if this is an active pragma with at least one applicable diagnostic ID/error code. // Note that a pragma can have multiple error codes, such as '#pragma warning disable ID0001, ID0002' if (SyntaxFacts.IsPragmaDirective(trivia, out var isDisable, out var isActive, out var errorCodeNodes) && isActive && errorCodeNodes.Count > 0) { // Iterate through each ID for this pragma and build the supported IDs. idsBuilder.Clear(); foreach (var errorCodeNode in errorCodeNodes) { // Ignore unsupported IDs and those excluded through user option. if (!IsSupportedId(errorCodeNode, out var id, out var isCompilerDiagnosticId) || userExclusions.Contains(id, StringComparer.OrdinalIgnoreCase)) { continue; } idsBuilder.Add(id); if (isCompilerDiagnosticId) { compilerDiagnosticIds.Add(id); } // Add entry to idToPragmasMap // Insert the pragmas in reverse order for easier processing later. if (!idToPragmasMap.TryGetValue(id, out var pragmasForIdInReverseOrder)) { pragmasForIdInReverseOrder = new List<(SyntaxTrivia pragma, bool isDisable)>(); idToPragmasMap.Add(id, pragmasForIdInReverseOrder); } pragmasForIdInReverseOrder.Insert(0, (trivia, isDisable)); } if (idsBuilder.Count == 0) { // No supported ID in this pragma. continue; } hasPragmaInAnalysisSpan = hasPragmaInAnalysisSpan || !span.HasValue || span.Value.OverlapsWith(trivia.Span); sortedPragmasWithIds.Add((trivia, idsBuilder.ToImmutable(), isDisable)); // Pragma directive is initialized as unnecessary at the start of the algorithm (value = false). // We will subsequently find required/used pragmas and update the entries in this map (value = true). pragmasToIsUsedMap.Add(trivia, false); } } return hasPragmaInAnalysisSpan; } private bool IsSupportedId( SyntaxNode idNode, [NotNullWhen(returnValue: true)] out string? id, out bool isCompilerDiagnosticId) { id = idNode.ToString(); // Compiler diagnostic pragma suppressions allow specifying just the integral ID. // For example: // "#pragma warning disable 0168" OR "#pragma warning disable 168" // is equivalent to // "#pragma warning disable CS0168" // We handle all the three supported formats for compiler diagnostic pragmas. var idWithoutPrefix = id.StartsWith(CompilerErrorCodePrefix) && id.Length == CompilerErrorCodePrefix.Length + CompilerErrorCodeDigitCount ? id[CompilerErrorCodePrefix.Length..] : id; // ID without prefix should parse as an integer for compiler diagnostics. if (int.TryParse(idWithoutPrefix, out var errorCode)) { // Normalize the ID to always be in the format with prefix. id = CompilerErrorCodePrefix + errorCode.ToString($"D{CompilerErrorCodeDigitCount}"); isCompilerDiagnosticId = true; return _lazySupportedCompilerErrorCodes.Value.Contains(errorCode); } isCompilerDiagnosticId = false; return IsSupportedAnalyzerDiagnosticId(id) && idWithoutPrefix == id; } private static bool IsSupportedAnalyzerDiagnosticId(string id) { switch (id) { case IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId: // Not supported as this would lead to recursion in computation. return false; case "format": case IDEDiagnosticIds.FormattingDiagnosticId: // Formatting analyzer is not supported as the analyzer does not seem to return suppressed IDE0055 diagnostics. return false; default: return true; } } private static (ImmutableArray<string> userIdExclusions, ImmutableArray<string> userCategoryExclusions, bool analyzerDisabled) ParseUserExclusions(string? userExclusions) { // Option value must be a comma separate list of diagnostic IDs or categories (with a "category:" prefix) to exclude from unnecessary pragma analysis. // We also allow a special keyword "all" to disable the analyzer completely. switch (userExclusions) { case "": case null: return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: false); case "all": return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: true); default: // Default string representation for unconfigured option value should be treated as no exclusions. if (userExclusions == CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions.DefaultValue) return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: false); break; } // We allow excluding category of diagnostics with a category prefix, for example "category: ExcludedCategory". const string categoryPrefix = "category:"; using var _1 = ArrayBuilder<string>.GetInstance(out var idBuilder); using var _2 = ArrayBuilder<string>.GetInstance(out var categoryBuilder); foreach (var part in userExclusions.Split(',')) { var trimmedPart = part.Trim(); if (trimmedPart.StartsWith(categoryPrefix, StringComparison.OrdinalIgnoreCase)) { trimmedPart = trimmedPart[categoryPrefix.Length..].Trim(); categoryBuilder.Add(trimmedPart); } else { idBuilder.Add(trimmedPart); } } return (userIdExclusions: idBuilder.ToImmutable(), userCategoryExclusions: categoryBuilder.ToImmutable(), analyzerDisabled: false); } private static async Task<(ImmutableArray<Diagnostic> reportedDiagnostics, ImmutableArray<string> unhandledIds)> GetReportedDiagnosticsForIdsAsync( ImmutableHashSet<string> idsToAnalyze, SyntaxNode root, SemanticModel semanticModel, CompilationWithAnalyzers compilationWithAnalyzers, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getSupportedDiagnostics, PooledHashSet<string> compilerDiagnosticIds, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<DiagnosticAnalyzer>.GetInstance(out var analyzersBuilder); using var _2 = ArrayBuilder<string>.GetInstance(out var unhandledIds); // First, we compute the relevant analyzers whose reported diagnostics need to be computed. var addedCompilerAnalyzer = false; var hasNonCompilerAnalyzers = idsToAnalyze.Count > compilerDiagnosticIds.Count; foreach (var analyzer in compilationWithAnalyzers.Analyzers) { if (!addedCompilerAnalyzer && analyzer.IsCompilerAnalyzer()) { addedCompilerAnalyzer = true; analyzersBuilder.Add(analyzer); if (!hasNonCompilerAnalyzers) { break; } continue; } if (hasNonCompilerAnalyzers) { Debug.Assert(!analyzer.IsCompilerAnalyzer()); bool? lazyIsUnhandledAnalyzer = null; foreach (var descriptor in getSupportedDiagnostics(analyzer)) { if (!idsToAnalyze.Contains(descriptor.Id)) { continue; } lazyIsUnhandledAnalyzer ??= descriptor.IsCompilationEnd() || analyzer is IPragmaSuppressionsAnalyzer; if (lazyIsUnhandledAnalyzer.Value) { unhandledIds.Add(descriptor.Id); } } if (lazyIsUnhandledAnalyzer.HasValue && !lazyIsUnhandledAnalyzer.Value) { analyzersBuilder.Add(analyzer); } } } // Then, we execute these analyzers on the current file to fetch these diagnostics. // Note that if an analyzer has already executed, then this will be just a cache access // as computed analyzer diagnostics are cached on CompilationWithAnalyzers instance. using var _3 = ArrayBuilder<Diagnostic>.GetInstance(out var reportedDiagnostics); if (!addedCompilerAnalyzer && compilerDiagnosticIds.Count > 0) { // Special case when compiler analyzer could not be found. Debug.Assert(semanticModel.Compilation.Options.ReportSuppressedDiagnostics); reportedDiagnostics.AddRange(root.GetDiagnostics()); reportedDiagnostics.AddRange(semanticModel.GetDiagnostics(cancellationToken: cancellationToken)); cancellationToken.ThrowIfCancellationRequested(); } if (analyzersBuilder.Count > 0) { var analyzers = analyzersBuilder.ToImmutable(); var analysisResult = await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel.SyntaxTree, analyzers, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (analysisResult.SyntaxDiagnostics.TryGetValue(semanticModel.SyntaxTree, out var diagnostics)) { AddAllDiagnostics(diagnostics, reportedDiagnostics); } analysisResult = await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel, filterSpan: null, analyzers, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (analysisResult.SemanticDiagnostics.TryGetValue(semanticModel.SyntaxTree, out diagnostics)) { AddAllDiagnostics(diagnostics, reportedDiagnostics); } AddAllCompilationDiagnosticsForTree(analysisResult, semanticModel.SyntaxTree, reportedDiagnostics); } return (reportedDiagnostics.ToImmutable(), unhandledIds.ToImmutable()); static void AddAllDiagnostics(ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> diagnostics, ArrayBuilder<Diagnostic> reportedDiagnostics) { foreach (var perAnalyzerDiagnostics in diagnostics.Values) { reportedDiagnostics.AddRange(perAnalyzerDiagnostics); } } static void AddAllCompilationDiagnosticsForTree(AnalysisResult analysisResult, SyntaxTree tree, ArrayBuilder<Diagnostic> reportedDiagnostics) { foreach (var perAnalyzerDiagnostics in analysisResult.CompilationDiagnostics.Values) { foreach (var diagnostic in perAnalyzerDiagnostics) { if (diagnostic.Location.SourceTree == tree) { reportedDiagnostics.Add(diagnostic); } } } } } private static async Task ProcessReportedDiagnosticsAsync( ImmutableArray<Diagnostic> diagnostics, SyntaxTree tree, CompilationWithAnalyzers compilationWithAnalyzers, PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>> idToPragmasMap, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, PooledDictionary<string, List<SyntaxNode>> idToSuppressMessageAttributesMap, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { if (!diagnostic.IsSuppressed) { continue; } var suppressionInfo = diagnostic.GetSuppressionInfo(compilationWithAnalyzers.Compilation); if (suppressionInfo == null) { continue; } if (suppressionInfo.Attribute is { } attribute) { await ProcessAttributeSuppressionsAsync(diagnostic, attribute, idToSuppressMessageAttributesMap, suppressMessageAttributesToIsUsedMap, cancellationToken).ConfigureAwait(false); } else { ProcessPragmaSuppressions(diagnostic, tree, idToPragmasMap, pragmasToIsUsedMap); } } return; static void ProcessPragmaSuppressions( Diagnostic diagnostic, SyntaxTree tree, PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>> idToPragmasMap, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap) { if (!idToPragmasMap.TryGetValue(diagnostic.Id, out var pragmasForIdInReverseOrder)) { return; } Debug.Assert(diagnostic.Location.IsInSource); Debug.Assert(diagnostic.Location.SourceTree == tree); // Process the pragmas for the document bottom-up, // finding the first disable pragma directive before the diagnostic span. // Mark this pragma and the corresponding enable pragma directive as used. SyntaxTrivia? lastEnablePragma = null; foreach (var (pragma, isDisable) in pragmasForIdInReverseOrder) { if (isDisable) { if (pragma.Span.End <= diagnostic.Location.SourceSpan.Start) { pragmasToIsUsedMap[pragma] = true; if (lastEnablePragma.HasValue) { pragmasToIsUsedMap[lastEnablePragma.Value] = true; } break; } } else { lastEnablePragma = pragma; } } } static async Task ProcessAttributeSuppressionsAsync( Diagnostic diagnostic, AttributeData attribute, PooledDictionary<string, List<SyntaxNode>> idToSuppressMessageAttributesMap, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, CancellationToken cancellationToken) { if (attribute.ApplicationSyntaxReference == null || !idToSuppressMessageAttributesMap.TryGetValue(diagnostic.Id, out var suppressMessageAttributesForId)) { return; } var attributeNode = await attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); foreach (var node in suppressMessageAttributesForId) { if (attributeNode == node) { suppressMessageAttributesToIsUsedMap[attributeNode] = true; return; } } } } private static void ReportUnnecessarySuppressions( PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, Action<Diagnostic> reportDiagnostic, DiagnosticSeverity severity, Compilation compilation) { using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var diagnosticsBuilder); AddUnnecessaryPragmaDiagnostics(diagnosticsBuilder, pragmasToIsUsedMap, sortedPragmasWithIds, severity); AddUnnecessarySuppressMessageAttributeDiagnostics(diagnosticsBuilder, suppressMessageAttributesToIsUsedMap, severity); // Apply the diagnostic filtering var effectiveDiagnostics = CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnosticsBuilder, compilation); foreach (var diagnostic in effectiveDiagnostics) { reportDiagnostic(diagnostic); } return; static void AddUnnecessaryPragmaDiagnostics( ArrayBuilder<Diagnostic> diagnosticsBuilder, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, DiagnosticSeverity severity) { foreach (var (pragma, isUsed) in pragmasToIsUsedMap) { if (!isUsed) { // We found an unnecessary pragma directive. // Try to find a matching disable/restore counterpart that toggles the pragma state. // This enables the code fix to simultaneously remove both the disable and restore directives. // If we don't find a matching pragma, report just the current pragma. ImmutableArray<Location> additionalLocations; if (TryGetTogglingPragmaDirective(pragma, sortedPragmasWithIds, out var togglePragma) && pragmasToIsUsedMap.TryGetValue(togglePragma, out var isToggleUsed) && !isToggleUsed) { additionalLocations = ImmutableArray.Create(togglePragma.GetLocation()); } else { additionalLocations = ImmutableArray<Location>.Empty; } var diagnostic = Diagnostic.Create(s_removeUnnecessarySuppressionDescriptor, pragma.GetLocation(), severity, additionalLocations, properties: null); diagnosticsBuilder.Add(diagnostic); } } } static void AddUnnecessarySuppressMessageAttributeDiagnostics( ArrayBuilder<Diagnostic> diagnosticsBuilder, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, DiagnosticSeverity severity) { foreach (var (attribute, isUsed) in suppressMessageAttributesToIsUsedMap) { if (!isUsed) { var diagnostic = Diagnostic.Create(s_removeUnnecessarySuppressionDescriptor, attribute.GetLocation(), severity, additionalLocations: null, properties: null); diagnosticsBuilder.Add(diagnostic); } } } } private static bool TryGetTogglingPragmaDirective( SyntaxTrivia pragma, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, out SyntaxTrivia togglePragma) { var indexOfPragma = sortedPragmasWithIds.FindIndex(p => p.pragma == pragma); var idsForPragma = sortedPragmasWithIds[indexOfPragma].ids; var isDisable = sortedPragmasWithIds[indexOfPragma].isDisable; var incrementOrDecrement = isDisable ? 1 : -1; var matchingPragmaStackCount = 0; for (var i = indexOfPragma + incrementOrDecrement; i >= 0 && i < sortedPragmasWithIds.Count; i += incrementOrDecrement) { var (nextPragma, nextPragmaIds, nextPragmaIsDisable) = sortedPragmasWithIds[i]; var intersect = nextPragmaIds.Intersect(idsForPragma).ToImmutableArray(); if (intersect.IsEmpty) { // Unrelated pragma continue; } if (intersect.Length != idsForPragma.Length) { // Partial intersection of IDs - bail out. togglePragma = default; return false; } // Found a pragma with same IDs. // Check if this is a pragma of same kind (disable/restore) or not. if (isDisable == nextPragmaIsDisable) { // Same pragma kind, increment the stack count matchingPragmaStackCount++; } else { // Found a pragma of opposite kind. if (matchingPragmaStackCount > 0) { // Not matching one for the input pragma, decrement stack count matchingPragmaStackCount--; } else { // Found the match. togglePragma = nextPragma; return true; } } } togglePragma = default; return false; } private async Task<bool> ProcessSuppressMessageAttributesAsync( SyntaxNode root, SemanticModel semanticModel, TextSpan? span, PooledDictionary<string, List<SyntaxNode>> idToSuppressMessageAttributesMap, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, ImmutableArray<string> userIdExclusions, ImmutableArray<string> userCategoryExclusions, CancellationToken cancellationToken) { var suppressMessageAttributeType = semanticModel.Compilation.SuppressMessageAttributeType(); if (suppressMessageAttributeType == null) { return false; } var declarationNodes = SyntaxFacts.GetTopLevelAndMethodLevelMembers(root); using var _ = PooledHashSet<ISymbol>.GetInstance(out var processedPartialSymbols); if (declarationNodes.Count > 0) { foreach (var node in declarationNodes) { if (span.HasValue && !node.FullSpan.Contains(span.Value)) { continue; } var symbols = SemanticFacts.GetDeclaredSymbols(semanticModel, node, cancellationToken); foreach (var symbol in symbols) { switch (symbol?.Kind) { // Local SuppressMessageAttributes are only applicable for types and members. case SymbolKind.NamedType: case SymbolKind.Method: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: break; default: continue; } // Skip already processed symbols from partial declarations var isPartial = symbol.Locations.Length > 1; if (isPartial && !processedPartialSymbols.Add(symbol)) { continue; } foreach (var attribute in symbol.GetAttributes()) { if (attribute.ApplicationSyntaxReference != null && TryGetSuppressedDiagnosticId(attribute, suppressMessageAttributeType, out var id, out var category)) { // Ignore unsupported IDs and those excluded through user option. if (!IsSupportedAnalyzerDiagnosticId(id) || userIdExclusions.Contains(id, StringComparer.OrdinalIgnoreCase) || category?.Length > 0 && userCategoryExclusions.Contains(category, StringComparer.OrdinalIgnoreCase)) { continue; } if (!idToSuppressMessageAttributesMap.TryGetValue(id, out var nodesForId)) { nodesForId = new List<SyntaxNode>(); idToSuppressMessageAttributesMap.Add(id, nodesForId); } var attributeNode = await attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); nodesForId.Add(attributeNode); // Initialize the attribute node as unnecessary at the start of the algorithm. // Later processing will identify attributes which are indeed responsible for suppressing diagnostics // and mark them as used. // NOTE: For attributes on partial symbols with multiple declarations, we conservatively // consider them as used and avoid unnecessary attribute analysis because that would potentially // require analysis across multiple files, which can be expensive from a performance standpoint. suppressMessageAttributesToIsUsedMap.Add(attributeNode, isPartial); } } } } } return idToSuppressMessageAttributesMap.Count > 0; } private static bool TryGetSuppressedDiagnosticId( AttributeData attribute, INamedTypeSymbol suppressMessageAttributeType, [NotNullWhen(returnValue: true)] out string? id, out string? category) { category = null; if (suppressMessageAttributeType.Equals(attribute.AttributeClass) && attribute.AttributeConstructor?.Parameters.Length >= 2 && attribute.AttributeConstructor.Parameters[1].Name == "checkId" && attribute.AttributeConstructor.Parameters[1].Type.SpecialType == SpecialType.System_String && attribute.ConstructorArguments.Length >= 2 && attribute.ConstructorArguments[1] is { Kind: TypedConstantKind.Primitive, Value: string checkId }) { // CheckId represents diagnostic ID, followed by an option ':' and name. // For example, "CA1801:ReviewUnusedParameters" var index = checkId.IndexOf(':'); id = index > 0 ? checkId.Substring(0, index) : checkId; if (attribute.AttributeConstructor.Parameters[0].Name == "category" && attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_String && attribute.ConstructorArguments[0] is { Kind: TypedConstantKind.Primitive, Value: string categoryArg }) { category = categoryArg; } return id.Length > 0; } id = null; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeQuality; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions { internal abstract class AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer : AbstractCodeQualityDiagnosticAnalyzer, IPragmaSuppressionsAnalyzer { private static readonly LocalizableResourceString s_localizableRemoveUnnecessarySuppression = new( nameof(AnalyzersResources.Remove_unnecessary_suppression), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); internal static readonly DiagnosticDescriptor s_removeUnnecessarySuppressionDescriptor = CreateDescriptor( IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, EnforceOnBuildValues.RemoveUnnecessarySuppression, s_localizableRemoveUnnecessarySuppression, s_localizableRemoveUnnecessarySuppression, isUnnecessary: true); private readonly Lazy<ImmutableHashSet<int>> _lazySupportedCompilerErrorCodes; protected AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer() : base(ImmutableArray.Create(s_removeUnnecessarySuppressionDescriptor), GeneratedCodeAnalysisFlags.None) { _lazySupportedCompilerErrorCodes = new Lazy<ImmutableHashSet<int>>(() => GetSupportedCompilerErrorCodes()); } protected abstract string CompilerErrorCodePrefix { get; } protected abstract int CompilerErrorCodeDigitCount { get; } protected abstract ISyntaxFacts SyntaxFacts { get; } protected abstract ISemanticFacts SemanticFacts { get; } protected abstract (Assembly assembly, string typeName) GetCompilerDiagnosticAnalyzerInfo(); private ImmutableHashSet<int> GetSupportedCompilerErrorCodes() { try { // Use reflection to fetch compiler diagnostic IDs that are supported in IDE live analysis. // Note that the unit test projects have IVT access to compiler layer, and hence can access this API. // We have unit tests that guard this reflection based logic and will fail if the API is changed // without updating the below code. var (assembly, compilerAnalyzerTypeName) = GetCompilerDiagnosticAnalyzerInfo(); var compilerAnalyzerType = assembly.GetType(compilerAnalyzerTypeName)!; var methodInfo = compilerAnalyzerType.GetMethod("GetSupportedErrorCodes", BindingFlags.Instance | BindingFlags.NonPublic)!; var compilerAnalyzerInstance = Activator.CreateInstance(compilerAnalyzerType); var supportedCodes = methodInfo.Invoke(compilerAnalyzerInstance, Array.Empty<object>()) as IEnumerable<int>; return supportedCodes?.ToImmutableHashSet() ?? ImmutableHashSet<int>.Empty; } catch (Exception ex) { Debug.Fail(ex.Message); return ImmutableHashSet<int>.Empty; } } public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) { // We do not register any normal analyzer actions as we need 'CompilationWithAnalyzers' // context to analyze unused suppressions using reported compiler and analyzer diagnostics. // Instead, the analyzer defines a special 'AnalyzeAsync' method that should be invoked // by the host with CompilationWithAnalyzers input to compute unused suppression diagnostics. } public async Task AnalyzeAsync( SemanticModel semanticModel, TextSpan? span, CompilationWithAnalyzers compilationWithAnalyzers, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getSupportedDiagnostics, Action<Diagnostic> reportDiagnostic, CancellationToken cancellationToken) { // We need compilation with suppressed diagnostics for this feature. if (!compilationWithAnalyzers.Compilation.Options.ReportSuppressedDiagnostics) { return; } var tree = semanticModel.SyntaxTree; // Bail out if analyzer is suppressed on this file or project. // NOTE: Normally, we would not require this check in the analyzer as the analyzer driver has this optimization. // However, this is a special analyzer that is directly invoked by the analysis host (IDE), so we do this check here. if (compilationWithAnalyzers.Compilation.Options.SyntaxTreeOptionsProvider != null && compilationWithAnalyzers.Compilation.Options.SyntaxTreeOptionsProvider.TryGetDiagnosticValue(tree, IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, cancellationToken, out var severity) || compilationWithAnalyzers.Compilation.Options.SpecificDiagnosticOptions.TryGetValue(IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId, out severity)) { if (severity == ReportDiagnostic.Suppress) { return; } } // Bail out if analyzer has been turned off through options. var option = compilationWithAnalyzers.AnalysisOptions.Options?.GetOption( CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions, tree, cancellationToken).Trim(); var (userIdExclusions, userCategoryExclusions, analyzerDisabled) = ParseUserExclusions(option); if (analyzerDisabled) { return; } // Bail out for generated code. if (tree.IsGeneratedCode(compilationWithAnalyzers.AnalysisOptions.Options, SyntaxFacts, cancellationToken)) { return; } var root = tree.GetRoot(cancellationToken); // Bail out if tree has syntax errors. if (root.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { return; } // Process pragma directives and inline SuppressMessageAttributes in the tree. // The core algorithm is as follows: // 1. Iterate through all the active pragmas and local SuppressMessageAttributes in the source file and // identify the pragmas and local SuppressMessageAttributes // with diagnostics IDs for which we support unnecesary suppression analysis. // 2. Build the following data structures during this loop: // a. A map from diagnostic ID to list of pragmas for the ID. This map tracks supported diagnostic IDs for this tree's pragmas. // b. A array of tuples of candidate pragmas sorted by span, along with associated IDs and enable/disable flag. // This sorted array allows mapping an unnecessary pragma to the corresponding toggling pragma pair for removal. // c. A map from pragmas to a boolean indicating if the pragma was used or not. // d. A map from diagnostic ID to list of SuppressMessageAttribute nodes for the ID. // This map tracks supported diagnostic IDs for this tree's SuppressMessageAttribute nodes. // e. A map from SuppressMessageAttribute nodes to a boolean indicating if the attribute was used or not. // f. A set of supported compiler diagnostic IDs that are used in pragmas or SuppressMessageAttributes in this file. // 3. Map the set of candidate diagnostic IDs to the analyzers that can report diagnostics with these IDs. // 4. Execute these analyzers to compute the diagnostics reported by these analyzers in this file. // 5. Iterate through the suppressed diagnostics from this list and do the following: // a. If the diagnostic was suppressed with a prama, mark the closest preceeeding disable pragma // which suppresses this ID as used/necessary. Also mark the matching restore pragma as used. // b. Otherwise, if the diagnostic was suppressed with SuppressMessageAttribute, mark the attribute as used. // 6. Finally, report a diagostic all the pragmas and SuppressMessageAttributes which have not been marked as used. using var _1 = PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>>.GetInstance(out var idToPragmasMap); using var _2 = ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)>.GetInstance(out var sortedPragmasWithIds); using var _3 = PooledDictionary<SyntaxTrivia, bool>.GetInstance(out var pragmasToIsUsedMap); using var _4 = PooledHashSet<string>.GetInstance(out var compilerDiagnosticIds); var hasPragmaInAnalysisSpan = ProcessPragmaDirectives(root, span, idToPragmasMap, pragmasToIsUsedMap, sortedPragmasWithIds, compilerDiagnosticIds, userIdExclusions); cancellationToken.ThrowIfCancellationRequested(); using var _5 = PooledDictionary<string, List<SyntaxNode>>.GetInstance(out var idToSuppressMessageAttributesMap); using var _6 = PooledDictionary<SyntaxNode, bool>.GetInstance(out var suppressMessageAttributesToIsUsedMap); var hasAttributeInAnalysisSpan = await ProcessSuppressMessageAttributesAsync(root, semanticModel, span, idToSuppressMessageAttributesMap, suppressMessageAttributesToIsUsedMap, userIdExclusions, userCategoryExclusions, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Bail out if we have no pragma directives or SuppressMessageAttributes to analyze. if (!hasPragmaInAnalysisSpan && !hasAttributeInAnalysisSpan) { return; } using var _8 = PooledHashSet<string>.GetInstance(out var idsToAnalyzeBuilder); idsToAnalyzeBuilder.AddAll(idToPragmasMap.Keys); idsToAnalyzeBuilder.AddAll(idToSuppressMessageAttributesMap.Keys); var idsToAnalyze = idsToAnalyzeBuilder.ToImmutableHashSet(); // Compute all the reported compiler and analyzer diagnostics for diagnostic IDs corresponding to pragmas in the tree. var (diagnostics, unhandledIds) = await GetReportedDiagnosticsForIdsAsync( idsToAnalyze, root, semanticModel, compilationWithAnalyzers, getSupportedDiagnostics, compilerDiagnosticIds, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Iterate through reported diagnostics which are suppressed in source through pragmas and mark the corresponding pragmas as used. await ProcessReportedDiagnosticsAsync(diagnostics, tree, compilationWithAnalyzers, idToPragmasMap, pragmasToIsUsedMap, idToSuppressMessageAttributesMap, suppressMessageAttributesToIsUsedMap, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Remove entries for unhandled diagnostic ids. foreach (var id in unhandledIds) { if (idToPragmasMap.TryGetValue(id, out var pragmas)) { foreach (var (pragma, _) in pragmas) { pragmasToIsUsedMap.Remove(pragma); } } if (idToSuppressMessageAttributesMap.TryGetValue(id, out var attributeNodes)) { foreach (var attributeNode in attributeNodes) { suppressMessageAttributesToIsUsedMap.Remove(attributeNode); } idToSuppressMessageAttributesMap.Remove(id); } } // Finally, report the unnecessary suppressions. var effectiveSeverity = severity.ToDiagnosticSeverity() ?? s_removeUnnecessarySuppressionDescriptor.DefaultSeverity; ReportUnnecessarySuppressions(pragmasToIsUsedMap, sortedPragmasWithIds, suppressMessageAttributesToIsUsedMap, reportDiagnostic, effectiveSeverity, compilationWithAnalyzers.Compilation); } private bool ProcessPragmaDirectives( SyntaxNode root, TextSpan? span, PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>> idToPragmasMap, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, PooledHashSet<string> compilerDiagnosticIds, ImmutableArray<string> userExclusions) { if (!root.ContainsDirectives) { return false; } using var _ = ArrayBuilder<string>.GetInstance(out var idsBuilder); var hasPragmaInAnalysisSpan = false; foreach (var trivia in root.DescendantTrivia()) { // Check if this is an active pragma with at least one applicable diagnostic ID/error code. // Note that a pragma can have multiple error codes, such as '#pragma warning disable ID0001, ID0002' if (SyntaxFacts.IsPragmaDirective(trivia, out var isDisable, out var isActive, out var errorCodeNodes) && isActive && errorCodeNodes.Count > 0) { // Iterate through each ID for this pragma and build the supported IDs. idsBuilder.Clear(); foreach (var errorCodeNode in errorCodeNodes) { // Ignore unsupported IDs and those excluded through user option. if (!IsSupportedId(errorCodeNode, out var id, out var isCompilerDiagnosticId) || userExclusions.Contains(id, StringComparer.OrdinalIgnoreCase)) { continue; } idsBuilder.Add(id); if (isCompilerDiagnosticId) { compilerDiagnosticIds.Add(id); } // Add entry to idToPragmasMap // Insert the pragmas in reverse order for easier processing later. if (!idToPragmasMap.TryGetValue(id, out var pragmasForIdInReverseOrder)) { pragmasForIdInReverseOrder = new List<(SyntaxTrivia pragma, bool isDisable)>(); idToPragmasMap.Add(id, pragmasForIdInReverseOrder); } pragmasForIdInReverseOrder.Insert(0, (trivia, isDisable)); } if (idsBuilder.Count == 0) { // No supported ID in this pragma. continue; } hasPragmaInAnalysisSpan = hasPragmaInAnalysisSpan || !span.HasValue || span.Value.OverlapsWith(trivia.Span); sortedPragmasWithIds.Add((trivia, idsBuilder.ToImmutable(), isDisable)); // Pragma directive is initialized as unnecessary at the start of the algorithm (value = false). // We will subsequently find required/used pragmas and update the entries in this map (value = true). pragmasToIsUsedMap.Add(trivia, false); } } return hasPragmaInAnalysisSpan; } private bool IsSupportedId( SyntaxNode idNode, [NotNullWhen(returnValue: true)] out string? id, out bool isCompilerDiagnosticId) { id = idNode.ToString(); // Compiler diagnostic pragma suppressions allow specifying just the integral ID. // For example: // "#pragma warning disable 0168" OR "#pragma warning disable 168" // is equivalent to // "#pragma warning disable CS0168" // We handle all the three supported formats for compiler diagnostic pragmas. var idWithoutPrefix = id.StartsWith(CompilerErrorCodePrefix) && id.Length == CompilerErrorCodePrefix.Length + CompilerErrorCodeDigitCount ? id[CompilerErrorCodePrefix.Length..] : id; // ID without prefix should parse as an integer for compiler diagnostics. if (int.TryParse(idWithoutPrefix, out var errorCode)) { // Normalize the ID to always be in the format with prefix. id = CompilerErrorCodePrefix + errorCode.ToString($"D{CompilerErrorCodeDigitCount}"); isCompilerDiagnosticId = true; return _lazySupportedCompilerErrorCodes.Value.Contains(errorCode); } isCompilerDiagnosticId = false; return IsSupportedAnalyzerDiagnosticId(id) && idWithoutPrefix == id; } private static bool IsSupportedAnalyzerDiagnosticId(string id) { switch (id) { case IDEDiagnosticIds.RemoveUnnecessarySuppressionDiagnosticId: // Not supported as this would lead to recursion in computation. return false; case "format": case IDEDiagnosticIds.FormattingDiagnosticId: // Formatting analyzer is not supported as the analyzer does not seem to return suppressed IDE0055 diagnostics. return false; default: return true; } } private static (ImmutableArray<string> userIdExclusions, ImmutableArray<string> userCategoryExclusions, bool analyzerDisabled) ParseUserExclusions(string? userExclusions) { // Option value must be a comma separate list of diagnostic IDs or categories (with a "category:" prefix) to exclude from unnecessary pragma analysis. // We also allow a special keyword "all" to disable the analyzer completely. switch (userExclusions) { case "": case null: return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: false); case "all": return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: true); default: // Default string representation for unconfigured option value should be treated as no exclusions. if (userExclusions == CodeStyleOptions2.RemoveUnnecessarySuppressionExclusions.DefaultValue) return (userIdExclusions: ImmutableArray<string>.Empty, userCategoryExclusions: ImmutableArray<string>.Empty, analyzerDisabled: false); break; } // We allow excluding category of diagnostics with a category prefix, for example "category: ExcludedCategory". const string categoryPrefix = "category:"; using var _1 = ArrayBuilder<string>.GetInstance(out var idBuilder); using var _2 = ArrayBuilder<string>.GetInstance(out var categoryBuilder); foreach (var part in userExclusions.Split(',')) { var trimmedPart = part.Trim(); if (trimmedPart.StartsWith(categoryPrefix, StringComparison.OrdinalIgnoreCase)) { trimmedPart = trimmedPart[categoryPrefix.Length..].Trim(); categoryBuilder.Add(trimmedPart); } else { idBuilder.Add(trimmedPart); } } return (userIdExclusions: idBuilder.ToImmutable(), userCategoryExclusions: categoryBuilder.ToImmutable(), analyzerDisabled: false); } private static async Task<(ImmutableArray<Diagnostic> reportedDiagnostics, ImmutableArray<string> unhandledIds)> GetReportedDiagnosticsForIdsAsync( ImmutableHashSet<string> idsToAnalyze, SyntaxNode root, SemanticModel semanticModel, CompilationWithAnalyzers compilationWithAnalyzers, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getSupportedDiagnostics, PooledHashSet<string> compilerDiagnosticIds, CancellationToken cancellationToken) { using var _1 = ArrayBuilder<DiagnosticAnalyzer>.GetInstance(out var analyzersBuilder); using var _2 = ArrayBuilder<string>.GetInstance(out var unhandledIds); // First, we compute the relevant analyzers whose reported diagnostics need to be computed. var addedCompilerAnalyzer = false; var hasNonCompilerAnalyzers = idsToAnalyze.Count > compilerDiagnosticIds.Count; foreach (var analyzer in compilationWithAnalyzers.Analyzers) { if (!addedCompilerAnalyzer && analyzer.IsCompilerAnalyzer()) { addedCompilerAnalyzer = true; analyzersBuilder.Add(analyzer); if (!hasNonCompilerAnalyzers) { break; } continue; } if (hasNonCompilerAnalyzers) { Debug.Assert(!analyzer.IsCompilerAnalyzer()); bool? lazyIsUnhandledAnalyzer = null; foreach (var descriptor in getSupportedDiagnostics(analyzer)) { if (!idsToAnalyze.Contains(descriptor.Id)) { continue; } lazyIsUnhandledAnalyzer ??= descriptor.IsCompilationEnd() || analyzer is IPragmaSuppressionsAnalyzer; if (lazyIsUnhandledAnalyzer.Value) { unhandledIds.Add(descriptor.Id); } } if (lazyIsUnhandledAnalyzer.HasValue && !lazyIsUnhandledAnalyzer.Value) { analyzersBuilder.Add(analyzer); } } } // Then, we execute these analyzers on the current file to fetch these diagnostics. // Note that if an analyzer has already executed, then this will be just a cache access // as computed analyzer diagnostics are cached on CompilationWithAnalyzers instance. using var _3 = ArrayBuilder<Diagnostic>.GetInstance(out var reportedDiagnostics); if (!addedCompilerAnalyzer && compilerDiagnosticIds.Count > 0) { // Special case when compiler analyzer could not be found. Debug.Assert(semanticModel.Compilation.Options.ReportSuppressedDiagnostics); reportedDiagnostics.AddRange(root.GetDiagnostics()); reportedDiagnostics.AddRange(semanticModel.GetDiagnostics(cancellationToken: cancellationToken)); cancellationToken.ThrowIfCancellationRequested(); } if (analyzersBuilder.Count > 0) { var analyzers = analyzersBuilder.ToImmutable(); var analysisResult = await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel.SyntaxTree, analyzers, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (analysisResult.SyntaxDiagnostics.TryGetValue(semanticModel.SyntaxTree, out var diagnostics)) { AddAllDiagnostics(diagnostics, reportedDiagnostics); } analysisResult = await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel, filterSpan: null, analyzers, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (analysisResult.SemanticDiagnostics.TryGetValue(semanticModel.SyntaxTree, out diagnostics)) { AddAllDiagnostics(diagnostics, reportedDiagnostics); } AddAllCompilationDiagnosticsForTree(analysisResult, semanticModel.SyntaxTree, reportedDiagnostics); } return (reportedDiagnostics.ToImmutable(), unhandledIds.ToImmutable()); static void AddAllDiagnostics(ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>> diagnostics, ArrayBuilder<Diagnostic> reportedDiagnostics) { foreach (var perAnalyzerDiagnostics in diagnostics.Values) { reportedDiagnostics.AddRange(perAnalyzerDiagnostics); } } static void AddAllCompilationDiagnosticsForTree(AnalysisResult analysisResult, SyntaxTree tree, ArrayBuilder<Diagnostic> reportedDiagnostics) { foreach (var perAnalyzerDiagnostics in analysisResult.CompilationDiagnostics.Values) { foreach (var diagnostic in perAnalyzerDiagnostics) { if (diagnostic.Location.SourceTree == tree) { reportedDiagnostics.Add(diagnostic); } } } } } private static async Task ProcessReportedDiagnosticsAsync( ImmutableArray<Diagnostic> diagnostics, SyntaxTree tree, CompilationWithAnalyzers compilationWithAnalyzers, PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>> idToPragmasMap, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, PooledDictionary<string, List<SyntaxNode>> idToSuppressMessageAttributesMap, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, CancellationToken cancellationToken) { foreach (var diagnostic in diagnostics) { if (!diagnostic.IsSuppressed) { continue; } var suppressionInfo = diagnostic.GetSuppressionInfo(compilationWithAnalyzers.Compilation); if (suppressionInfo == null) { continue; } if (suppressionInfo.Attribute is { } attribute) { await ProcessAttributeSuppressionsAsync(diagnostic, attribute, idToSuppressMessageAttributesMap, suppressMessageAttributesToIsUsedMap, cancellationToken).ConfigureAwait(false); } else { ProcessPragmaSuppressions(diagnostic, tree, idToPragmasMap, pragmasToIsUsedMap); } } return; static void ProcessPragmaSuppressions( Diagnostic diagnostic, SyntaxTree tree, PooledDictionary<string, List<(SyntaxTrivia pragma, bool isDisable)>> idToPragmasMap, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap) { if (!idToPragmasMap.TryGetValue(diagnostic.Id, out var pragmasForIdInReverseOrder)) { return; } Debug.Assert(diagnostic.Location.IsInSource); Debug.Assert(diagnostic.Location.SourceTree == tree); // Process the pragmas for the document bottom-up, // finding the first disable pragma directive before the diagnostic span. // Mark this pragma and the corresponding enable pragma directive as used. SyntaxTrivia? lastEnablePragma = null; foreach (var (pragma, isDisable) in pragmasForIdInReverseOrder) { if (isDisable) { if (pragma.Span.End <= diagnostic.Location.SourceSpan.Start) { pragmasToIsUsedMap[pragma] = true; if (lastEnablePragma.HasValue) { pragmasToIsUsedMap[lastEnablePragma.Value] = true; } break; } } else { lastEnablePragma = pragma; } } } static async Task ProcessAttributeSuppressionsAsync( Diagnostic diagnostic, AttributeData attribute, PooledDictionary<string, List<SyntaxNode>> idToSuppressMessageAttributesMap, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, CancellationToken cancellationToken) { if (attribute.ApplicationSyntaxReference == null || !idToSuppressMessageAttributesMap.TryGetValue(diagnostic.Id, out var suppressMessageAttributesForId)) { return; } var attributeNode = await attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); foreach (var node in suppressMessageAttributesForId) { if (attributeNode == node) { suppressMessageAttributesToIsUsedMap[attributeNode] = true; return; } } } } private static void ReportUnnecessarySuppressions( PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, Action<Diagnostic> reportDiagnostic, DiagnosticSeverity severity, Compilation compilation) { using var _ = ArrayBuilder<Diagnostic>.GetInstance(out var diagnosticsBuilder); AddUnnecessaryPragmaDiagnostics(diagnosticsBuilder, pragmasToIsUsedMap, sortedPragmasWithIds, severity); AddUnnecessarySuppressMessageAttributeDiagnostics(diagnosticsBuilder, suppressMessageAttributesToIsUsedMap, severity); // Apply the diagnostic filtering var effectiveDiagnostics = CompilationWithAnalyzers.GetEffectiveDiagnostics(diagnosticsBuilder, compilation); foreach (var diagnostic in effectiveDiagnostics) { reportDiagnostic(diagnostic); } return; static void AddUnnecessaryPragmaDiagnostics( ArrayBuilder<Diagnostic> diagnosticsBuilder, PooledDictionary<SyntaxTrivia, bool> pragmasToIsUsedMap, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, DiagnosticSeverity severity) { foreach (var (pragma, isUsed) in pragmasToIsUsedMap) { if (!isUsed) { // We found an unnecessary pragma directive. // Try to find a matching disable/restore counterpart that toggles the pragma state. // This enables the code fix to simultaneously remove both the disable and restore directives. // If we don't find a matching pragma, report just the current pragma. ImmutableArray<Location> additionalLocations; if (TryGetTogglingPragmaDirective(pragma, sortedPragmasWithIds, out var togglePragma) && pragmasToIsUsedMap.TryGetValue(togglePragma, out var isToggleUsed) && !isToggleUsed) { additionalLocations = ImmutableArray.Create(togglePragma.GetLocation()); } else { additionalLocations = ImmutableArray<Location>.Empty; } var diagnostic = Diagnostic.Create(s_removeUnnecessarySuppressionDescriptor, pragma.GetLocation(), severity, additionalLocations, properties: null); diagnosticsBuilder.Add(diagnostic); } } } static void AddUnnecessarySuppressMessageAttributeDiagnostics( ArrayBuilder<Diagnostic> diagnosticsBuilder, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, DiagnosticSeverity severity) { foreach (var (attribute, isUsed) in suppressMessageAttributesToIsUsedMap) { if (!isUsed) { var diagnostic = Diagnostic.Create(s_removeUnnecessarySuppressionDescriptor, attribute.GetLocation(), severity, additionalLocations: null, properties: null); diagnosticsBuilder.Add(diagnostic); } } } } private static bool TryGetTogglingPragmaDirective( SyntaxTrivia pragma, ArrayBuilder<(SyntaxTrivia pragma, ImmutableArray<string> ids, bool isDisable)> sortedPragmasWithIds, out SyntaxTrivia togglePragma) { var indexOfPragma = sortedPragmasWithIds.FindIndex(p => p.pragma == pragma); var idsForPragma = sortedPragmasWithIds[indexOfPragma].ids; var isDisable = sortedPragmasWithIds[indexOfPragma].isDisable; var incrementOrDecrement = isDisable ? 1 : -1; var matchingPragmaStackCount = 0; for (var i = indexOfPragma + incrementOrDecrement; i >= 0 && i < sortedPragmasWithIds.Count; i += incrementOrDecrement) { var (nextPragma, nextPragmaIds, nextPragmaIsDisable) = sortedPragmasWithIds[i]; var intersect = nextPragmaIds.Intersect(idsForPragma).ToImmutableArray(); if (intersect.IsEmpty) { // Unrelated pragma continue; } if (intersect.Length != idsForPragma.Length) { // Partial intersection of IDs - bail out. togglePragma = default; return false; } // Found a pragma with same IDs. // Check if this is a pragma of same kind (disable/restore) or not. if (isDisable == nextPragmaIsDisable) { // Same pragma kind, increment the stack count matchingPragmaStackCount++; } else { // Found a pragma of opposite kind. if (matchingPragmaStackCount > 0) { // Not matching one for the input pragma, decrement stack count matchingPragmaStackCount--; } else { // Found the match. togglePragma = nextPragma; return true; } } } togglePragma = default; return false; } private async Task<bool> ProcessSuppressMessageAttributesAsync( SyntaxNode root, SemanticModel semanticModel, TextSpan? span, PooledDictionary<string, List<SyntaxNode>> idToSuppressMessageAttributesMap, PooledDictionary<SyntaxNode, bool> suppressMessageAttributesToIsUsedMap, ImmutableArray<string> userIdExclusions, ImmutableArray<string> userCategoryExclusions, CancellationToken cancellationToken) { var suppressMessageAttributeType = semanticModel.Compilation.SuppressMessageAttributeType(); if (suppressMessageAttributeType == null) { return false; } var declarationNodes = SyntaxFacts.GetTopLevelAndMethodLevelMembers(root); using var _ = PooledHashSet<ISymbol>.GetInstance(out var processedPartialSymbols); if (declarationNodes.Count > 0) { foreach (var node in declarationNodes) { if (span.HasValue && !node.FullSpan.Contains(span.Value)) { continue; } var symbols = SemanticFacts.GetDeclaredSymbols(semanticModel, node, cancellationToken); foreach (var symbol in symbols) { switch (symbol?.Kind) { // Local SuppressMessageAttributes are only applicable for types and members. case SymbolKind.NamedType: case SymbolKind.Method: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: break; default: continue; } // Skip already processed symbols from partial declarations var isPartial = symbol.Locations.Length > 1; if (isPartial && !processedPartialSymbols.Add(symbol)) { continue; } foreach (var attribute in symbol.GetAttributes()) { if (attribute.ApplicationSyntaxReference != null && TryGetSuppressedDiagnosticId(attribute, suppressMessageAttributeType, out var id, out var category)) { // Ignore unsupported IDs and those excluded through user option. if (!IsSupportedAnalyzerDiagnosticId(id) || userIdExclusions.Contains(id, StringComparer.OrdinalIgnoreCase) || category?.Length > 0 && userCategoryExclusions.Contains(category, StringComparer.OrdinalIgnoreCase)) { continue; } if (!idToSuppressMessageAttributesMap.TryGetValue(id, out var nodesForId)) { nodesForId = new List<SyntaxNode>(); idToSuppressMessageAttributesMap.Add(id, nodesForId); } var attributeNode = await attribute.ApplicationSyntaxReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false); nodesForId.Add(attributeNode); // Initialize the attribute node as unnecessary at the start of the algorithm. // Later processing will identify attributes which are indeed responsible for suppressing diagnostics // and mark them as used. // NOTE: For attributes on partial symbols with multiple declarations, we conservatively // consider them as used and avoid unnecessary attribute analysis because that would potentially // require analysis across multiple files, which can be expensive from a performance standpoint. suppressMessageAttributesToIsUsedMap.Add(attributeNode, isPartial); } } } } } return idToSuppressMessageAttributesMap.Count > 0; } private static bool TryGetSuppressedDiagnosticId( AttributeData attribute, INamedTypeSymbol suppressMessageAttributeType, [NotNullWhen(returnValue: true)] out string? id, out string? category) { category = null; if (suppressMessageAttributeType.Equals(attribute.AttributeClass) && attribute.AttributeConstructor?.Parameters.Length >= 2 && attribute.AttributeConstructor.Parameters[1].Name == "checkId" && attribute.AttributeConstructor.Parameters[1].Type.SpecialType == SpecialType.System_String && attribute.ConstructorArguments.Length >= 2 && attribute.ConstructorArguments[1] is { Kind: TypedConstantKind.Primitive, Value: string checkId }) { // CheckId represents diagnostic ID, followed by an option ':' and name. // For example, "CA1801:ReviewUnusedParameters" var index = checkId.IndexOf(':'); id = index > 0 ? checkId.Substring(0, index) : checkId; if (attribute.AttributeConstructor.Parameters[0].Name == "category" && attribute.AttributeConstructor.Parameters[0].Type.SpecialType == SpecialType.System_String && attribute.ConstructorArguments[0] is { Kind: TypedConstantKind.Primitive, Value: string categoryArg }) { category = categoryArg; } return id.Length > 0; } id = null; return false; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Test2/Classification/SyntacticChangeRangeComputerTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification <UseExportProvider> Public Class SyntacticChangeRangeComputerTests Private Shared Function TestCSharp(markup As String, newText As String) As Task Return Test(markup, newText, LanguageNames.CSharp) End Function Private Shared Async Function Test(markup As String, newText As String, language As String) As Task Using workspace = TestWorkspace.Create(language, compilationOptions:=Nothing, parseOptions:=Nothing, markup) Dim testDocument = workspace.Documents(0) Dim startingDocument = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim spans = testDocument.SelectedSpans Assert.True(1 = spans.Count, "Test should have one spans in it representing the span to replace") Dim annotatedSpans = testDocument.AnnotatedSpans Assert.True(1 = annotatedSpans.Count, "Test should have a single {||} span representing the change span in the final document") Dim annotatedSpan = annotatedSpans.Single().Value.Single() Dim startingText = Await startingDocument.GetTextAsync() Dim startingTree = Await startingDocument.GetSyntaxTreeAsync() Dim startingRoot = Await startingTree.GetRootAsync() Dim endingText = startingText.Replace(spans(0), newText) Dim endingTree = startingTree.WithChangedText(endingText) Dim endingRoot = Await endingTree.GetRootAsync() Dim actualChange = SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(startingRoot, endingRoot, TimeSpan.MaxValue, Nothing) Dim expectedChange = New TextChangeRange( annotatedSpan, annotatedSpan.Length + newText.Length - spans(0).Length) Assert.True(expectedChange = actualChange, expectedChange.ToString() & " != " & actualChange.ToString() & vbCrLf & "Changed span was" & vbCrLf & startingText.ToString(actualChange.Span)) End Using End Function <Fact> Public Async Function TestIdentifierChangeInMethod1() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: Con[||]|}.WriteLine(0); } void M3() { } } ", "sole") End Function <Fact> Public Async Function TestIdentifierChangeInMethod2() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: Con[|sole|]|}.WriteLine(0); } void M3() { } } ", "") End Function <Fact> Public Async Function TestSplitClass1() As Task Await TestCSharp( " using X; public class C { void M1() { } {|changed: [||] void |}M2() { Console.WriteLine(0); } void M3() { } } ", "} class C2 {") End Function <Fact> Public Async Function TestMergeClass() As Task Await TestCSharp( " using X; public class C { void M1() { } {|changed: [|} class C2 {|] void |}M2() { Console.WriteLine(0); } void M3() { } } ", "") End Function <Fact> Public Async Function TestExtendComment() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [||] } void M3() { Console.WriteLine(""*/ Console.WriteLine("") |} } void M4() { } } ", "/*") End Function <Fact> Public Async Function TestRemoveComment() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [|/*|] } void M3() { Console.WriteLine(""*/ Console.WriteLine("") |} } void M4() { } } ", "") End Function <Fact> Public Async Function TestExtendCommentToEndOfFile() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [||] } void M3() { } void M4() { } } |}", "/*") End Function <Fact> Public Async Function TestDeleteFullFile() As Task Await TestCSharp( "{|changed:[| using X; public class C { void M1() { } void M2() { } void M3() { } void M4() { } } |]|}", "") End Function <Fact> Public Async Function InsertFullFile() As Task Await TestCSharp( "{|changed:[||]|}", " using X; public class C { void M1() { } void M2() { } void M3() { } void M4() { } } ") End Function <Fact> Public Async Function TestInsertDuplicateLineBelow() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { throw new NotImplementedException();[||] {|changed:|} } void M3() { } } ", " throw new NotImplementedException();") End Function <Fact> Public Async Function TestInsertDuplicateLineAbove() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() {[||] throw new NotImplementedException(); {|changed:|} } void M3() { } } ", " throw new NotImplementedException();") End Function <Fact> Public Async Function TestDeleteDuplicateLineBelow() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { throw new NotImplementedException(); {|changed: [|throw new NotImplementedException();|] } |} void M3() { } } ", "") End Function <Fact> Public Async Function TestDeleteDuplicateLineAbove() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [|throw new NotImplementedException();|] throw |}new NotImplementedException(); } void M3() { } } ", "") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Classification <UseExportProvider> Public Class SyntacticChangeRangeComputerTests Private Shared Function TestCSharp(markup As String, newText As String) As Task Return Test(markup, newText, LanguageNames.CSharp) End Function Private Shared Async Function Test(markup As String, newText As String, language As String) As Task Using workspace = TestWorkspace.Create(language, compilationOptions:=Nothing, parseOptions:=Nothing, markup) Dim testDocument = workspace.Documents(0) Dim startingDocument = workspace.CurrentSolution.GetDocument(testDocument.Id) Dim spans = testDocument.SelectedSpans Assert.True(1 = spans.Count, "Test should have one spans in it representing the span to replace") Dim annotatedSpans = testDocument.AnnotatedSpans Assert.True(1 = annotatedSpans.Count, "Test should have a single {||} span representing the change span in the final document") Dim annotatedSpan = annotatedSpans.Single().Value.Single() Dim startingText = Await startingDocument.GetTextAsync() Dim startingTree = Await startingDocument.GetSyntaxTreeAsync() Dim startingRoot = Await startingTree.GetRootAsync() Dim endingText = startingText.Replace(spans(0), newText) Dim endingTree = startingTree.WithChangedText(endingText) Dim endingRoot = Await endingTree.GetRootAsync() Dim actualChange = SyntacticChangeRangeComputer.ComputeSyntacticChangeRange(startingRoot, endingRoot, TimeSpan.MaxValue, Nothing) Dim expectedChange = New TextChangeRange( annotatedSpan, annotatedSpan.Length + newText.Length - spans(0).Length) Assert.True(expectedChange = actualChange, expectedChange.ToString() & " != " & actualChange.ToString() & vbCrLf & "Changed span was" & vbCrLf & startingText.ToString(actualChange.Span)) End Using End Function <Fact> Public Async Function TestIdentifierChangeInMethod1() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: Con[||]|}.WriteLine(0); } void M3() { } } ", "sole") End Function <Fact> Public Async Function TestIdentifierChangeInMethod2() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: Con[|sole|]|}.WriteLine(0); } void M3() { } } ", "") End Function <Fact> Public Async Function TestSplitClass1() As Task Await TestCSharp( " using X; public class C { void M1() { } {|changed: [||] void |}M2() { Console.WriteLine(0); } void M3() { } } ", "} class C2 {") End Function <Fact> Public Async Function TestMergeClass() As Task Await TestCSharp( " using X; public class C { void M1() { } {|changed: [|} class C2 {|] void |}M2() { Console.WriteLine(0); } void M3() { } } ", "") End Function <Fact> Public Async Function TestExtendComment() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [||] } void M3() { Console.WriteLine(""*/ Console.WriteLine("") |} } void M4() { } } ", "/*") End Function <Fact> Public Async Function TestRemoveComment() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [|/*|] } void M3() { Console.WriteLine(""*/ Console.WriteLine("") |} } void M4() { } } ", "") End Function <Fact> Public Async Function TestExtendCommentToEndOfFile() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [||] } void M3() { } void M4() { } } |}", "/*") End Function <Fact> Public Async Function TestDeleteFullFile() As Task Await TestCSharp( "{|changed:[| using X; public class C { void M1() { } void M2() { } void M3() { } void M4() { } } |]|}", "") End Function <Fact> Public Async Function InsertFullFile() As Task Await TestCSharp( "{|changed:[||]|}", " using X; public class C { void M1() { } void M2() { } void M3() { } void M4() { } } ") End Function <Fact> Public Async Function TestInsertDuplicateLineBelow() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { throw new NotImplementedException();[||] {|changed:|} } void M3() { } } ", " throw new NotImplementedException();") End Function <Fact> Public Async Function TestInsertDuplicateLineAbove() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() {[||] throw new NotImplementedException(); {|changed:|} } void M3() { } } ", " throw new NotImplementedException();") End Function <Fact> Public Async Function TestDeleteDuplicateLineBelow() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { throw new NotImplementedException(); {|changed: [|throw new NotImplementedException();|] } |} void M3() { } } ", "") End Function <Fact> Public Async Function TestDeleteDuplicateLineAbove() As Task Await TestCSharp( " using X; public class C { void M1() { } void M2() { {|changed: [|throw new NotImplementedException();|] throw |}new NotImplementedException(); } void M3() { } } ", "") End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Portable/Symbols/SymbolEqualityComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SymbolEqualityComparer : EqualityComparer<Symbol> { internal static readonly EqualityComparer<Symbol> ConsiderEverything = new SymbolEqualityComparer(TypeCompareKind.ConsiderEverything); internal static readonly EqualityComparer<Symbol> IgnoringTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static EqualityComparer<Symbol> IncludeNullability => ConsiderEverything; /// <summary> /// A comparer that treats dynamic and object as "the same" types, and also ignores tuple element names differences. /// </summary> internal static readonly EqualityComparer<Symbol> IgnoringDynamicTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static readonly EqualityComparer<Symbol> IgnoringNullable = new SymbolEqualityComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static readonly EqualityComparer<Symbol> ObliviousNullableModifierMatchesAny = new SymbolEqualityComparer(TypeCompareKind.ObliviousNullableModifierMatchesAny); internal static readonly EqualityComparer<Symbol> AllIgnoreOptions = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions); internal static readonly EqualityComparer<Symbol> AllIgnoreOptionsPlusNullableWithUnknownMatchesAny = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions & ~(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); internal static readonly EqualityComparer<Symbol> CLRSignature = new SymbolEqualityComparer(TypeCompareKind.CLRSignatureCompareOptions); private readonly TypeCompareKind _comparison; private SymbolEqualityComparer(TypeCompareKind comparison) { _comparison = comparison; } public override int GetHashCode(Symbol obj) { return obj is null ? 0 : obj.GetHashCode(); } public override bool Equals(Symbol x, Symbol y) { return x is null ? y is null : x.Equals(y, _comparison); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class SymbolEqualityComparer : EqualityComparer<Symbol> { internal static readonly EqualityComparer<Symbol> ConsiderEverything = new SymbolEqualityComparer(TypeCompareKind.ConsiderEverything); internal static readonly EqualityComparer<Symbol> IgnoringTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static EqualityComparer<Symbol> IncludeNullability => ConsiderEverything; /// <summary> /// A comparer that treats dynamic and object as "the same" types, and also ignores tuple element names differences. /// </summary> internal static readonly EqualityComparer<Symbol> IgnoringDynamicTupleNamesAndNullability = new SymbolEqualityComparer(TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static readonly EqualityComparer<Symbol> IgnoringNullable = new SymbolEqualityComparer(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); internal static readonly EqualityComparer<Symbol> ObliviousNullableModifierMatchesAny = new SymbolEqualityComparer(TypeCompareKind.ObliviousNullableModifierMatchesAny); internal static readonly EqualityComparer<Symbol> AllIgnoreOptions = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions); internal static readonly EqualityComparer<Symbol> AllIgnoreOptionsPlusNullableWithUnknownMatchesAny = new SymbolEqualityComparer(TypeCompareKind.AllIgnoreOptions & ~(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); internal static readonly EqualityComparer<Symbol> CLRSignature = new SymbolEqualityComparer(TypeCompareKind.CLRSignatureCompareOptions); private readonly TypeCompareKind _comparison; private SymbolEqualityComparer(TypeCompareKind comparison) { _comparison = comparison; } public override int GetHashCode(Symbol obj) { return obj is null ? 0 : obj.GetHashCode(); } public override bool Equals(Symbol x, Symbol y) { return x is null ? y is null : x.Equals(y, _comparison); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Test/Core/Compilation/IRuntimeEnvironment.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { public static class RuntimeEnvironmentFactory { private static readonly Lazy<IRuntimeEnvironmentFactory> s_lazyFactory = new Lazy<IRuntimeEnvironmentFactory>(RuntimeUtilities.GetRuntimeEnvironmentFactory); internal static IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies = null) { return s_lazyFactory.Value.Create(additionalDependencies); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { using (var runtimeEnvironment = Create()) { runtimeEnvironment.CaptureOutput(action, expectedLength, out output, out errorOutput); } } } internal struct EmitOutput { internal ImmutableArray<byte> Assembly { get; } internal ImmutableArray<byte> Pdb { get; } internal EmitOutput(ImmutableArray<byte> assembly, ImmutableArray<byte> pdb) { Assembly = assembly; if (pdb.IsDefault) { // We didn't emit a discrete PDB file, so we'll look for an embedded PDB instead. using (var peReader = new PEReader(Assembly)) { DebugDirectoryEntry portablePdbEntry = peReader.ReadDebugDirectory().FirstOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); if (portablePdbEntry.DataSize != 0) { using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(portablePdbEntry)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); pdb = readMetadata(mdReader); } } } } Pdb = pdb; unsafe ImmutableArray<byte> readMetadata(MetadataReader mdReader) { var length = mdReader.MetadataLength; var bytes = new byte[length]; Marshal.Copy((IntPtr)mdReader.MetadataPointer, bytes, 0, length); return ImmutableArray.Create(bytes); } } } internal static class RuntimeEnvironmentUtilities { private static int s_dumpCount; private static IEnumerable<ModuleMetadata> EnumerateModules(Metadata metadata) { return (metadata.Kind == MetadataImageKind.Assembly) ? ((AssemblyMetadata)metadata).GetModules().AsEnumerable() : SpecializedCollections.SingletonEnumerable((ModuleMetadata)metadata); } /// <summary> /// Emit all of the references which are not directly or indirectly a <see cref="Compilation"/> value. /// </summary> internal static void EmitReferences(Compilation compilation, HashSet<string> fullNameSet, List<ModuleData> dependencies, DiagnosticBag diagnostics) { // NOTE: specifically don't need to consider previous submissions since they will always be compilations. foreach (var metadataReference in compilation.References) { if (metadataReference is CompilationReference) { continue; } var peRef = (PortableExecutableReference)metadataReference; var metadata = peRef.GetMetadataNoCopy(); var isManifestModule = peRef.Properties.Kind == MetadataImageKind.Assembly; var identity = isManifestModule ? ((AssemblyMetadata)metadata).GetAssembly().Identity : null; // If this is an indirect reference to a Compilation then it is already been emitted // so no more work to be done. if (isManifestModule && fullNameSet.Contains(identity.GetDisplayName())) { continue; } foreach (var module in EnumerateModules(metadata)) { ImmutableArray<byte> bytes = module.Module.PEReaderOpt.GetEntireImage().GetContent(); ModuleData moduleData; if (isManifestModule) { fullNameSet.Add(identity.GetDisplayName()); moduleData = new ModuleData(identity, OutputKind.DynamicallyLinkedLibrary, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } else { moduleData = new ModuleData(module.Name, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } dependencies.Add(moduleData); isManifestModule = false; } } } /// <summary> /// Find all of the <see cref="Compilation"/> values reachable from this instance. /// </summary> /// <param name="original"></param> /// <returns></returns> private static List<Compilation> FindReferencedCompilations(Compilation original) { var list = new List<Compilation>(); var toVisit = new Queue<Compilation>(FindDirectReferencedCompilations(original)); while (toVisit.Count > 0) { var current = toVisit.Dequeue(); if (list.Contains(current)) { continue; } list.Add(current); foreach (var other in FindDirectReferencedCompilations(current)) { toVisit.Enqueue(other); } } return list; } private static List<Compilation> FindDirectReferencedCompilations(Compilation compilation) { var list = new List<Compilation>(); var previousCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousCompilation != null) { list.Add(previousCompilation); } foreach (var reference in compilation.References.OfType<CompilationReference>()) { list.Add(reference.Compilation); } return list; } internal static EmitOutput? EmitCompilation( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, List<ModuleData> dependencies, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions ) { // A Compilation can appear multiple times in a dependency graph as both a Compilation and as a MetadataReference // value. Iterate the Compilations eagerly so they are always emitted directly and later references can re-use // the value. This gives better, and consistent, diagnostic information. var referencedCompilations = FindReferencedCompilations(compilation); var fullNameSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var referencedCompilation in referencedCompilations) { var emitData = EmitCompilationCore(referencedCompilation, null, diagnostics, null, emitOptions); if (emitData.HasValue) { var moduleData = new ModuleData(referencedCompilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, emitData.Value.Assembly, pdb: default(ImmutableArray<byte>), inMemoryModule: true); fullNameSet.Add(moduleData.Id.FullName); dependencies.Add(moduleData); } } // Now that the Compilation values have been emitted, emit the non-compilation references foreach (var current in (new[] { compilation }).Concat(referencedCompilations)) { EmitReferences(current, fullNameSet, dependencies, diagnostics); } return EmitCompilationCore(compilation, manifestResources, diagnostics, testData, emitOptions); } internal static EmitOutput? EmitCompilationCore( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions) { emitOptions ??= EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded); using var executableStream = new MemoryStream(); var pdb = default(ImmutableArray<byte>); var assembly = default(ImmutableArray<byte>); var pdbStream = (emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded) ? new MemoryStream() : null; var embeddedTexts = compilation.SyntaxTrees .Select(t => (filePath: t.FilePath, text: t.GetText())) .Where(t => t.text.CanBeEmbedded && !string.IsNullOrEmpty(t.filePath)) .Select(t => EmbeddedText.FromSource(t.filePath, t.text)) .ToImmutableArray(); EmitResult result; try { result = compilation.Emit( executableStream, metadataPEStream: null, pdbStream: pdbStream, xmlDocumentationStream: null, win32Resources: null, manifestResources: manifestResources, options: emitOptions, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts, rebuildData: null, testData: testData, cancellationToken: default); } finally { if (pdbStream != null) { pdb = pdbStream.ToImmutable(); pdbStream.Dispose(); } } diagnostics.AddRange(result.Diagnostics); assembly = executableStream.ToImmutable(); if (result.Success) { return new EmitOutput(assembly, pdb); } return null; } public static string DumpAssemblyData(IEnumerable<ModuleData> modules, out string dumpDirectory) { dumpDirectory = null; var sb = new StringBuilder(); foreach (var module in modules) { // Limit the number of dumps to 10. After 10 we're likely in a bad state and are // dumping lots of unnecessary data. if (s_dumpCount > 10) { break; } if (module.InMemoryModule) { Interlocked.Increment(ref s_dumpCount); if (dumpDirectory == null) { dumpDirectory = TempRoot.Root; try { Directory.CreateDirectory(dumpDirectory); } catch { // Okay if directory already exists } } string fileName; if (module.Kind == OutputKind.NetModule) { fileName = module.FullName; } else { AssemblyIdentity.TryParseDisplayName(module.FullName, out var identity); fileName = identity.Name; } string pePath = Path.Combine(dumpDirectory, fileName + module.Kind.GetDefaultExtension()); try { module.Image.WriteToFile(pePath); } catch (ArgumentException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } catch (IOException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } string pdbPath; if (!module.Pdb.IsDefaultOrEmpty) { pdbPath = Path.Combine(dumpDirectory, fileName + ".pdb"); try { module.Pdb.WriteToFile(pdbPath); } catch (ArgumentException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } catch (IOException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } } else { pdbPath = null; } sb.Append("PE(" + module.Kind + "): "); sb.AppendLine(pePath); if (pdbPath != null) { sb.Append("PDB: "); sb.AppendLine(pdbPath); } } } return sb.ToString(); } } public interface IRuntimeEnvironmentFactory { IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies); } public interface IRuntimeEnvironment : IDisposable { void Emit(Compilation mainCompilation, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, bool usePdbForDebugging = false); int Execute(string moduleName, string[] args, string expectedOutput); ImmutableArray<byte> GetMainImage(); ImmutableArray<byte> GetMainPdb(); ImmutableArray<Diagnostic> GetDiagnostics(); SortedSet<string> GetMemberSignaturesFromMetadata(string fullyQualifiedTypeName, string memberName); IList<ModuleData> GetAllModuleData(); void Verify(Verification verification); string[] VerifyModules(string[] modulesToVerify); void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput); } internal interface IInternalRuntimeEnvironment { CompilationTestData GetCompilationTestData(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Utilities; namespace Roslyn.Test.Utilities { public static class RuntimeEnvironmentFactory { private static readonly Lazy<IRuntimeEnvironmentFactory> s_lazyFactory = new Lazy<IRuntimeEnvironmentFactory>(RuntimeUtilities.GetRuntimeEnvironmentFactory); internal static IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies = null) { return s_lazyFactory.Value.Create(additionalDependencies); } public static void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput) { using (var runtimeEnvironment = Create()) { runtimeEnvironment.CaptureOutput(action, expectedLength, out output, out errorOutput); } } } internal struct EmitOutput { internal ImmutableArray<byte> Assembly { get; } internal ImmutableArray<byte> Pdb { get; } internal EmitOutput(ImmutableArray<byte> assembly, ImmutableArray<byte> pdb) { Assembly = assembly; if (pdb.IsDefault) { // We didn't emit a discrete PDB file, so we'll look for an embedded PDB instead. using (var peReader = new PEReader(Assembly)) { DebugDirectoryEntry portablePdbEntry = peReader.ReadDebugDirectory().FirstOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb); if (portablePdbEntry.DataSize != 0) { using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(portablePdbEntry)) { var mdReader = embeddedMetadataProvider.GetMetadataReader(); pdb = readMetadata(mdReader); } } } } Pdb = pdb; unsafe ImmutableArray<byte> readMetadata(MetadataReader mdReader) { var length = mdReader.MetadataLength; var bytes = new byte[length]; Marshal.Copy((IntPtr)mdReader.MetadataPointer, bytes, 0, length); return ImmutableArray.Create(bytes); } } } internal static class RuntimeEnvironmentUtilities { private static int s_dumpCount; private static IEnumerable<ModuleMetadata> EnumerateModules(Metadata metadata) { return (metadata.Kind == MetadataImageKind.Assembly) ? ((AssemblyMetadata)metadata).GetModules().AsEnumerable() : SpecializedCollections.SingletonEnumerable((ModuleMetadata)metadata); } /// <summary> /// Emit all of the references which are not directly or indirectly a <see cref="Compilation"/> value. /// </summary> internal static void EmitReferences(Compilation compilation, HashSet<string> fullNameSet, List<ModuleData> dependencies, DiagnosticBag diagnostics) { // NOTE: specifically don't need to consider previous submissions since they will always be compilations. foreach (var metadataReference in compilation.References) { if (metadataReference is CompilationReference) { continue; } var peRef = (PortableExecutableReference)metadataReference; var metadata = peRef.GetMetadataNoCopy(); var isManifestModule = peRef.Properties.Kind == MetadataImageKind.Assembly; var identity = isManifestModule ? ((AssemblyMetadata)metadata).GetAssembly().Identity : null; // If this is an indirect reference to a Compilation then it is already been emitted // so no more work to be done. if (isManifestModule && fullNameSet.Contains(identity.GetDisplayName())) { continue; } foreach (var module in EnumerateModules(metadata)) { ImmutableArray<byte> bytes = module.Module.PEReaderOpt.GetEntireImage().GetContent(); ModuleData moduleData; if (isManifestModule) { fullNameSet.Add(identity.GetDisplayName()); moduleData = new ModuleData(identity, OutputKind.DynamicallyLinkedLibrary, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } else { moduleData = new ModuleData(module.Name, bytes, pdb: default(ImmutableArray<byte>), inMemoryModule: true); } dependencies.Add(moduleData); isManifestModule = false; } } } /// <summary> /// Find all of the <see cref="Compilation"/> values reachable from this instance. /// </summary> /// <param name="original"></param> /// <returns></returns> private static List<Compilation> FindReferencedCompilations(Compilation original) { var list = new List<Compilation>(); var toVisit = new Queue<Compilation>(FindDirectReferencedCompilations(original)); while (toVisit.Count > 0) { var current = toVisit.Dequeue(); if (list.Contains(current)) { continue; } list.Add(current); foreach (var other in FindDirectReferencedCompilations(current)) { toVisit.Enqueue(other); } } return list; } private static List<Compilation> FindDirectReferencedCompilations(Compilation compilation) { var list = new List<Compilation>(); var previousCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation; if (previousCompilation != null) { list.Add(previousCompilation); } foreach (var reference in compilation.References.OfType<CompilationReference>()) { list.Add(reference.Compilation); } return list; } internal static EmitOutput? EmitCompilation( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, List<ModuleData> dependencies, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions ) { // A Compilation can appear multiple times in a dependency graph as both a Compilation and as a MetadataReference // value. Iterate the Compilations eagerly so they are always emitted directly and later references can re-use // the value. This gives better, and consistent, diagnostic information. var referencedCompilations = FindReferencedCompilations(compilation); var fullNameSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var referencedCompilation in referencedCompilations) { var emitData = EmitCompilationCore(referencedCompilation, null, diagnostics, null, emitOptions); if (emitData.HasValue) { var moduleData = new ModuleData(referencedCompilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, emitData.Value.Assembly, pdb: default(ImmutableArray<byte>), inMemoryModule: true); fullNameSet.Add(moduleData.Id.FullName); dependencies.Add(moduleData); } } // Now that the Compilation values have been emitted, emit the non-compilation references foreach (var current in (new[] { compilation }).Concat(referencedCompilations)) { EmitReferences(current, fullNameSet, dependencies, diagnostics); } return EmitCompilationCore(compilation, manifestResources, diagnostics, testData, emitOptions); } internal static EmitOutput? EmitCompilationCore( Compilation compilation, IEnumerable<ResourceDescription> manifestResources, DiagnosticBag diagnostics, CompilationTestData testData, EmitOptions emitOptions) { emitOptions ??= EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded); using var executableStream = new MemoryStream(); var pdb = default(ImmutableArray<byte>); var assembly = default(ImmutableArray<byte>); var pdbStream = (emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded) ? new MemoryStream() : null; var embeddedTexts = compilation.SyntaxTrees .Select(t => (filePath: t.FilePath, text: t.GetText())) .Where(t => t.text.CanBeEmbedded && !string.IsNullOrEmpty(t.filePath)) .Select(t => EmbeddedText.FromSource(t.filePath, t.text)) .ToImmutableArray(); EmitResult result; try { result = compilation.Emit( executableStream, metadataPEStream: null, pdbStream: pdbStream, xmlDocumentationStream: null, win32Resources: null, manifestResources: manifestResources, options: emitOptions, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts, rebuildData: null, testData: testData, cancellationToken: default); } finally { if (pdbStream != null) { pdb = pdbStream.ToImmutable(); pdbStream.Dispose(); } } diagnostics.AddRange(result.Diagnostics); assembly = executableStream.ToImmutable(); if (result.Success) { return new EmitOutput(assembly, pdb); } return null; } public static string DumpAssemblyData(IEnumerable<ModuleData> modules, out string dumpDirectory) { dumpDirectory = null; var sb = new StringBuilder(); foreach (var module in modules) { // Limit the number of dumps to 10. After 10 we're likely in a bad state and are // dumping lots of unnecessary data. if (s_dumpCount > 10) { break; } if (module.InMemoryModule) { Interlocked.Increment(ref s_dumpCount); if (dumpDirectory == null) { dumpDirectory = TempRoot.Root; try { Directory.CreateDirectory(dumpDirectory); } catch { // Okay if directory already exists } } string fileName; if (module.Kind == OutputKind.NetModule) { fileName = module.FullName; } else { AssemblyIdentity.TryParseDisplayName(module.FullName, out var identity); fileName = identity.Name; } string pePath = Path.Combine(dumpDirectory, fileName + module.Kind.GetDefaultExtension()); try { module.Image.WriteToFile(pePath); } catch (ArgumentException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } catch (IOException e) { pePath = $"<unable to write file: '{pePath}' -- {e.Message}>"; } string pdbPath; if (!module.Pdb.IsDefaultOrEmpty) { pdbPath = Path.Combine(dumpDirectory, fileName + ".pdb"); try { module.Pdb.WriteToFile(pdbPath); } catch (ArgumentException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } catch (IOException e) { pdbPath = $"<unable to write file: '{pdbPath}' -- {e.Message}>"; } } else { pdbPath = null; } sb.Append("PE(" + module.Kind + "): "); sb.AppendLine(pePath); if (pdbPath != null) { sb.Append("PDB: "); sb.AppendLine(pdbPath); } } } return sb.ToString(); } } public interface IRuntimeEnvironmentFactory { IRuntimeEnvironment Create(IEnumerable<ModuleData> additionalDependencies); } public interface IRuntimeEnvironment : IDisposable { void Emit(Compilation mainCompilation, IEnumerable<ResourceDescription> manifestResources, EmitOptions emitOptions, bool usePdbForDebugging = false); int Execute(string moduleName, string[] args, string expectedOutput); ImmutableArray<byte> GetMainImage(); ImmutableArray<byte> GetMainPdb(); ImmutableArray<Diagnostic> GetDiagnostics(); SortedSet<string> GetMemberSignaturesFromMetadata(string fullyQualifiedTypeName, string memberName); IList<ModuleData> GetAllModuleData(); void Verify(Verification verification); string[] VerifyModules(string[] modulesToVerify); void CaptureOutput(Action action, int expectedLength, out string output, out string errorOutput); } internal interface IInternalRuntimeEnvironment { CompilationTestData GetCompilationTestData(); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Core/Implementation/RenameTracking/IRenameTrackingLanguageHeuristicsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal interface IRenameTrackingLanguageHeuristicsService : ILanguageService { bool IsIdentifierValidForRenameTracking(string name); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal interface IRenameTrackingLanguageHeuristicsService : ILanguageService { bool IsIdentifierValidForRenameTracking(string name); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Expressions/MyBaseKeywordRecommender.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions ''' <summary> ''' Recommends the "MyBase" keyword. ''' </summary> Friend Class MyBaseKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword(SyntaxFacts.GetText(SyntaxKind.MyBaseKeyword), VBFeaturesResources.Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken If (context.IsAnyExpressionContext OrElse context.IsSingleLineStatementContext OrElse context.IsNameOfContext) AndAlso targetToken.GetInnermostDeclarationContext().IsKind(SyntaxKind.ClassBlock) Then Return s_keywords End If If context.IsAccessibleEventContext(startAtEnclosingBaseType:=True, cancellationToken:=cancellationToken) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions ''' <summary> ''' Recommends the "MyBase" keyword. ''' </summary> Friend Class MyBaseKeywordRecommender Inherits AbstractKeywordRecommender Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) = ImmutableArray.Create(New RecommendedKeyword(SyntaxFacts.GetText(SyntaxKind.MyBaseKeyword), VBFeaturesResources.Provides_a_way_to_refer_to_the_base_class_of_the_current_class_instance_You_cannot_use_MyBase_to_call_MustOverride_base_methods)) Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken If (context.IsAnyExpressionContext OrElse context.IsSingleLineStatementContext OrElse context.IsNameOfContext) AndAlso targetToken.GetInnermostDeclarationContext().IsKind(SyntaxKind.ClassBlock) Then Return s_keywords End If If context.IsAccessibleEventContext(startAtEnclosingBaseType:=True, cancellationToken:=cancellationToken) Then Return s_keywords End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/Core/Portable/Workspace/Host/Metadata/AnalyzerAssemblyLoaderOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Host { internal readonly struct AnalyzerAssemblyLoaderOptions { public bool ShadowCopy { get; } public AnalyzerAssemblyLoaderOptions(bool shadowCopy) { ShadowCopy = shadowCopy; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Host { internal readonly struct AnalyzerAssemblyLoaderOptions { public bool ShadowCopy { get; } public AnalyzerAssemblyLoaderOptions(bool shadowCopy) { ShadowCopy = shadowCopy; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Core/Portable/SymbolDisplay/ObjectDisplayOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how generics are displayed in the description of a symbol. /// </summary> [Flags] internal enum ObjectDisplayOptions { /// <summary> /// Format object using default options. /// </summary> None = 0, /// <summary> /// In C#, include the numeric code point before character literals. /// </summary> IncludeCodePoints = 1 << 0, /// <summary> /// Whether or not to include type suffix for applicable integral literals. /// </summary> IncludeTypeSuffix = 1 << 1, /// <summary> /// Whether or not to display integral literals in hexadecimal. /// </summary> UseHexadecimalNumbers = 1 << 2, /// <summary> /// Whether or not to quote character and string literals. /// </summary> UseQuotes = 1 << 3, /// <summary> /// In C#, replace non-printable (e.g. control) characters with dedicated (e.g. \t) or unicode (\u0001) escape sequences. /// In Visual Basic, replace non-printable characters with calls to ChrW and vb* constants. /// </summary> EscapeNonPrintableCharacters = 1 << 4, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies the options for how generics are displayed in the description of a symbol. /// </summary> [Flags] internal enum ObjectDisplayOptions { /// <summary> /// Format object using default options. /// </summary> None = 0, /// <summary> /// In C#, include the numeric code point before character literals. /// </summary> IncludeCodePoints = 1 << 0, /// <summary> /// Whether or not to include type suffix for applicable integral literals. /// </summary> IncludeTypeSuffix = 1 << 1, /// <summary> /// Whether or not to display integral literals in hexadecimal. /// </summary> UseHexadecimalNumbers = 1 << 2, /// <summary> /// Whether or not to quote character and string literals. /// </summary> UseQuotes = 1 << 3, /// <summary> /// In C#, replace non-printable (e.g. control) characters with dedicated (e.g. \t) or unicode (\u0001) escape sequences. /// In Visual Basic, replace non-printable characters with calls to ChrW and vb* constants. /// </summary> EscapeNonPrintableCharacters = 1 << 4, } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/VisualBasic/Portable/CodeCleanup/Providers/FixIncorrectTokensCodeCleanupProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers <ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.FixIncorrectTokens, LanguageNames.VisualBasic), [Shared]> <ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.AddMissingTokens, Before:=PredefinedCodeCleanupProviderNames.Format)> Friend Class FixIncorrectTokensCodeCleanupProvider Inherits AbstractTokensCodeCleanupProvider Private Const s_ASCII_LSMART_Q As Char = ChrW(&H91S) '// ASCII left single smart quote Private Const s_ASCII_RSMART_Q As Char = ChrW(&H92S) '// ASCII right single smart quote Private Const s_UNICODE_LSMART_Q As Char = ChrW(&H2018S) '// UNICODE left single smart quote Private Const s_UNICODE_RSMART_Q As Char = ChrW(&H2019S) '// UNICODE right single smart quote Private Const s_CH_STRGHT_Q As Char = ChrW(&H27S) '// UNICODE straight quote Private Shared ReadOnly s_smartSingleQuotes As Char() = New Char() {s_ASCII_LSMART_Q, s_ASCII_RSMART_Q, s_UNICODE_LSMART_Q, s_UNICODE_RSMART_Q} <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")> Public Sub New() End Sub Public Overrides ReadOnly Property Name As String Get Return PredefinedCodeCleanupProviderNames.FixIncorrectTokens End Get End Property Protected Overrides Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter) Return FixIncorrectTokensRewriter.CreateAsync(document, spans, cancellationToken) End Function Private Class FixIncorrectTokensRewriter Inherits AbstractTokensCodeCleanupProvider.Rewriter Private ReadOnly _semanticModel As SemanticModel Private Sub New(semanticModel As SemanticModel, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) MyBase.New(spans, cancellationToken) _semanticModel = semanticModel End Sub Public Shared Async Function CreateAsync(document As Document, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) As Task(Of Rewriter) Dim modifiedSpan = spans.Collapse() Dim semanticModel = If(document Is Nothing, Nothing, Await document.ReuseExistingSpeculativeModelAsync(modifiedSpan, cancellationToken).ConfigureAwait(False)) Return New FixIncorrectTokensRewriter(semanticModel, spans, cancellationToken) End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia Dim newTrivia = MyBase.VisitTrivia(trivia) ' convert fullwidth single quotes into halfwidth single quotes. If newTrivia.Kind = SyntaxKind.CommentTrivia Then Dim triviaText = newTrivia.ToString() If triviaText.Length > 0 AndAlso s_smartSingleQuotes.Contains(triviaText(0)) Then triviaText = s_CH_STRGHT_Q + triviaText.Substring(1) Return SyntaxFactory.CommentTrivia(triviaText) End If End If Return newTrivia End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode Dim newIdentifierName = DirectCast(MyBase.VisitIdentifierName(node), IdentifierNameSyntax) ' VB Language specification Section 7.3 for Primitive Types states: ' The primitive types are identified through keywords, which are aliases for predefined types in the System namespace. ' A primitive type is completely indistinguishable from the type it aliases: writing the reserved word Byte is exactly ' the same as writing System.Byte. ' ' Language specification defines the following primitive type mappings: ' ------------------------------------------------------------------- ' Keyword --> Predefined type in the System namespace ' ------------------------------------------------------------------- ' Byte --> Byte ' SByte --> SByte ' * UShort --> UInt16 ' * Short --> Int16 ' * UInteger --> UInt32 ' * Integer --> Int32 ' * ULong --> UInt64 ' * Long --> Int64 ' Single --> Single ' Double --> Double ' Decimal --> Decimal ' Boolean --> Boolean ' * Date --> DateTime ' Char --> Char ' String --> String ' ' * - Keyword string differs from the predefined type name ' ' Here we rewrite the above * marked Keyword identifier tokens to their corresponding predefined type names when following conditions are met: ' (a) It occurs as the RIGHT child of a qualified name "LEFT.RIGHT" ' (b) LEFT child of the qualified name binds to the "System" namespace symbol or an alias to it. If Not _underStructuredTrivia Then Dim parent = TryCast(node.Parent, QualifiedNameSyntax) If parent IsNot Nothing AndAlso _semanticModel IsNot Nothing Then Dim symbol = _semanticModel.GetSymbolInfo(parent.Left, _cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.IsNamespace AndAlso String.Equals(DirectCast(symbol, INamespaceSymbol).MetadataName, "System", StringComparison.Ordinal) Then Dim id = newIdentifierName.Identifier Dim newValueText As String Select Case id.ValueText.ToUpperInvariant() Case "USHORT" newValueText = "UInt16" Case "SHORT" newValueText = "Int16" Case "UINTEGER" newValueText = "UInt32" Case "INTEGER" newValueText = "Int32" Case "ULONG" newValueText = "UInt64" Case "LONG" newValueText = "Int64" Case "DATE" newValueText = "DateTime" Case Else Return newIdentifierName End Select Return newIdentifierName.ReplaceToken(id, CreateIdentifierToken(id, newValueText)) End If End If End If Return newIdentifierName End Function #Region "EndIf Rewriting" Public Overrides Function VisitEndBlockStatement(node As EndBlockStatementSyntax) As SyntaxNode Dim newStatement = DirectCast(MyBase.VisitEndBlockStatement(node), EndBlockStatementSyntax) Return If(newStatement.BlockKeyword.Kind = SyntaxKind.IfKeyword, RewriteEndIfStatementOrDirectiveSyntax(newStatement, newStatement.EndKeyword, newStatement.BlockKeyword), newStatement) End Function Public Overrides Function VisitEndIfDirectiveTrivia(node As EndIfDirectiveTriviaSyntax) As SyntaxNode Dim newDirective = DirectCast(MyBase.VisitEndIfDirectiveTrivia(node), EndIfDirectiveTriviaSyntax) Return RewriteEndIfStatementOrDirectiveSyntax(newDirective, newDirective.EndKeyword, newDirective.IfKeyword) End Function ''' <summary> ''' Rewrite "EndIf" to "End If" for an EndIfStatementSyntax/EndIfDirectiveSyntax node. ''' </summary> ''' <param name="curNode">Syntax node for the EndIfStatementSyntax or EndIfDirectiveSyntax to be rewritten.</param> ''' <param name="curEndKeyword">"End" keyword token for <paramref name="curNode"/>.</param> ''' <param name="curIfKeyword">"If" keyword token for <paramref name="curNode"/>.</param> ''' <returns>Rewritten EndIfStatementSyntax/EndIfDirectiveSyntax node.</returns> ''' <remarks> ''' This method checks for the following: ''' (a) Both the End keyword and If keyword, <paramref name="curEndKeyword"/> and <paramref name="curIfKeyword"/> respectively, are Missing tokens AND ''' (b) Descendant Trivia under the given <paramref name="curEndKeyword"/> token or <paramref name="curIfKeyword"/> token has an "EndIf" keyword token. ''' ''' If the above conditions are met, it does the following node rewrites: ''' (a) Replace the missing <paramref name="curEndKeyword"/> and <paramref name="curIfKeyword"/> tokens with new "End" and "If" keywords tokens respectively. ''' (b) Remove the first "EndIf" keyword token from the descendant trivia and adjust the leading and trailing trivia appropriately. ''' </remarks> Private Shared Function RewriteEndIfStatementOrDirectiveSyntax(curNode As SyntaxNode, curEndKeyword As SyntaxToken, curIfKeyword As SyntaxToken) As SyntaxNode ' (a) Are both the curEndKeyword and curIfKeyword Missing tokens? If curEndKeyword.IsMissing AndAlso curIfKeyword.IsMissing Then Dim endKeywordTrivia = curEndKeyword.GetAllTrivia() Dim ifKeywordTrivia = curIfKeyword.GetAllTrivia() If endKeywordTrivia.Any() OrElse ifKeywordTrivia.Any() Then Dim endIfKeywordFound As Boolean = False Dim leadingTriviaBuilder As Queue(Of SyntaxTrivia) = Nothing Dim trailingTriviaBuilder As Queue(Of SyntaxTrivia) = Nothing ' (b) Descendant Trivia under the given curEndKeyword token or curIfKeyword token has an "EndIf" keyword token? ProcessTrivia(endKeywordTrivia, endIfKeywordFound, leadingTriviaBuilder, trailingTriviaBuilder) ProcessTrivia(ifKeywordTrivia, endIfKeywordFound, leadingTriviaBuilder, trailingTriviaBuilder) If endIfKeywordFound Then ' Rewrites: ' (a) Replace the missing curEndKeyword and curIfKeyword tokens with new "End" and "If" keywords tokens respectively. ' (b) Remove the first "EndIf" keyword token from the descendant trivia and adjust the leading and trailing trivia appropriately. Dim newEndKeyword = SyntaxFactory.Token(SyntaxKind.EndKeyword).WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")) If leadingTriviaBuilder IsNot Nothing Then newEndKeyword = newEndKeyword.WithLeadingTrivia(leadingTriviaBuilder) End If Dim newIfKeyword = SyntaxFactory.Token(SyntaxKind.IfKeyword) If trailingTriviaBuilder IsNot Nothing Then newIfKeyword = newIfKeyword.WithTrailingTrivia(trailingTriviaBuilder) End If Return curNode.ReplaceTokens(SpecializedCollections.SingletonEnumerable(curEndKeyword).Concat(curIfKeyword), Function(o, m) If o = curEndKeyword Then Return newEndKeyword ElseIf o = curIfKeyword Then Return newIfKeyword Else Return o End If End Function) End If End If End If Return curNode End Function ' Process trivia looking for an "EndIf" keyword token. Private Shared Sub ProcessTrivia(triviaList As IEnumerable(Of SyntaxTrivia), ByRef endIfKeywordFound As Boolean, ByRef leadingTriviaBuilder As Queue(Of SyntaxTrivia), ByRef trailingTriviaBuilder As Queue(Of SyntaxTrivia)) For Each trivia In triviaList If Not endIfKeywordFound Then If trivia.HasStructure Then Dim structuredTrivia = DirectCast(trivia.GetStructure(), StructuredTriviaSyntax) If structuredTrivia.Kind = SyntaxKind.SkippedTokensTrivia Then Dim skippedTokens = DirectCast(structuredTrivia, SkippedTokensTriviaSyntax).Tokens If skippedTokens.Count = 1 AndAlso skippedTokens.First.Kind = SyntaxKind.EndIfKeyword Then endIfKeywordFound = True Continue For End If End If End If ' Append the trivia to leading trivia and continue processing remaining trivia for EndIf keyword. If leadingTriviaBuilder Is Nothing Then leadingTriviaBuilder = New Queue(Of SyntaxTrivia) End If leadingTriviaBuilder.Enqueue(trivia) Else ' EndIf keyword was already found in a prior trivia, so just append this trivia to trailing trivia. If trailingTriviaBuilder Is Nothing Then trailingTriviaBuilder = New Queue(Of SyntaxTrivia) ' This is the first trivia encountered after the EndIf keyword. ' If this trivia is neither a WhitespaceTrivia nor an EndOfLineTrivia, then we must insert an extra WhitespaceTrivia here. Select Case trivia.Kind Case SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia Exit Select Case Else trailingTriviaBuilder.Enqueue(SyntaxFactory.WhitespaceTrivia(" ")) End Select End If trailingTriviaBuilder.Enqueue(trivia) End If Next End Sub #End Region End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.CodeCleanup.Providers <ExportCodeCleanupProvider(PredefinedCodeCleanupProviderNames.FixIncorrectTokens, LanguageNames.VisualBasic), [Shared]> <ExtensionOrder(After:=PredefinedCodeCleanupProviderNames.AddMissingTokens, Before:=PredefinedCodeCleanupProviderNames.Format)> Friend Class FixIncorrectTokensCodeCleanupProvider Inherits AbstractTokensCodeCleanupProvider Private Const s_ASCII_LSMART_Q As Char = ChrW(&H91S) '// ASCII left single smart quote Private Const s_ASCII_RSMART_Q As Char = ChrW(&H92S) '// ASCII right single smart quote Private Const s_UNICODE_LSMART_Q As Char = ChrW(&H2018S) '// UNICODE left single smart quote Private Const s_UNICODE_RSMART_Q As Char = ChrW(&H2019S) '// UNICODE right single smart quote Private Const s_CH_STRGHT_Q As Char = ChrW(&H27S) '// UNICODE straight quote Private Shared ReadOnly s_smartSingleQuotes As Char() = New Char() {s_ASCII_LSMART_Q, s_ASCII_RSMART_Q, s_UNICODE_LSMART_Q, s_UNICODE_RSMART_Q} <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="https://github.com/dotnet/roslyn/issues/42820")> Public Sub New() End Sub Public Overrides ReadOnly Property Name As String Get Return PredefinedCodeCleanupProviderNames.FixIncorrectTokens End Get End Property Protected Overrides Function GetRewriterAsync(document As Document, root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, cancellationToken As CancellationToken) As Task(Of Rewriter) Return FixIncorrectTokensRewriter.CreateAsync(document, spans, cancellationToken) End Function Private Class FixIncorrectTokensRewriter Inherits AbstractTokensCodeCleanupProvider.Rewriter Private ReadOnly _semanticModel As SemanticModel Private Sub New(semanticModel As SemanticModel, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) MyBase.New(spans, cancellationToken) _semanticModel = semanticModel End Sub Public Shared Async Function CreateAsync(document As Document, spans As ImmutableArray(Of TextSpan), cancellationToken As CancellationToken) As Task(Of Rewriter) Dim modifiedSpan = spans.Collapse() Dim semanticModel = If(document Is Nothing, Nothing, Await document.ReuseExistingSpeculativeModelAsync(modifiedSpan, cancellationToken).ConfigureAwait(False)) Return New FixIncorrectTokensRewriter(semanticModel, spans, cancellationToken) End Function Public Overrides Function VisitTrivia(trivia As SyntaxTrivia) As SyntaxTrivia Dim newTrivia = MyBase.VisitTrivia(trivia) ' convert fullwidth single quotes into halfwidth single quotes. If newTrivia.Kind = SyntaxKind.CommentTrivia Then Dim triviaText = newTrivia.ToString() If triviaText.Length > 0 AndAlso s_smartSingleQuotes.Contains(triviaText(0)) Then triviaText = s_CH_STRGHT_Q + triviaText.Substring(1) Return SyntaxFactory.CommentTrivia(triviaText) End If End If Return newTrivia End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode Dim newIdentifierName = DirectCast(MyBase.VisitIdentifierName(node), IdentifierNameSyntax) ' VB Language specification Section 7.3 for Primitive Types states: ' The primitive types are identified through keywords, which are aliases for predefined types in the System namespace. ' A primitive type is completely indistinguishable from the type it aliases: writing the reserved word Byte is exactly ' the same as writing System.Byte. ' ' Language specification defines the following primitive type mappings: ' ------------------------------------------------------------------- ' Keyword --> Predefined type in the System namespace ' ------------------------------------------------------------------- ' Byte --> Byte ' SByte --> SByte ' * UShort --> UInt16 ' * Short --> Int16 ' * UInteger --> UInt32 ' * Integer --> Int32 ' * ULong --> UInt64 ' * Long --> Int64 ' Single --> Single ' Double --> Double ' Decimal --> Decimal ' Boolean --> Boolean ' * Date --> DateTime ' Char --> Char ' String --> String ' ' * - Keyword string differs from the predefined type name ' ' Here we rewrite the above * marked Keyword identifier tokens to their corresponding predefined type names when following conditions are met: ' (a) It occurs as the RIGHT child of a qualified name "LEFT.RIGHT" ' (b) LEFT child of the qualified name binds to the "System" namespace symbol or an alias to it. If Not _underStructuredTrivia Then Dim parent = TryCast(node.Parent, QualifiedNameSyntax) If parent IsNot Nothing AndAlso _semanticModel IsNot Nothing Then Dim symbol = _semanticModel.GetSymbolInfo(parent.Left, _cancellationToken).Symbol If symbol IsNot Nothing AndAlso symbol.IsNamespace AndAlso String.Equals(DirectCast(symbol, INamespaceSymbol).MetadataName, "System", StringComparison.Ordinal) Then Dim id = newIdentifierName.Identifier Dim newValueText As String Select Case id.ValueText.ToUpperInvariant() Case "USHORT" newValueText = "UInt16" Case "SHORT" newValueText = "Int16" Case "UINTEGER" newValueText = "UInt32" Case "INTEGER" newValueText = "Int32" Case "ULONG" newValueText = "UInt64" Case "LONG" newValueText = "Int64" Case "DATE" newValueText = "DateTime" Case Else Return newIdentifierName End Select Return newIdentifierName.ReplaceToken(id, CreateIdentifierToken(id, newValueText)) End If End If End If Return newIdentifierName End Function #Region "EndIf Rewriting" Public Overrides Function VisitEndBlockStatement(node As EndBlockStatementSyntax) As SyntaxNode Dim newStatement = DirectCast(MyBase.VisitEndBlockStatement(node), EndBlockStatementSyntax) Return If(newStatement.BlockKeyword.Kind = SyntaxKind.IfKeyword, RewriteEndIfStatementOrDirectiveSyntax(newStatement, newStatement.EndKeyword, newStatement.BlockKeyword), newStatement) End Function Public Overrides Function VisitEndIfDirectiveTrivia(node As EndIfDirectiveTriviaSyntax) As SyntaxNode Dim newDirective = DirectCast(MyBase.VisitEndIfDirectiveTrivia(node), EndIfDirectiveTriviaSyntax) Return RewriteEndIfStatementOrDirectiveSyntax(newDirective, newDirective.EndKeyword, newDirective.IfKeyword) End Function ''' <summary> ''' Rewrite "EndIf" to "End If" for an EndIfStatementSyntax/EndIfDirectiveSyntax node. ''' </summary> ''' <param name="curNode">Syntax node for the EndIfStatementSyntax or EndIfDirectiveSyntax to be rewritten.</param> ''' <param name="curEndKeyword">"End" keyword token for <paramref name="curNode"/>.</param> ''' <param name="curIfKeyword">"If" keyword token for <paramref name="curNode"/>.</param> ''' <returns>Rewritten EndIfStatementSyntax/EndIfDirectiveSyntax node.</returns> ''' <remarks> ''' This method checks for the following: ''' (a) Both the End keyword and If keyword, <paramref name="curEndKeyword"/> and <paramref name="curIfKeyword"/> respectively, are Missing tokens AND ''' (b) Descendant Trivia under the given <paramref name="curEndKeyword"/> token or <paramref name="curIfKeyword"/> token has an "EndIf" keyword token. ''' ''' If the above conditions are met, it does the following node rewrites: ''' (a) Replace the missing <paramref name="curEndKeyword"/> and <paramref name="curIfKeyword"/> tokens with new "End" and "If" keywords tokens respectively. ''' (b) Remove the first "EndIf" keyword token from the descendant trivia and adjust the leading and trailing trivia appropriately. ''' </remarks> Private Shared Function RewriteEndIfStatementOrDirectiveSyntax(curNode As SyntaxNode, curEndKeyword As SyntaxToken, curIfKeyword As SyntaxToken) As SyntaxNode ' (a) Are both the curEndKeyword and curIfKeyword Missing tokens? If curEndKeyword.IsMissing AndAlso curIfKeyword.IsMissing Then Dim endKeywordTrivia = curEndKeyword.GetAllTrivia() Dim ifKeywordTrivia = curIfKeyword.GetAllTrivia() If endKeywordTrivia.Any() OrElse ifKeywordTrivia.Any() Then Dim endIfKeywordFound As Boolean = False Dim leadingTriviaBuilder As Queue(Of SyntaxTrivia) = Nothing Dim trailingTriviaBuilder As Queue(Of SyntaxTrivia) = Nothing ' (b) Descendant Trivia under the given curEndKeyword token or curIfKeyword token has an "EndIf" keyword token? ProcessTrivia(endKeywordTrivia, endIfKeywordFound, leadingTriviaBuilder, trailingTriviaBuilder) ProcessTrivia(ifKeywordTrivia, endIfKeywordFound, leadingTriviaBuilder, trailingTriviaBuilder) If endIfKeywordFound Then ' Rewrites: ' (a) Replace the missing curEndKeyword and curIfKeyword tokens with new "End" and "If" keywords tokens respectively. ' (b) Remove the first "EndIf" keyword token from the descendant trivia and adjust the leading and trailing trivia appropriately. Dim newEndKeyword = SyntaxFactory.Token(SyntaxKind.EndKeyword).WithTrailingTrivia(SyntaxFactory.WhitespaceTrivia(" ")) If leadingTriviaBuilder IsNot Nothing Then newEndKeyword = newEndKeyword.WithLeadingTrivia(leadingTriviaBuilder) End If Dim newIfKeyword = SyntaxFactory.Token(SyntaxKind.IfKeyword) If trailingTriviaBuilder IsNot Nothing Then newIfKeyword = newIfKeyword.WithTrailingTrivia(trailingTriviaBuilder) End If Return curNode.ReplaceTokens(SpecializedCollections.SingletonEnumerable(curEndKeyword).Concat(curIfKeyword), Function(o, m) If o = curEndKeyword Then Return newEndKeyword ElseIf o = curIfKeyword Then Return newIfKeyword Else Return o End If End Function) End If End If End If Return curNode End Function ' Process trivia looking for an "EndIf" keyword token. Private Shared Sub ProcessTrivia(triviaList As IEnumerable(Of SyntaxTrivia), ByRef endIfKeywordFound As Boolean, ByRef leadingTriviaBuilder As Queue(Of SyntaxTrivia), ByRef trailingTriviaBuilder As Queue(Of SyntaxTrivia)) For Each trivia In triviaList If Not endIfKeywordFound Then If trivia.HasStructure Then Dim structuredTrivia = DirectCast(trivia.GetStructure(), StructuredTriviaSyntax) If structuredTrivia.Kind = SyntaxKind.SkippedTokensTrivia Then Dim skippedTokens = DirectCast(structuredTrivia, SkippedTokensTriviaSyntax).Tokens If skippedTokens.Count = 1 AndAlso skippedTokens.First.Kind = SyntaxKind.EndIfKeyword Then endIfKeywordFound = True Continue For End If End If End If ' Append the trivia to leading trivia and continue processing remaining trivia for EndIf keyword. If leadingTriviaBuilder Is Nothing Then leadingTriviaBuilder = New Queue(Of SyntaxTrivia) End If leadingTriviaBuilder.Enqueue(trivia) Else ' EndIf keyword was already found in a prior trivia, so just append this trivia to trailing trivia. If trailingTriviaBuilder Is Nothing Then trailingTriviaBuilder = New Queue(Of SyntaxTrivia) ' This is the first trivia encountered after the EndIf keyword. ' If this trivia is neither a WhitespaceTrivia nor an EndOfLineTrivia, then we must insert an extra WhitespaceTrivia here. Select Case trivia.Kind Case SyntaxKind.WhitespaceTrivia, SyntaxKind.EndOfLineTrivia Exit Select Case Else trailingTriviaBuilder.Enqueue(SyntaxFactory.WhitespaceTrivia(" ")) End Select End If trailingTriviaBuilder.Enqueue(trivia) End If Next End Sub #End Region End Class End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/EmbeddedLanguages/Common/EmbeddedSyntaxHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal static class EmbeddedSyntaxHelpers { public static TextSpan GetSpan<TSyntaxKind>(EmbeddedSyntaxToken<TSyntaxKind> token1, EmbeddedSyntaxToken<TSyntaxKind> token2) where TSyntaxKind : struct => GetSpan(token1.VirtualChars[0], token2.VirtualChars.Last()); public static TextSpan GetSpan(VirtualCharSequence virtualChars) => GetSpan(virtualChars[0], virtualChars.Last()); public static TextSpan GetSpan(VirtualChar firstChar, VirtualChar lastChar) => TextSpan.FromBounds(firstChar.Span.Start, lastChar.Span.End); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Common { internal static class EmbeddedSyntaxHelpers { public static TextSpan GetSpan<TSyntaxKind>(EmbeddedSyntaxToken<TSyntaxKind> token1, EmbeddedSyntaxToken<TSyntaxKind> token2) where TSyntaxKind : struct => GetSpan(token1.VirtualChars[0], token2.VirtualChars.Last()); public static TextSpan GetSpan(VirtualCharSequence virtualChars) => GetSpan(virtualChars[0], virtualChars.Last()); public static TextSpan GetSpan(VirtualChar firstChar, VirtualChar lastChar) => TextSpan.FromBounds(firstChar.Span.Start, lastChar.Span.End); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/CSharp/Portable/Symbols/Source/SourceParameterSymbolBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for all parameters that are emitted. /// </summary> internal abstract class SourceParameterSymbolBase : ParameterSymbol { private readonly Symbol _containingSymbol; private readonly ushort _ordinal; public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) { Debug.Assert((object)containingSymbol != null); _ordinal = (ushort)ordinal; _containingSymbol = containingSymbol; } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } if (obj is NativeIntegerParameterSymbol nps) { return nps.Equals(this, compareKind); } var symbol = obj as SourceParameterSymbolBase; return (object)symbol != null && symbol.Ordinal == this.Ordinal && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal); } public sealed override int Ordinal { get { return _ordinal; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } public sealed override AssemblySymbol ContainingAssembly { get { return _containingSymbol.ContainingAssembly; } } internal abstract ConstantValue DefaultValueFromAttributes { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; if (this.IsParams) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor)); } // Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already: var defaultValue = this.ExplicitDefaultConstantValue; if (defaultValue != ConstantValue.NotAvailable && defaultValue.SpecialType == SpecialType.System_Decimal && DefaultValueFromAttributes == ConstantValue.NotAvailable) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)); } var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } } internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Base class for all parameters that are emitted. /// </summary> internal abstract class SourceParameterSymbolBase : ParameterSymbol { private readonly Symbol _containingSymbol; private readonly ushort _ordinal; public SourceParameterSymbolBase(Symbol containingSymbol, int ordinal) { Debug.Assert((object)containingSymbol != null); _ordinal = (ushort)ordinal; _containingSymbol = containingSymbol; } public sealed override bool Equals(Symbol obj, TypeCompareKind compareKind) { if (obj == (object)this) { return true; } if (obj is NativeIntegerParameterSymbol nps) { return nps.Equals(this, compareKind); } var symbol = obj as SourceParameterSymbolBase; return (object)symbol != null && symbol.Ordinal == this.Ordinal && symbol._containingSymbol.Equals(_containingSymbol, compareKind); } public sealed override int GetHashCode() { return Hash.Combine(_containingSymbol.GetHashCode(), this.Ordinal); } public sealed override int Ordinal { get { return _ordinal; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } public sealed override AssemblySymbol ContainingAssembly { get { return _containingSymbol.ContainingAssembly; } } internal abstract ConstantValue DefaultValueFromAttributes { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = this.DeclaringCompilation; if (this.IsParams) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ParamArrayAttribute__ctor)); } // Synthesize DecimalConstantAttribute if we don't have an explicit custom attribute already: var defaultValue = this.ExplicitDefaultConstantValue; if (defaultValue != ConstantValue.NotAvailable && defaultValue.SpecialType == SpecialType.System_Decimal && DefaultValueFromAttributes == ConstantValue.NotAvailable) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDecimalConstantAttribute(defaultValue.DecimalValue)); } var type = this.TypeWithAnnotations; if (type.Type.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type.Type, type.CustomModifiers.Length + this.RefCustomModifiers.Length, this.RefKind)); } if (type.Type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type.Type)); } if (type.Type.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(type.Type)); } if (this.RefKind == RefKind.RefReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, GetNullableContextValue(), type)); } } internal abstract ParameterSymbol WithCustomModifiersAndParams(TypeSymbol newType, ImmutableArray<CustomModifier> newCustomModifiers, ImmutableArray<CustomModifier> newRefCustomModifiers, bool newIsParams); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/ChangeSignature/ReorderParametersTests.Cascading.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToImplementedMethod() { var markup = @" interface I { void M(int x, string y); } class C : I { $$public void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C : I { public void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToImplementedMethod_WithTuples() { var markup = @" interface I { void M((int, int) x, (string a, string b) y); } class C : I { $$public void M((int, int) x, (string a, string b) y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M((string a, string b) y, (int, int) x); } class C : I { public void M((string a, string b) y, (int, int) x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToImplementingMethod() { var markup = @" interface I { $$void M(int x, string y); } class C : I { public void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C : I { public void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverriddenMethod() { var markup = @" class B { public virtual void M(int x, string y) { } } class D : B { $$public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverridingMethod() { var markup = @" class B { $$public virtual void M(int x, string y) { } } class D : B { public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverriddenMethod_Transitive() { var markup = @" class B { public virtual void M(int x, string y) { } } class D : B { public override void M(int x, string y) { } } class D2 : D { $$public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverridingMethod_Transitive() { var markup = @" class B { $$public virtual void M(int x, string y) { } } class D : B { public override void M(int x, string y) { } } class D2 : D { public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToMethods_Complex() { //// B I I2 //// \ / \ / //// D (I3) //// / \ \ //// $$D2 D3 C var markup = @" class B { public virtual void M(int x, string y) { } } class D : B, I { public override void M(int x, string y) { } } class D2 : D { public override void $$M(int x, string y) { } } class D3 : D { public override void M(int x, string y) { } } interface I { void M(int x, string y); } interface I2 { void M(int x, string y); } interface I3 : I, I2 { } class C : I3 { public void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B, I { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } } class D3 : D { public override void M(string y, int x) { } } interface I { void M(string y, int x); } interface I2 { void M(string y, int x); } interface I3 : I, I2 { } class C : I3 { public void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToMethods_WithDifferentParameterNames() { var markup = @" public class B { /// <param name=""x""></param> /// <param name=""y""></param> public virtual int M(int x, string y) { return 1; } } public class D : B { /// <param name=""a""></param> /// <param name=""b""></param> public override int M(int a, string b) { return 1; } } public class D2 : D { /// <param name=""y""></param> /// <param name=""x""></param> public override int $$M(int y, string x) { M(1, ""Two""); ((D)this).M(1, ""Two""); ((B)this).M(1, ""Two""); M(1, x: ""Two""); ((D)this).M(1, b: ""Two""); ((B)this).M(1, y: ""Two""); return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class B { /// <param name=""y""></param> /// <param name=""x""></param> public virtual int M(string y, int x) { return 1; } } public class D : B { /// <param name=""b""></param> /// <param name=""a""></param> public override int M(string b, int a) { return 1; } } public class D2 : D { /// <param name=""x""></param> /// <param name=""y""></param> public override int M(string x, int y) { M(""Two"", 1); ((D)this).M(""Two"", 1); ((B)this).M(""Two"", 1); M(x: ""Two"", y: 1); ((D)this).M(b: ""Two"", a: 1); ((B)this).M(y: ""Two"", x: 1); return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToImplementedMethod() { var markup = @" interface I { void M(int x, string y); } class C : I { $$public void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C : I { public void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToImplementedMethod_WithTuples() { var markup = @" interface I { void M((int, int) x, (string a, string b) y); } class C : I { $$public void M((int, int) x, (string a, string b) y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M((string a, string b) y, (int, int) x); } class C : I { public void M((string a, string b) y, (int, int) x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToImplementingMethod() { var markup = @" interface I { $$void M(int x, string y); } class C : I { public void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" interface I { void M(string y, int x); } class C : I { public void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverriddenMethod() { var markup = @" class B { public virtual void M(int x, string y) { } } class D : B { $$public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverridingMethod() { var markup = @" class B { $$public virtual void M(int x, string y) { } } class D : B { public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverriddenMethod_Transitive() { var markup = @" class B { public virtual void M(int x, string y) { } } class D : B { public override void M(int x, string y) { } } class D2 : D { $$public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToOverridingMethod_Transitive() { var markup = @" class B { $$public virtual void M(int x, string y) { } } class D : B { public override void M(int x, string y) { } } class D2 : D { public override void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToMethods_Complex() { //// B I I2 //// \ / \ / //// D (I3) //// / \ \ //// $$D2 D3 C var markup = @" class B { public virtual void M(int x, string y) { } } class D : B, I { public override void M(int x, string y) { } } class D2 : D { public override void $$M(int x, string y) { } } class D3 : D { public override void M(int x, string y) { } } interface I { void M(int x, string y); } interface I2 { void M(int x, string y); } interface I3 : I, I2 { } class C : I3 { public void M(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public virtual void M(string y, int x) { } } class D : B, I { public override void M(string y, int x) { } } class D2 : D { public override void M(string y, int x) { } } class D3 : D { public override void M(string y, int x) { } } interface I { void M(string y, int x); } interface I2 { void M(string y, int x); } interface I3 : I, I2 { } class C : I3 { public void M(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderParameters_Cascade_ToMethods_WithDifferentParameterNames() { var markup = @" public class B { /// <param name=""x""></param> /// <param name=""y""></param> public virtual int M(int x, string y) { return 1; } } public class D : B { /// <param name=""a""></param> /// <param name=""b""></param> public override int M(int a, string b) { return 1; } } public class D2 : D { /// <param name=""y""></param> /// <param name=""x""></param> public override int $$M(int y, string x) { M(1, ""Two""); ((D)this).M(1, ""Two""); ((B)this).M(1, ""Two""); M(1, x: ""Two""); ((D)this).M(1, b: ""Two""); ((B)this).M(1, y: ""Two""); return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class B { /// <param name=""y""></param> /// <param name=""x""></param> public virtual int M(string y, int x) { return 1; } } public class D : B { /// <param name=""b""></param> /// <param name=""a""></param> public override int M(string b, int a) { return 1; } } public class D2 : D { /// <param name=""x""></param> /// <param name=""y""></param> public override int M(string x, int y) { M(""Two"", 1); ((D)this).M(""Two"", 1); ((B)this).M(""Two"", 1); M(x: ""Two"", y: 1); ((D)this).M(b: ""Two"", a: 1); ((B)this).M(y: ""Two"", x: 1); return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicDeclarationComparer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Class VisualBasicDeclarationComparer Implements IComparer(Of SyntaxNode) Private Shared ReadOnly s_kindPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From { {SyntaxKind.FieldDeclaration, 0}, {SyntaxKind.ConstructorBlock, 1}, {SyntaxKind.SubNewStatement, 1}, {SyntaxKind.PropertyBlock, 2}, {SyntaxKind.PropertyStatement, 2}, {SyntaxKind.EventBlock, 3}, {SyntaxKind.EventStatement, 3}, {SyntaxKind.SubBlock, 4}, {SyntaxKind.SubStatement, 4}, {SyntaxKind.FunctionBlock, 5}, {SyntaxKind.FunctionStatement, 5}, {SyntaxKind.OperatorBlock, 6}, {SyntaxKind.OperatorStatement, 6}, {SyntaxKind.EnumBlock, 7}, {SyntaxKind.InterfaceBlock, 8}, {SyntaxKind.StructureBlock, 9}, {SyntaxKind.ClassBlock, 10}, {SyntaxKind.ModuleBlock, 11}, {SyntaxKind.DelegateSubStatement, 12}, {SyntaxKind.DelegateFunctionStatement, 12} } Private Shared ReadOnly s_operatorPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From { {SyntaxKind.PlusToken, 0}, {SyntaxKind.MinusToken, 1}, {SyntaxKind.AsteriskToken, 3}, {SyntaxKind.SlashToken, 4}, {SyntaxKind.BackslashToken, 5}, {SyntaxKind.CaretToken, 6}, {SyntaxKind.AmpersandToken, 7}, {SyntaxKind.NotKeyword, 8}, {SyntaxKind.LikeKeyword, 9}, {SyntaxKind.ModKeyword, 10}, {SyntaxKind.AndKeyword, 11}, {SyntaxKind.OrKeyword, 12}, {SyntaxKind.XorKeyword, 13}, {SyntaxKind.LessThanLessThanToken, 14}, {SyntaxKind.GreaterThanGreaterThanToken, 15}, {SyntaxKind.EqualsToken, 16}, {SyntaxKind.LessThanGreaterThanToken, 17}, {SyntaxKind.GreaterThanToken, 18}, {SyntaxKind.LessThanToken, 19}, {SyntaxKind.GreaterThanEqualsToken, 20}, {SyntaxKind.LessThanEqualsToken, 21}, {SyntaxKind.IsTrueKeyword, 22}, {SyntaxKind.IsFalseKeyword, 23}, {SyntaxKind.CTypeKeyword, 24} } Public Shared ReadOnly WithNamesInstance As New VisualBasicDeclarationComparer(includeName:=True) Public Shared ReadOnly WithoutNamesInstance As New VisualBasicDeclarationComparer(includeName:=False) Private ReadOnly _includeName As Boolean Private Sub New(includeName As Boolean) _includeName = includeName End Sub Public Function Compare(x As SyntaxNode, y As SyntaxNode) As Integer Implements IComparer(Of SyntaxNode).Compare Dim xPrecedence As Integer Dim yPrecedence As Integer If Not s_kindPrecedenceMap.TryGetValue(x.Kind(), xPrecedence) OrElse Not s_kindPrecedenceMap.TryGetValue(y.Kind(), yPrecedence) Then ' The containing definition is malformed and contains a node kind we didn't expect. ' Ignore comparisons with those unexpected nodes and sort them to the end of the declaration. Return 1 End If If xPrecedence <> yPrecedence Then Return If(xPrecedence < yPrecedence, -1, 1) End If x = ConvertBlockToStatement(x) y = ConvertBlockToStatement(y) Select Case x.Kind Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return Compare(DirectCast(x, DelegateStatementSyntax), DirectCast(y, DelegateStatementSyntax)) Case SyntaxKind.FieldDeclaration Return Compare(DirectCast(x, FieldDeclarationSyntax), DirectCast(y, FieldDeclarationSyntax)) Case SyntaxKind.SubNewStatement Return Compare(DirectCast(x, SubNewStatementSyntax), DirectCast(y, SubNewStatementSyntax)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return Compare(DirectCast(x, MethodStatementSyntax), DirectCast(y, MethodStatementSyntax)) Case SyntaxKind.EventStatement Return Compare(DirectCast(x, EventStatementSyntax), DirectCast(y, EventStatementSyntax)) Case SyntaxKind.PropertyStatement Return Compare(DirectCast(x, PropertyStatementSyntax), DirectCast(y, PropertyStatementSyntax)) Case SyntaxKind.OperatorStatement Return Compare(DirectCast(x, OperatorStatementSyntax), DirectCast(y, OperatorStatementSyntax)) Case SyntaxKind.EnumStatement Return Compare(DirectCast(x, EnumStatementSyntax), DirectCast(y, EnumStatementSyntax)) Case SyntaxKind.InterfaceStatement, SyntaxKind.StructureStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return Compare(DirectCast(x, TypeStatementSyntax), DirectCast(y, TypeStatementSyntax)) End Select throw ExceptionUtilities.UnexpectedValue(x.Kind) End Function Private Shared Function ConvertBlockToStatement(node As SyntaxNode) As SyntaxNode Select Case node.Kind Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).PropertyStatement Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).EventStatement Case SyntaxKind.ConstructorBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).BlockStatement Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).BlockStatement Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).BlockStatement Case SyntaxKind.ModuleBlock Return DirectCast(node, ModuleBlockSyntax).BlockStatement End Select Return node End Function Private Function Compare(x As DelegateStatementSyntax, y As DelegateStatementSyntax) As Integer Dim result = 0 If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As FieldDeclarationSyntax, y As FieldDeclarationSyntax) As Integer Dim result = 0 If EqualConstness(x.Modifiers, y.Modifiers, result) AndAlso EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualReadOnlyNess(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName( x.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier, y.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier, result) End If End If Return result End Function Private Shared Function Compare(x As SubNewStatementSyntax, y As SubNewStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then EqualParameterLists(x.ParameterList, y.ParameterList, result) End If Return result End Function Private Function Compare(x As MethodStatementSyntax, y As MethodStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As EventStatementSyntax, y As EventStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As PropertyStatementSyntax, y As PropertyStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Shared Function Compare(x As OperatorStatementSyntax, y As OperatorStatementSyntax) As Integer Dim result = 0 If EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, result) Then EqualParameterLists(x.ParameterList, y.ParameterList, result) End If Return result End Function Private Function Compare(x As EnumStatementSyntax, y As EnumStatementSyntax) As Integer Dim result = 0 If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As TypeStatementSyntax, y As TypeStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Shared Function NeitherNull(x As Object, y As Object, ByRef comparisonResult As Integer) As Boolean If x Is Nothing AndAlso y Is Nothing Then comparisonResult = 0 Return False ElseIf x Is Nothing Then comparisonResult = -1 Return False ElseIf y Is Nothing Then comparisonResult = 1 Return False Else comparisonResult = 0 Return True End If End Function Private Shared Function ContainsToken(list As IEnumerable(Of SyntaxToken), kind As SyntaxKind) As Boolean Return list.Contains(Function(token As SyntaxToken) Return token.Kind = kind End Function) End Function Private Enum Accessibility [Public] [Protected] [ProtectedFriend] [Friend] [Private] End Enum Private Shared Function GetAccessibilityPrecedence(declaration As SyntaxNode, modifiers As IEnumerable(Of SyntaxToken)) As Integer If ContainsToken(modifiers, SyntaxKind.PublicKeyword) Then Return Accessibility.Public ElseIf ContainsToken(modifiers, SyntaxKind.ProtectedKeyword) Then If ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then Return Accessibility.ProtectedFriend End If Return Accessibility.Protected ElseIf ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then Return Accessibility.Friend ElseIf ContainsToken(modifiers, SyntaxKind.PrivateKeyword) Then Return Accessibility.Private End If ' Determine default accessibility Select Case declaration.Kind Case SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement, SyntaxKind.ClassStatement, SyntaxKind.StructureStatement ' Convert type definition statements to their corresponding blocks so we can traverse up the tree declaration = declaration.Parent End Select Dim node = declaration.Parent While node IsNot Nothing Select Case node.Kind Case SyntaxKind.InterfaceBlock ' Interface members are all Public Return Accessibility.Public Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock ' Standard module and class members default to Public unless they are variable declarations Return If(declaration.Kind = SyntaxKind.FieldDeclaration, Accessibility.Private, Accessibility.Public) Case SyntaxKind.StructureBlock ' Structure member declarations always default to Public Return Accessibility.Public End Select node = node.Parent End While ' Namespace members default to Friend Return Accessibility.Friend End Function Private Shared Function BothHaveModifier(x As SyntaxTokenList, y As SyntaxTokenList, modifierKind As SyntaxKind, ByRef comparisonResult As Integer) As Boolean Dim xHasModifier = ContainsToken(x, modifierKind) Dim yHasModifier = ContainsToken(y, modifierKind) If xHasModifier = yHasModifier Then comparisonResult = 0 Return True End If comparisonResult = If(xHasModifier, -1, 1) Return False End Function Private Shared Function EqualSharedness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Return BothHaveModifier(x, y, SyntaxKind.SharedKeyword, comparisonResult) End Function Private Shared Function EqualReadOnlyness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Return BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, comparisonResult) End Function Private Shared Function EqualConstness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Return BothHaveModifier(x, y, SyntaxKind.ConstKeyword, comparisonResult) End Function Private Shared Function EqualAccessibility(x As SyntaxNode, xModifiers As SyntaxTokenList, y As SyntaxNode, yModifiers As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Dim xAccessibility = GetAccessibilityPrecedence(x, xModifiers) Dim yAccessibility = GetAccessibilityPrecedence(y, yModifiers) If xAccessibility = yAccessibility Then comparisonResult = 0 Return True End If comparisonResult = If(xAccessibility < yAccessibility, -1, 1) Return False End Function Private Shared Function EqualIdentifierName(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean If NeitherNull(x, y, comparisonResult) Then comparisonResult = CaseInsensitiveComparison.Compare(x.ValueText, y.ValueText) End If Return comparisonResult = 0 End Function Private Shared Function EqualOperatorPrecedence(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean If NeitherNull(x, y, comparisonResult) Then Dim xPrecedence = 0 Dim yPrecedence = 0 s_operatorPrecedenceMap.TryGetValue(x.Kind, xPrecedence) s_operatorPrecedenceMap.TryGetValue(y.Kind, yPrecedence) comparisonResult = If(xPrecedence = yPrecedence, 0, If(xPrecedence < yPrecedence, -1, 1)) End If Return comparisonResult = 0 End Function Private Shared Function EqualParameterLists(x As ParameterListSyntax, y As ParameterListSyntax, ByRef comparisonResult As Integer) As Boolean Dim result = 0 If NeitherNull(x, y, result) Then Dim xParameterCount = x.Parameters.Count Dim yParameterCount = y.Parameters.Count comparisonResult = If(xParameterCount = yParameterCount, 0, If(x.Parameters.Count < y.Parameters.Count, -1, 1)) End If Return comparisonResult = 0 End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Class VisualBasicDeclarationComparer Implements IComparer(Of SyntaxNode) Private Shared ReadOnly s_kindPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From { {SyntaxKind.FieldDeclaration, 0}, {SyntaxKind.ConstructorBlock, 1}, {SyntaxKind.SubNewStatement, 1}, {SyntaxKind.PropertyBlock, 2}, {SyntaxKind.PropertyStatement, 2}, {SyntaxKind.EventBlock, 3}, {SyntaxKind.EventStatement, 3}, {SyntaxKind.SubBlock, 4}, {SyntaxKind.SubStatement, 4}, {SyntaxKind.FunctionBlock, 5}, {SyntaxKind.FunctionStatement, 5}, {SyntaxKind.OperatorBlock, 6}, {SyntaxKind.OperatorStatement, 6}, {SyntaxKind.EnumBlock, 7}, {SyntaxKind.InterfaceBlock, 8}, {SyntaxKind.StructureBlock, 9}, {SyntaxKind.ClassBlock, 10}, {SyntaxKind.ModuleBlock, 11}, {SyntaxKind.DelegateSubStatement, 12}, {SyntaxKind.DelegateFunctionStatement, 12} } Private Shared ReadOnly s_operatorPrecedenceMap As Dictionary(Of SyntaxKind, Integer) = New Dictionary(Of SyntaxKind, Integer)(SyntaxFacts.EqualityComparer) From { {SyntaxKind.PlusToken, 0}, {SyntaxKind.MinusToken, 1}, {SyntaxKind.AsteriskToken, 3}, {SyntaxKind.SlashToken, 4}, {SyntaxKind.BackslashToken, 5}, {SyntaxKind.CaretToken, 6}, {SyntaxKind.AmpersandToken, 7}, {SyntaxKind.NotKeyword, 8}, {SyntaxKind.LikeKeyword, 9}, {SyntaxKind.ModKeyword, 10}, {SyntaxKind.AndKeyword, 11}, {SyntaxKind.OrKeyword, 12}, {SyntaxKind.XorKeyword, 13}, {SyntaxKind.LessThanLessThanToken, 14}, {SyntaxKind.GreaterThanGreaterThanToken, 15}, {SyntaxKind.EqualsToken, 16}, {SyntaxKind.LessThanGreaterThanToken, 17}, {SyntaxKind.GreaterThanToken, 18}, {SyntaxKind.LessThanToken, 19}, {SyntaxKind.GreaterThanEqualsToken, 20}, {SyntaxKind.LessThanEqualsToken, 21}, {SyntaxKind.IsTrueKeyword, 22}, {SyntaxKind.IsFalseKeyword, 23}, {SyntaxKind.CTypeKeyword, 24} } Public Shared ReadOnly WithNamesInstance As New VisualBasicDeclarationComparer(includeName:=True) Public Shared ReadOnly WithoutNamesInstance As New VisualBasicDeclarationComparer(includeName:=False) Private ReadOnly _includeName As Boolean Private Sub New(includeName As Boolean) _includeName = includeName End Sub Public Function Compare(x As SyntaxNode, y As SyntaxNode) As Integer Implements IComparer(Of SyntaxNode).Compare Dim xPrecedence As Integer Dim yPrecedence As Integer If Not s_kindPrecedenceMap.TryGetValue(x.Kind(), xPrecedence) OrElse Not s_kindPrecedenceMap.TryGetValue(y.Kind(), yPrecedence) Then ' The containing definition is malformed and contains a node kind we didn't expect. ' Ignore comparisons with those unexpected nodes and sort them to the end of the declaration. Return 1 End If If xPrecedence <> yPrecedence Then Return If(xPrecedence < yPrecedence, -1, 1) End If x = ConvertBlockToStatement(x) y = ConvertBlockToStatement(y) Select Case x.Kind Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement Return Compare(DirectCast(x, DelegateStatementSyntax), DirectCast(y, DelegateStatementSyntax)) Case SyntaxKind.FieldDeclaration Return Compare(DirectCast(x, FieldDeclarationSyntax), DirectCast(y, FieldDeclarationSyntax)) Case SyntaxKind.SubNewStatement Return Compare(DirectCast(x, SubNewStatementSyntax), DirectCast(y, SubNewStatementSyntax)) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement Return Compare(DirectCast(x, MethodStatementSyntax), DirectCast(y, MethodStatementSyntax)) Case SyntaxKind.EventStatement Return Compare(DirectCast(x, EventStatementSyntax), DirectCast(y, EventStatementSyntax)) Case SyntaxKind.PropertyStatement Return Compare(DirectCast(x, PropertyStatementSyntax), DirectCast(y, PropertyStatementSyntax)) Case SyntaxKind.OperatorStatement Return Compare(DirectCast(x, OperatorStatementSyntax), DirectCast(y, OperatorStatementSyntax)) Case SyntaxKind.EnumStatement Return Compare(DirectCast(x, EnumStatementSyntax), DirectCast(y, EnumStatementSyntax)) Case SyntaxKind.InterfaceStatement, SyntaxKind.StructureStatement, SyntaxKind.ClassStatement, SyntaxKind.ModuleStatement Return Compare(DirectCast(x, TypeStatementSyntax), DirectCast(y, TypeStatementSyntax)) End Select throw ExceptionUtilities.UnexpectedValue(x.Kind) End Function Private Shared Function ConvertBlockToStatement(node As SyntaxNode) As SyntaxNode Select Case node.Kind Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).PropertyStatement Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).EventStatement Case SyntaxKind.ConstructorBlock, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock Return DirectCast(node, MethodBlockBaseSyntax).BlockStatement Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement Case SyntaxKind.InterfaceBlock Return DirectCast(node, InterfaceBlockSyntax).BlockStatement Case SyntaxKind.StructureBlock Return DirectCast(node, StructureBlockSyntax).BlockStatement Case SyntaxKind.ClassBlock Return DirectCast(node, ClassBlockSyntax).BlockStatement Case SyntaxKind.ModuleBlock Return DirectCast(node, ModuleBlockSyntax).BlockStatement End Select Return node End Function Private Function Compare(x As DelegateStatementSyntax, y As DelegateStatementSyntax) As Integer Dim result = 0 If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As FieldDeclarationSyntax, y As FieldDeclarationSyntax) As Integer Dim result = 0 If EqualConstness(x.Modifiers, y.Modifiers, result) AndAlso EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualReadOnlyNess(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName( x.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier, y.Declarators.FirstOrDefault().Names.FirstOrDefault().Identifier, result) End If End If Return result End Function Private Shared Function Compare(x As SubNewStatementSyntax, y As SubNewStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then EqualParameterLists(x.ParameterList, y.ParameterList, result) End If Return result End Function Private Function Compare(x As MethodStatementSyntax, y As MethodStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As EventStatementSyntax, y As EventStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As PropertyStatementSyntax, y As PropertyStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Shared Function Compare(x As OperatorStatementSyntax, y As OperatorStatementSyntax) As Integer Dim result = 0 If EqualOperatorPrecedence(x.OperatorToken, y.OperatorToken, result) Then EqualParameterLists(x.ParameterList, y.ParameterList, result) End If Return result End Function Private Function Compare(x As EnumStatementSyntax, y As EnumStatementSyntax) As Integer Dim result = 0 If EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Function Compare(x As TypeStatementSyntax, y As TypeStatementSyntax) As Integer Dim result = 0 If EqualSharedness(x.Modifiers, y.Modifiers, result) AndAlso EqualAccessibility(x, x.Modifiers, y, y.Modifiers, result) Then If _includeName Then EqualIdentifierName(x.Identifier, y.Identifier, result) End If End If Return result End Function Private Shared Function NeitherNull(x As Object, y As Object, ByRef comparisonResult As Integer) As Boolean If x Is Nothing AndAlso y Is Nothing Then comparisonResult = 0 Return False ElseIf x Is Nothing Then comparisonResult = -1 Return False ElseIf y Is Nothing Then comparisonResult = 1 Return False Else comparisonResult = 0 Return True End If End Function Private Shared Function ContainsToken(list As IEnumerable(Of SyntaxToken), kind As SyntaxKind) As Boolean Return list.Contains(Function(token As SyntaxToken) Return token.Kind = kind End Function) End Function Private Enum Accessibility [Public] [Protected] [ProtectedFriend] [Friend] [Private] End Enum Private Shared Function GetAccessibilityPrecedence(declaration As SyntaxNode, modifiers As IEnumerable(Of SyntaxToken)) As Integer If ContainsToken(modifiers, SyntaxKind.PublicKeyword) Then Return Accessibility.Public ElseIf ContainsToken(modifiers, SyntaxKind.ProtectedKeyword) Then If ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then Return Accessibility.ProtectedFriend End If Return Accessibility.Protected ElseIf ContainsToken(modifiers, SyntaxKind.FriendKeyword) Then Return Accessibility.Friend ElseIf ContainsToken(modifiers, SyntaxKind.PrivateKeyword) Then Return Accessibility.Private End If ' Determine default accessibility Select Case declaration.Kind Case SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement, SyntaxKind.ClassStatement, SyntaxKind.StructureStatement ' Convert type definition statements to their corresponding blocks so we can traverse up the tree declaration = declaration.Parent End Select Dim node = declaration.Parent While node IsNot Nothing Select Case node.Kind Case SyntaxKind.InterfaceBlock ' Interface members are all Public Return Accessibility.Public Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock ' Standard module and class members default to Public unless they are variable declarations Return If(declaration.Kind = SyntaxKind.FieldDeclaration, Accessibility.Private, Accessibility.Public) Case SyntaxKind.StructureBlock ' Structure member declarations always default to Public Return Accessibility.Public End Select node = node.Parent End While ' Namespace members default to Friend Return Accessibility.Friend End Function Private Shared Function BothHaveModifier(x As SyntaxTokenList, y As SyntaxTokenList, modifierKind As SyntaxKind, ByRef comparisonResult As Integer) As Boolean Dim xHasModifier = ContainsToken(x, modifierKind) Dim yHasModifier = ContainsToken(y, modifierKind) If xHasModifier = yHasModifier Then comparisonResult = 0 Return True End If comparisonResult = If(xHasModifier, -1, 1) Return False End Function Private Shared Function EqualSharedness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Return BothHaveModifier(x, y, SyntaxKind.SharedKeyword, comparisonResult) End Function Private Shared Function EqualReadOnlyness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Return BothHaveModifier(x, y, SyntaxKind.ReadOnlyKeyword, comparisonResult) End Function Private Shared Function EqualConstness(x As SyntaxTokenList, y As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Return BothHaveModifier(x, y, SyntaxKind.ConstKeyword, comparisonResult) End Function Private Shared Function EqualAccessibility(x As SyntaxNode, xModifiers As SyntaxTokenList, y As SyntaxNode, yModifiers As SyntaxTokenList, ByRef comparisonResult As Integer) As Boolean Dim xAccessibility = GetAccessibilityPrecedence(x, xModifiers) Dim yAccessibility = GetAccessibilityPrecedence(y, yModifiers) If xAccessibility = yAccessibility Then comparisonResult = 0 Return True End If comparisonResult = If(xAccessibility < yAccessibility, -1, 1) Return False End Function Private Shared Function EqualIdentifierName(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean If NeitherNull(x, y, comparisonResult) Then comparisonResult = CaseInsensitiveComparison.Compare(x.ValueText, y.ValueText) End If Return comparisonResult = 0 End Function Private Shared Function EqualOperatorPrecedence(x As SyntaxToken, y As SyntaxToken, ByRef comparisonResult As Integer) As Boolean If NeitherNull(x, y, comparisonResult) Then Dim xPrecedence = 0 Dim yPrecedence = 0 s_operatorPrecedenceMap.TryGetValue(x.Kind, xPrecedence) s_operatorPrecedenceMap.TryGetValue(y.Kind, yPrecedence) comparisonResult = If(xPrecedence = yPrecedence, 0, If(xPrecedence < yPrecedence, -1, 1)) End If Return comparisonResult = 0 End Function Private Shared Function EqualParameterLists(x As ParameterListSyntax, y As ParameterListSyntax, ByRef comparisonResult As Integer) As Boolean Dim result = 0 If NeitherNull(x, y, result) Then Dim xParameterCount = x.Parameters.Count Dim yParameterCount = y.Parameters.Count comparisonResult = If(xParameterCount = yParameterCount, 0, If(x.Parameters.Count < y.Parameters.Count, -1, 1)) End If Return comparisonResult = 0 End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/Test/Core/Diagnostics/SuppressMessageAttributeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public abstract partial class SuppressMessageAttributeTests { #region Local Suppression public static IEnumerable<string[]> QualifiedAttributeNames { get; } = new[] { new[] { "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute" }, new[] { "System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute" }, }; public static IEnumerable<string[]> SimpleAttributeNames { get; } = new[] { new[] { "SuppressMessage" }, new[] { "UnconditionalSuppressMessage" } }; [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task LocalSuppressionOnType(string attrName) { await VerifyCSharpAsync(@" [" + attrName + @"(""Test"", ""Declaration"")] public class C { } public class C1 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C1")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task MultipleLocalSuppressionsOnSingleSymbol(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [" + attrName + @"(""Test"", ""Declaration"")] [" + attrName + @"(""Test"", ""TypeDeclaration"")] public class C { } ", new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C"), new WarningOnTypeDeclarationAnalyzer() }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task DuplicateLocalSuppressions(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [" + attrName + @"(""Test"", ""Declaration"")] [" + attrName + @"(""Test"", ""Declaration"")] public class C { } ", new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task LocalSuppressionOnMember(string attrName) { await VerifyCSharpAsync(@" public class C { [" + attrName + @"(""Test"", ""Declaration"")] public void Goo() {} public void Goo1() {} } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("Goo") }, Diagnostic("Declaration", "Goo1")); } #endregion #region Global Suppression [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnNamespaces(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N.N1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N4"")] namespace N { namespace N1 { namespace N2.N3 { } } } namespace N4 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") }, Diagnostic("Declaration", "N2"), Diagnostic("Declaration", "N3")); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnNamespaces_NamespaceAndDescendants(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""namespaceanddescendants"", Target=""N4"")] namespace N { namespace N1 { namespace N2.N3 { } } } namespace N4 { namespace N5 { } } namespace N.N1.N6.N7 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") }, Diagnostic("Declaration", "N")); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnTypesAndNamespaces_NamespaceAndDescendants(string attrName) { var source = @" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1.N2"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N4"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C2"")] namespace N { namespace N1 { class C1 { } namespace N2.N3 { class C2 { } class C3 { class C4 { } } } } } namespace N4 { namespace N5 { class C5 { } } class C6 { } } namespace N.N1.N2.N7 { class C7 { } } "; await VerifyCSharpAsync(source, new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") }, Diagnostic("Declaration", "N"), Diagnostic("Declaration", "N1")); await VerifyCSharpAsync(source, new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C1")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnTypes(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ef"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Egg"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ele`2"")] public class E { } public interface Ef { } public struct Egg { } public delegate void Ele<T1,T2>(T1 x, T2 y); ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnNestedTypes(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C.A1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C+A2"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C+A3"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C.A4"")] public class C { public class A1 { } public class A2 { } public class A3 { } public delegate void A4(); } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("A") }, Diagnostic("Declaration", "A1"), Diagnostic("Declaration", "A3"), Diagnostic("Declaration", "A4")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GlobalSuppressionOnBasicModule(string attrName) { await VerifyBasicAsync(@" <assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""M"")> Module M Class C End Class End Module ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnMembers(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M3`1()"")] public class C { int M1; public void M2() {} public static void M3<T>() {} } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") }, new[] { Diagnostic("Declaration", "M2") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnValueTupleMemberWithDocId(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""~M:C.M~System.Threading.Tasks.Task{System.ValueTuple{System.Boolean,ErrorCode}}"")] enum ErrorCode {} class C { Task<(bool status, ErrorCode errorCode)> M() => null; } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task MultipleGlobalSuppressionsOnSingleSymbol(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [assembly: " + attrName + @"(""Test"", ""TypeDeclaration"", Scope=""Type"", Target=""E"")] public class E { } ", new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("E"), new WarningOnTypeDeclarationAnalyzer() }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task DuplicateGlobalSuppressions(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] public class E { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") }); } #endregion #region Syntax Semantics [Fact] public async Task WarningOnCommentAnalyzerCSharp() { await VerifyCSharpAsync("// Comment\r\n /* Comment */", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "// Comment"), Diagnostic("Comment", "/* Comment */")); } [Fact] public async Task WarningOnCommentAnalyzerBasic() { await VerifyBasicAsync("' Comment", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "' Comment")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsCSharp(string attrName) { await VerifyCSharpAsync(@" // before module attributes [module: " + attrName + @"(""Test"", ""Comment"")] // before class public class C { // before method public void Goo() // after method declaration { // inside method } } // after class ", new[] { new WarningOnCommentAnalyzer() }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsBasic(string attrName) { await VerifyBasicAsync(@" ' before module attributes <Module: " + attrName + @"(""Test"", ""Comment"")> ' before class Public Class C ' before sub Public Sub Goo() ' after sub statement ' inside sub End Sub End Class ' after class ", new[] { new WarningOnCommentAnalyzer() }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsOnTargetCSharp(string attrName) { await VerifyCSharpAsync(@" // before module attributes [module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""C.Goo():System.Void"")] // before class public class C { // before method public void Goo() // after method declaration { // inside method } } // after class ", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "// before module attributes"), Diagnostic("Comment", "// before class"), Diagnostic("Comment", "// after class")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsOnTargetBasic(string attrName) { await VerifyBasicAsync(@" ' before module attributes <Module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Member"", Target:=""C.Goo():System.Void"")> ' before class Public Class C ' before sub Public Sub Goo() ' after sub statement ' inside sub End Sub End Class ' after class ", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "' before module attributes"), Diagnostic("Comment", "' before class"), Diagnostic("Comment", "' after class")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" [assembly: " + attrName + @"(""Test"", ""Token"", Scope=""namespace"", Target=""A.B"")] namespace A [|{ namespace B { class C {} } }|] ", Diagnostic("Token", "{").WithLocation(4, 1), Diagnostic("Token", "class").WithLocation(7, 9), Diagnostic("Token", "C").WithLocation(7, 15), Diagnostic("Token", "{").WithLocation(7, 17), Diagnostic("Token", "}").WithLocation(7, 18), Diagnostic("Token", "}").WithLocation(9, 1)); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceAndChildDeclarationCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" [assembly: " + attrName + @"(""Test"", ""Token"", Scope=""NamespaceAndDescendants"", Target=""A.B"")] namespace A [|{ namespace B { class C {} } }|] ", Diagnostic("Token", "{").WithLocation(4, 1), Diagnostic("Token", "}").WithLocation(9, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" <assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""Namespace"", Target:=""A.B"")> Namespace [|A Namespace B Class C End Class End Namespace End|] Namespace ", Diagnostic("Token", "A").WithLocation(3, 11), Diagnostic("Token", "Class").WithLocation(5, 9), Diagnostic("Token", "C").WithLocation(5, 15), Diagnostic("Token", "End").WithLocation(6, 9), Diagnostic("Token", "Class").WithLocation(6, 13), Diagnostic("Token", "End").WithLocation(8, 1)); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceAndDescendantsDeclarationBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" <assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""NamespaceAndDescendants"", Target:=""A.B"")> Namespace [|A Namespace B Class C End Class End Namespace End|] Namespace ", Diagnostic("Token", "A").WithLocation(3, 11), Diagnostic("Token", "End").WithLocation(8, 1)); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [InlineData("Namespace")] [InlineData("NamespaceAndDescendants")] public async Task DontSuppressSyntaxDiagnosticsInRootNamespaceBasic(string scope) { await VerifyBasicAsync($@" <module: System.Diagnostics.SuppressMessage(""Test"", ""Comment"", Scope:=""{scope}"", Target:=""RootNamespace"")> ' In root namespace ", rootNamespace: "RootNamespace", analyzers: new[] { new WarningOnCommentAnalyzer() }, diagnostics: Diagnostic("Comment", "' In root namespace").WithLocation(3, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnTypesCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; namespace N [|{ [" + attrName + @"(""Test"", ""Token"")] class C<T> {} [" + attrName + @"(""Test"", ""Token"")] struct S<T> {} [" + attrName + @"(""Test"", ""Token"")] interface I<T>{} [" + attrName + @"(""Test"", ""Token"")] enum E {} [" + attrName + @"(""Test"", ""Token"")] delegate void D(); }|] ", Diagnostic("Token", "{").WithLocation(5, 1), Diagnostic("Token", "}").WithLocation(20, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnTypesBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Namespace [|N <" + attrName + @"(""Test"", ""Token"")> Module M End Module <" + attrName + @"(""Test"", ""Token"")> Class C End Class <" + attrName + @"(""Test"", ""Token"")> Structure S End Structure <" + attrName + @"(""Test"", ""Token"")> Interface I End Interface <" + attrName + @"(""Test"", ""Token"")> Enum E None End Enum <" + attrName + @"(""Test"", ""Token"")> Delegate Sub D() End|] Namespace ", Diagnostic("Token", "N").WithLocation(4, 11), Diagnostic("Token", "End").WithLocation(28, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnFieldsCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; class C [|{ [" + attrName + @"(""Test"", ""Token"")] int field1 = 1, field2 = 2; [" + attrName + @"(""Test"", ""Token"")] int field3 = 3; }|] ", Diagnostic("Token", "{"), Diagnostic("Token", "}")); } [Theory] [WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEnumFieldsCSharp(string attrName) { await VerifyCSharpAsync(@" // before module attributes [module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""E.Field1"")] // before enum public enum E { // before Field1 declaration Field1, // after Field1 declaration Field2 // after Field2 declaration } // after enum ", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "// before module attributes"), Diagnostic("Comment", "// before enum"), Diagnostic("Comment", "// after Field1 declaration"), Diagnostic("Comment", "// after Field2 declaration"), Diagnostic("Comment", "// after enum")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnFieldsBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Class [|C <" + attrName + @"(""Test"", ""Token"")> Public field1 As Integer = 1, field2 As Double = 2.0 <" + attrName + @"(""Test"", ""Token"")> Public field3 As Integer = 3 End|] Class ", Diagnostic("Token", "C"), Diagnostic("Token", "End")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventsCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] public event System.Action<int> E1; [" + attrName + @"(""Test"", ""Token"")] public event System.Action<int> E2, E3; }|] ", Diagnostic("Token", "{"), Diagnostic("Token", "}")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventsBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Event E1 As System.Action(Of Integer) <" + attrName + @"(""Test"", ""Token"")> Public Event E2(ByVal arg As Integer) End|] Class ", Diagnostic("Token", "C"), Diagnostic("Token", "End")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { public event System.Action<int> E [|{ [" + attrName + @"(""Test"", ""Token"")] add {} remove|] {} } } ", Diagnostic("Token", "{").WithLocation(5, 5), Diagnostic("Token", "remove").WithLocation(8, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Public Custom Event E As System.Action(Of Integer[|) <" + attrName + @"(""Test"", ""Token"")> AddHandler(value As Action(Of Integer)) End AddHandler RemoveHandler|](value As Action(Of Integer)) End RemoveHandler RaiseEvent(obj As Integer) End RaiseEvent End Event End Class ", Diagnostic("Token", ")"), Diagnostic("Token", "RemoveHandler")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { public event System.Action<int> E { add {[|} [" + attrName + @"(""Test"", ""Token"")] remove {} }|] } ", Diagnostic("Token", "}").WithLocation(6, 14), Diagnostic("Token", "}").WithLocation(9, 5)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Public Custom Event E As System.Action(Of Integer) AddHandler(value As Action(Of Integer)) End [|AddHandler <" + attrName + @"(""Test"", ""Token"")> RemoveHandler(value As Action(Of Integer)) End RemoveHandler RaiseEvent|](obj As Integer) End RaiseEvent End Event End Class ", Diagnostic("Token", "AddHandler"), Diagnostic("Token", "RaiseEvent")); } [WorkItem(1103442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103442")] [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnRaiseEventAccessorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Public Custom Event E As System.Action(Of Integer) AddHandler(value As Action(Of Integer)) End AddHandler RemoveHandler(value As Action(Of Integer)) End [|RemoveHandler <" + attrName + @"(""Test"", ""Token"")> RaiseEvent(obj As Integer) End RaiseEvent End|] Event End Class ", Diagnostic("Token", "RemoveHandler"), Diagnostic("Token", "End")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; class C [|{ [" + attrName + @"(""Test"", ""Token"")] int Property1 { get; set; } [" + attrName + @"(""Test"", ""Token"")] int Property2 { get { return 2; } set { Property1 = 2; } } }|] ", Diagnostic("Token", "{").WithLocation(5, 1), Diagnostic("Token", "}").WithLocation(15, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Class [|C <" + attrName + @"(""Test"", ""Token"")> Property Property1 As Integer <" + attrName + @"(""Test"", ""Token"")> Property Property2 As Integer Get Return 2 End Get Set(value As Integer) Property1 = value End Set End Property End|] Class ", Diagnostic("Token", "C").WithLocation(4, 7), Diagnostic("Token", "End").WithLocation(17, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyGetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int Property [|{ [" + attrName + @"(""Test"", ""Token"")] get { return 2; } set|] { x = 2; } } } ", Diagnostic("Token", "{").WithLocation(6, 5), Diagnostic("Token", "set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyGetterBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Private x As Integer Property [Property] As [|Integer <" + attrName + @"(""Test"", ""Token"")> Get Return 2 End Get Set|](value As Integer) x = value End Set End Property End Class ", Diagnostic("Token", "Integer").WithLocation(4, 28), Diagnostic("Token", "Set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertySetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int Property [|{ [" + attrName + @"(""Test"", ""Token"")] get { return 2; } set|] { x = 2; } } } ", Diagnostic("Token", "{").WithLocation(6, 5), Diagnostic("Token", "set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertySetterBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Private x As Integer Property [Property] As Integer Get Return 2 End [|Get <" + attrName + @"(""Test"", ""Token"")> Set(value As Integer) x = value End Set End|] Property End Class ", Diagnostic("Token", "Get").WithLocation(7, 13), Diagnostic("Token", "End").WithLocation(12, 5)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnIndexerCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x[|; [" + attrName + @"(""Test"", ""Token"")] int this[int i] { get { return 2; } set { x = 2; } } }|] ", Diagnostic("Token", ";").WithLocation(4, 10), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnIndexerGetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int this[int i] [|{ [" + attrName + @"(""Test"", ""Token"")] get { return 2; } set|] { x = 2; } } } ", Diagnostic("Token", "{").WithLocation(6, 5), Diagnostic("Token", "set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnIndexerSetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int this[int i] { get { return 2; [|} [" + attrName + @"(""Test"", ""Token"")] set { x = 2; } }|] } ", Diagnostic("Token", "}").WithLocation(7, 25), Diagnostic("Token", "}").WithLocation(10, 5)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnMethodCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; abstract class C [|{ [" + attrName + @"(""Test"", ""Token"")] public void M1<T>() {} [" + attrName + @"(""Test"", ""Token"")] public abstract void M2(); }|] ", Diagnostic("Token", "{").WithLocation(5, 1), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnMethodBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Public MustInherit Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Function M2(Of T)() As Integer Return 0 End Function <" + attrName + @"(""Test"", ""Token"")> Public MustOverride Sub M3() End|] Class ", Diagnostic("Token", "C").WithLocation(4, 26), Diagnostic("Token", "End").WithLocation(12, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnOperatorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] public static C operator +(C a, C b) { return null; } }|] ", Diagnostic("Token", "{").WithLocation(3, 1), Diagnostic("Token", "}").WithLocation(9, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnOperatorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Shared Operator +(ByVal a As C, ByVal b As C) As C Return Nothing End Operator End|] Class ", Diagnostic("Token", "C").WithLocation(2, 7), Diagnostic("Token", "End").WithLocation(7, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnConstructorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class Base { public Base(int x) {} } class C : Base [|{ [" + attrName + @"(""Test"", ""Token"")] public C() : base(0) {} }|] ", Diagnostic("Token", "{").WithLocation(8, 1), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnConstructorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Sub New() End Sub End|] Class ", Diagnostic("Token", "C").WithLocation(2, 7), Diagnostic("Token", "End").WithLocation(6, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnDestructorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] ~C() {} }|] ", Diagnostic("Token", "{").WithLocation(3, 1), Diagnostic("Token", "}").WithLocation(6, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNestedTypeCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] class D { class E { } } }|] ", Diagnostic("Token", "{").WithLocation(3, 1), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNestedTypeBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class [|C <" + attrName + @"(""Test"", ""Token"")> Class D Class E End Class End Class End|] Class ", Diagnostic("Token", "C").WithLocation(2, 7), Diagnostic("Token", "End").WithLocation(8, 1)); } #endregion #region Special Cases [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageCompilationEnded(string attrName) { await VerifyCSharpAsync( @"[module: " + attrName + @"(""Test"", ""CompilationEnded"")]", new[] { new WarningOnCompilationEndedAnalyzer() }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnPropertyAccessor(string attrName) { await VerifyCSharpAsync(@" public class C { [" + attrName + @"(""Test"", ""Declaration"")] public string P { get; private set; } } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("get_") }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnDelegateInvoke(string attrName) { await VerifyCSharpAsync(@" public class C { [" + attrName + @"(""Test"", ""Declaration"")] delegate void D(); } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("Invoke") }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnCodeBodyCSharp(string attrName) { await VerifyCSharpAsync( @" public class C { [" + attrName + @"(""Test"", ""CodeBody"")] void Goo() { Goo(); } } ", new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.CSharp) }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnCodeBodyBasic(string attrName) { await VerifyBasicAsync( @" Public Class C <" + attrName + @"(""Test"", ""CodeBody"")> Sub Goo() Goo() End Sub End Class ", new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.VisualBasic) }); } #endregion #region Attribute Decoding [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task UnnecessaryScopeAndTarget(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")] public class C1 { } [" + attrName + @"(""Test"", ""Declaration"", Target=""C"")] public class C2 { } [" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C"")] public class C3 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task InvalidScopeOrTarget(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""C"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""E"")] public class C { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task MissingScopeOrTarget(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [module: " + attrName + @"(""Test"", ""Declaration"", Target=""C"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")] public class C { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task InvalidAttributeConstructorParameters(string attrName) { await VerifyBasicAsync(@" Imports System.Diagnostics.CodeAnalysis <module: " + attrName + @"UndeclaredIdentifier, ""Comment"")> <module: " + attrName + @"(""Test"", UndeclaredIdentifier)> <module: " + attrName + @"(""Test"", ""Comment"", Scope:=UndeclaredIdentifier, Target:=""C"")> <module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Type"", Target:=UndeclaredIdentifier)> Class C End Class ", new[] { new WarningOnTypeDeclarationAnalyzer() }, Diagnostic("TypeDeclaration", "C").WithLocation(9, 7)); } #endregion protected async Task VerifyCSharpAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { await VerifyAsync(source, LanguageNames.CSharp, analyzers, diagnostics); } protected Task VerifyTokenDiagnosticsCSharpAsync(string markup, params DiagnosticDescription[] diagnostics) { return VerifyTokenDiagnosticsAsync(markup, LanguageNames.CSharp, diagnostics); } protected async Task VerifyBasicAsync(string source, string rootNamespace, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { Assert.False(string.IsNullOrWhiteSpace(rootNamespace), string.Format("Invalid root namespace '{0}'", rootNamespace)); await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics, rootNamespace: rootNamespace); } protected async Task VerifyBasicAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics); } protected Task VerifyTokenDiagnosticsBasicAsync(string markup, params DiagnosticDescription[] diagnostics) { return VerifyTokenDiagnosticsAsync(markup, LanguageNames.VisualBasic, diagnostics); } protected abstract Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null); // Generate a diagnostic on every token in the specified spans, and verify that only the specified diagnostics are not suppressed private Task VerifyTokenDiagnosticsAsync(string markup, string language, DiagnosticDescription[] diagnostics) { MarkupTestFile.GetSpans(markup, out var source, out ImmutableArray<TextSpan> spans); Assert.True(spans.Length > 0, "Must specify a span within which to generate diagnostics on each token"); return VerifyAsync(source, language, new DiagnosticAnalyzer[] { new WarningOnTokenAnalyzer(spans) }, diagnostics); } protected abstract bool ConsiderArgumentsForComparingDiagnostics { get; } protected DiagnosticDescription Diagnostic(string id, string squiggledText) { var arguments = this.ConsiderArgumentsForComparingDiagnostics && squiggledText != null ? new[] { squiggledText } : null; return new DiagnosticDescription(id, false, squiggledText, arguments, null, null, false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public abstract partial class SuppressMessageAttributeTests { #region Local Suppression public static IEnumerable<string[]> QualifiedAttributeNames { get; } = new[] { new[] { "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute" }, new[] { "System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessageAttribute" }, }; public static IEnumerable<string[]> SimpleAttributeNames { get; } = new[] { new[] { "SuppressMessage" }, new[] { "UnconditionalSuppressMessage" } }; [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task LocalSuppressionOnType(string attrName) { await VerifyCSharpAsync(@" [" + attrName + @"(""Test"", ""Declaration"")] public class C { } public class C1 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C1")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task MultipleLocalSuppressionsOnSingleSymbol(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [" + attrName + @"(""Test"", ""Declaration"")] [" + attrName + @"(""Test"", ""TypeDeclaration"")] public class C { } ", new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C"), new WarningOnTypeDeclarationAnalyzer() }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task DuplicateLocalSuppressions(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [" + attrName + @"(""Test"", ""Declaration"")] [" + attrName + @"(""Test"", ""Declaration"")] public class C { } ", new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task LocalSuppressionOnMember(string attrName) { await VerifyCSharpAsync(@" public class C { [" + attrName + @"(""Test"", ""Declaration"")] public void Goo() {} public void Goo1() {} } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("Goo") }, Diagnostic("Declaration", "Goo1")); } #endregion #region Global Suppression [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnNamespaces(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N.N1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Namespace"", Target=""N4"")] namespace N { namespace N1 { namespace N2.N3 { } } } namespace N4 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") }, Diagnostic("Declaration", "N2"), Diagnostic("Declaration", "N3")); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnNamespaces_NamespaceAndDescendants(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""namespaceanddescendants"", Target=""N4"")] namespace N { namespace N1 { namespace N2.N3 { } } } namespace N4 { namespace N5 { } } namespace N.N1.N6.N7 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") }, Diagnostic("Declaration", "N")); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnTypesAndNamespaces_NamespaceAndDescendants(string attrName) { var source = @" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N.N1.N2"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""NamespaceAndDescendants"", Target=""N4"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C2"")] namespace N { namespace N1 { class C1 { } namespace N2.N3 { class C2 { } class C3 { class C4 { } } } } } namespace N4 { namespace N5 { class C5 { } } class C6 { } } namespace N.N1.N2.N7 { class C7 { } } "; await VerifyCSharpAsync(source, new[] { new WarningOnNamePrefixDeclarationAnalyzer("N") }, Diagnostic("Declaration", "N"), Diagnostic("Declaration", "N1")); await VerifyCSharpAsync(source, new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C1")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnTypes(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ef"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Egg"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""Ele`2"")] public class E { } public interface Ef { } public struct Egg { } public delegate void Ele<T1,T2>(T1 x, T2 y); ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnNestedTypes(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C.A1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""C+A2"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C+A3"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""member"", Target=""C.A4"")] public class C { public class A1 { } public class A2 { } public class A3 { } public delegate void A4(); } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("A") }, Diagnostic("Declaration", "A1"), Diagnostic("Declaration", "A3"), Diagnostic("Declaration", "A4")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GlobalSuppressionOnBasicModule(string attrName) { await VerifyBasicAsync(@" <assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""type"", Target=""M"")> Module M Class C End Class End Module ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnMembers(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M1"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""C.#M3`1()"")] public class C { int M1; public void M2() {} public static void M3<T>() {} } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") }, new[] { Diagnostic("Declaration", "M2") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task GlobalSuppressionOnValueTupleMemberWithDocId(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Member"", Target=""~M:C.M~System.Threading.Tasks.Task{System.ValueTuple{System.Boolean,ErrorCode}}"")] enum ErrorCode {} class C { Task<(bool status, ErrorCode errorCode)> M() => null; } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("M") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task MultipleGlobalSuppressionsOnSingleSymbol(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [assembly: " + attrName + @"(""Test"", ""TypeDeclaration"", Scope=""Type"", Target=""E"")] public class E { } ", new DiagnosticAnalyzer[] { new WarningOnNamePrefixDeclarationAnalyzer("E"), new WarningOnTypeDeclarationAnalyzer() }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task DuplicateGlobalSuppressions(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [assembly: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] public class E { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("E") }); } #endregion #region Syntax Semantics [Fact] public async Task WarningOnCommentAnalyzerCSharp() { await VerifyCSharpAsync("// Comment\r\n /* Comment */", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "// Comment"), Diagnostic("Comment", "/* Comment */")); } [Fact] public async Task WarningOnCommentAnalyzerBasic() { await VerifyBasicAsync("' Comment", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "' Comment")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsCSharp(string attrName) { await VerifyCSharpAsync(@" // before module attributes [module: " + attrName + @"(""Test"", ""Comment"")] // before class public class C { // before method public void Goo() // after method declaration { // inside method } } // after class ", new[] { new WarningOnCommentAnalyzer() }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsBasic(string attrName) { await VerifyBasicAsync(@" ' before module attributes <Module: " + attrName + @"(""Test"", ""Comment"")> ' before class Public Class C ' before sub Public Sub Goo() ' after sub statement ' inside sub End Sub End Class ' after class ", new[] { new WarningOnCommentAnalyzer() }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsOnTargetCSharp(string attrName) { await VerifyCSharpAsync(@" // before module attributes [module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""C.Goo():System.Void"")] // before class public class C { // before method public void Goo() // after method declaration { // inside method } } // after class ", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "// before module attributes"), Diagnostic("Comment", "// before class"), Diagnostic("Comment", "// after class")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task GloballySuppressSyntaxDiagnosticsOnTargetBasic(string attrName) { await VerifyBasicAsync(@" ' before module attributes <Module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Member"", Target:=""C.Goo():System.Void"")> ' before class Public Class C ' before sub Public Sub Goo() ' after sub statement ' inside sub End Sub End Class ' after class ", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "' before module attributes"), Diagnostic("Comment", "' before class"), Diagnostic("Comment", "' after class")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" [assembly: " + attrName + @"(""Test"", ""Token"", Scope=""namespace"", Target=""A.B"")] namespace A [|{ namespace B { class C {} } }|] ", Diagnostic("Token", "{").WithLocation(4, 1), Diagnostic("Token", "class").WithLocation(7, 9), Diagnostic("Token", "C").WithLocation(7, 15), Diagnostic("Token", "{").WithLocation(7, 17), Diagnostic("Token", "}").WithLocation(7, 18), Diagnostic("Token", "}").WithLocation(9, 1)); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceAndChildDeclarationCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" [assembly: " + attrName + @"(""Test"", ""Token"", Scope=""NamespaceAndDescendants"", Target=""A.B"")] namespace A [|{ namespace B { class C {} } }|] ", Diagnostic("Token", "{").WithLocation(4, 1), Diagnostic("Token", "}").WithLocation(9, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceDeclarationBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" <assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""Namespace"", Target:=""A.B"")> Namespace [|A Namespace B Class C End Class End Namespace End|] Namespace ", Diagnostic("Token", "A").WithLocation(3, 11), Diagnostic("Token", "Class").WithLocation(5, 9), Diagnostic("Token", "C").WithLocation(5, 15), Diagnostic("Token", "End").WithLocation(6, 9), Diagnostic("Token", "Class").WithLocation(6, 13), Diagnostic("Token", "End").WithLocation(8, 1)); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNamespaceAndDescendantsDeclarationBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" <assembly: " + attrName + @"(""Test"", ""Token"", Scope:=""NamespaceAndDescendants"", Target:=""A.B"")> Namespace [|A Namespace B Class C End Class End Namespace End|] Namespace ", Diagnostic("Token", "A").WithLocation(3, 11), Diagnostic("Token", "End").WithLocation(8, 1)); } [Theory, WorkItem(486, "https://github.com/dotnet/roslyn/issues/486")] [InlineData("Namespace")] [InlineData("NamespaceAndDescendants")] public async Task DontSuppressSyntaxDiagnosticsInRootNamespaceBasic(string scope) { await VerifyBasicAsync($@" <module: System.Diagnostics.SuppressMessage(""Test"", ""Comment"", Scope:=""{scope}"", Target:=""RootNamespace"")> ' In root namespace ", rootNamespace: "RootNamespace", analyzers: new[] { new WarningOnCommentAnalyzer() }, diagnostics: Diagnostic("Comment", "' In root namespace").WithLocation(3, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnTypesCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; namespace N [|{ [" + attrName + @"(""Test"", ""Token"")] class C<T> {} [" + attrName + @"(""Test"", ""Token"")] struct S<T> {} [" + attrName + @"(""Test"", ""Token"")] interface I<T>{} [" + attrName + @"(""Test"", ""Token"")] enum E {} [" + attrName + @"(""Test"", ""Token"")] delegate void D(); }|] ", Diagnostic("Token", "{").WithLocation(5, 1), Diagnostic("Token", "}").WithLocation(20, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnTypesBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Namespace [|N <" + attrName + @"(""Test"", ""Token"")> Module M End Module <" + attrName + @"(""Test"", ""Token"")> Class C End Class <" + attrName + @"(""Test"", ""Token"")> Structure S End Structure <" + attrName + @"(""Test"", ""Token"")> Interface I End Interface <" + attrName + @"(""Test"", ""Token"")> Enum E None End Enum <" + attrName + @"(""Test"", ""Token"")> Delegate Sub D() End|] Namespace ", Diagnostic("Token", "N").WithLocation(4, 11), Diagnostic("Token", "End").WithLocation(28, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnFieldsCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; class C [|{ [" + attrName + @"(""Test"", ""Token"")] int field1 = 1, field2 = 2; [" + attrName + @"(""Test"", ""Token"")] int field3 = 3; }|] ", Diagnostic("Token", "{"), Diagnostic("Token", "}")); } [Theory] [WorkItem(6379, "https://github.com/dotnet/roslyn/issues/6379")] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEnumFieldsCSharp(string attrName) { await VerifyCSharpAsync(@" // before module attributes [module: " + attrName + @"(""Test"", ""Comment"", Scope=""Member"" Target=""E.Field1"")] // before enum public enum E { // before Field1 declaration Field1, // after Field1 declaration Field2 // after Field2 declaration } // after enum ", new[] { new WarningOnCommentAnalyzer() }, Diagnostic("Comment", "// before module attributes"), Diagnostic("Comment", "// before enum"), Diagnostic("Comment", "// after Field1 declaration"), Diagnostic("Comment", "// after Field2 declaration"), Diagnostic("Comment", "// after enum")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnFieldsBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Class [|C <" + attrName + @"(""Test"", ""Token"")> Public field1 As Integer = 1, field2 As Double = 2.0 <" + attrName + @"(""Test"", ""Token"")> Public field3 As Integer = 3 End|] Class ", Diagnostic("Token", "C"), Diagnostic("Token", "End")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventsCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] public event System.Action<int> E1; [" + attrName + @"(""Test"", ""Token"")] public event System.Action<int> E2, E3; }|] ", Diagnostic("Token", "{"), Diagnostic("Token", "}")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventsBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Event E1 As System.Action(Of Integer) <" + attrName + @"(""Test"", ""Token"")> Public Event E2(ByVal arg As Integer) End|] Class ", Diagnostic("Token", "C"), Diagnostic("Token", "End")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { public event System.Action<int> E [|{ [" + attrName + @"(""Test"", ""Token"")] add {} remove|] {} } } ", Diagnostic("Token", "{").WithLocation(5, 5), Diagnostic("Token", "remove").WithLocation(8, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventAddAccessorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Public Custom Event E As System.Action(Of Integer[|) <" + attrName + @"(""Test"", ""Token"")> AddHandler(value As Action(Of Integer)) End AddHandler RemoveHandler|](value As Action(Of Integer)) End RemoveHandler RaiseEvent(obj As Integer) End RaiseEvent End Event End Class ", Diagnostic("Token", ")"), Diagnostic("Token", "RemoveHandler")); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { public event System.Action<int> E { add {[|} [" + attrName + @"(""Test"", ""Token"")] remove {} }|] } ", Diagnostic("Token", "}").WithLocation(6, 14), Diagnostic("Token", "}").WithLocation(9, 5)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnEventRemoveAccessorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Public Custom Event E As System.Action(Of Integer) AddHandler(value As Action(Of Integer)) End [|AddHandler <" + attrName + @"(""Test"", ""Token"")> RemoveHandler(value As Action(Of Integer)) End RemoveHandler RaiseEvent|](obj As Integer) End RaiseEvent End Event End Class ", Diagnostic("Token", "AddHandler"), Diagnostic("Token", "RaiseEvent")); } [WorkItem(1103442, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1103442")] [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnRaiseEventAccessorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Public Custom Event E As System.Action(Of Integer) AddHandler(value As Action(Of Integer)) End AddHandler RemoveHandler(value As Action(Of Integer)) End [|RemoveHandler <" + attrName + @"(""Test"", ""Token"")> RaiseEvent(obj As Integer) End RaiseEvent End|] Event End Class ", Diagnostic("Token", "RemoveHandler"), Diagnostic("Token", "End")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; class C [|{ [" + attrName + @"(""Test"", ""Token"")] int Property1 { get; set; } [" + attrName + @"(""Test"", ""Token"")] int Property2 { get { return 2; } set { Property1 = 2; } } }|] ", Diagnostic("Token", "{").WithLocation(5, 1), Diagnostic("Token", "}").WithLocation(15, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Class [|C <" + attrName + @"(""Test"", ""Token"")> Property Property1 As Integer <" + attrName + @"(""Test"", ""Token"")> Property Property2 As Integer Get Return 2 End Get Set(value As Integer) Property1 = value End Set End Property End|] Class ", Diagnostic("Token", "C").WithLocation(4, 7), Diagnostic("Token", "End").WithLocation(17, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyGetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int Property [|{ [" + attrName + @"(""Test"", ""Token"")] get { return 2; } set|] { x = 2; } } } ", Diagnostic("Token", "{").WithLocation(6, 5), Diagnostic("Token", "set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertyGetterBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Private x As Integer Property [Property] As [|Integer <" + attrName + @"(""Test"", ""Token"")> Get Return 2 End Get Set|](value As Integer) x = value End Set End Property End Class ", Diagnostic("Token", "Integer").WithLocation(4, 28), Diagnostic("Token", "Set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertySetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int Property [|{ [" + attrName + @"(""Test"", ""Token"")] get { return 2; } set|] { x = 2; } } } ", Diagnostic("Token", "{").WithLocation(6, 5), Diagnostic("Token", "set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnPropertySetterBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class C Private x As Integer Property [Property] As Integer Get Return 2 End [|Get <" + attrName + @"(""Test"", ""Token"")> Set(value As Integer) x = value End Set End|] Property End Class ", Diagnostic("Token", "Get").WithLocation(7, 13), Diagnostic("Token", "End").WithLocation(12, 5)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnIndexerCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x[|; [" + attrName + @"(""Test"", ""Token"")] int this[int i] { get { return 2; } set { x = 2; } } }|] ", Diagnostic("Token", ";").WithLocation(4, 10), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnIndexerGetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int this[int i] [|{ [" + attrName + @"(""Test"", ""Token"")] get { return 2; } set|] { x = 2; } } } ", Diagnostic("Token", "{").WithLocation(6, 5), Diagnostic("Token", "set").WithLocation(9, 9)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnIndexerSetterCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C { int x; int this[int i] { get { return 2; [|} [" + attrName + @"(""Test"", ""Token"")] set { x = 2; } }|] } ", Diagnostic("Token", "}").WithLocation(7, 25), Diagnostic("Token", "}").WithLocation(10, 5)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnMethodCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" using System.Diagnostics.CodeAnalysis; abstract class C [|{ [" + attrName + @"(""Test"", ""Token"")] public void M1<T>() {} [" + attrName + @"(""Test"", ""Token"")] public abstract void M2(); }|] ", Diagnostic("Token", "{").WithLocation(5, 1), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnMethodBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Imports System.Diagnostics.CodeAnalysis Public MustInherit Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Function M2(Of T)() As Integer Return 0 End Function <" + attrName + @"(""Test"", ""Token"")> Public MustOverride Sub M3() End|] Class ", Diagnostic("Token", "C").WithLocation(4, 26), Diagnostic("Token", "End").WithLocation(12, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnOperatorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] public static C operator +(C a, C b) { return null; } }|] ", Diagnostic("Token", "{").WithLocation(3, 1), Diagnostic("Token", "}").WithLocation(9, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnOperatorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Shared Operator +(ByVal a As C, ByVal b As C) As C Return Nothing End Operator End|] Class ", Diagnostic("Token", "C").WithLocation(2, 7), Diagnostic("Token", "End").WithLocation(7, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnConstructorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class Base { public Base(int x) {} } class C : Base [|{ [" + attrName + @"(""Test"", ""Token"")] public C() : base(0) {} }|] ", Diagnostic("Token", "{").WithLocation(8, 1), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnConstructorBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class [|C <" + attrName + @"(""Test"", ""Token"")> Public Sub New() End Sub End|] Class ", Diagnostic("Token", "C").WithLocation(2, 7), Diagnostic("Token", "End").WithLocation(6, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnDestructorCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] ~C() {} }|] ", Diagnostic("Token", "{").WithLocation(3, 1), Diagnostic("Token", "}").WithLocation(6, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNestedTypeCSharp(string attrName) { await VerifyTokenDiagnosticsCSharpAsync(@" class C [|{ [" + attrName + @"(""Test"", ""Token"")] class D { class E { } } }|] ", Diagnostic("Token", "{").WithLocation(3, 1), Diagnostic("Token", "}").WithLocation(11, 1)); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressSyntaxDiagnosticsOnNestedTypeBasic(string attrName) { await VerifyTokenDiagnosticsBasicAsync(@" Class [|C <" + attrName + @"(""Test"", ""Token"")> Class D Class E End Class End Class End|] Class ", Diagnostic("Token", "C").WithLocation(2, 7), Diagnostic("Token", "End").WithLocation(8, 1)); } #endregion #region Special Cases [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageCompilationEnded(string attrName) { await VerifyCSharpAsync( @"[module: " + attrName + @"(""Test"", ""CompilationEnded"")]", new[] { new WarningOnCompilationEndedAnalyzer() }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnPropertyAccessor(string attrName) { await VerifyCSharpAsync(@" public class C { [" + attrName + @"(""Test"", ""Declaration"")] public string P { get; private set; } } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("get_") }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnDelegateInvoke(string attrName) { await VerifyCSharpAsync(@" public class C { [" + attrName + @"(""Test"", ""Declaration"")] delegate void D(); } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("Invoke") }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnCodeBodyCSharp(string attrName) { await VerifyCSharpAsync( @" public class C { [" + attrName + @"(""Test"", ""CodeBody"")] void Goo() { Goo(); } } ", new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.CSharp) }); } [Theory] [MemberData(nameof(QualifiedAttributeNames))] public async Task SuppressMessageOnCodeBodyBasic(string attrName) { await VerifyBasicAsync( @" Public Class C <" + attrName + @"(""Test"", ""CodeBody"")> Sub Goo() Goo() End Sub End Class ", new[] { new WarningOnCodeBodyAnalyzer(LanguageNames.VisualBasic) }); } #endregion #region Attribute Decoding [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task UnnecessaryScopeAndTarget(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")] public class C1 { } [" + attrName + @"(""Test"", ""Declaration"", Target=""C"")] public class C2 { } [" + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""C"")] public class C3 { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task InvalidScopeOrTarget(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""C"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"", Target=""E"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Class"", Target=""E"")] public class C { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task MissingScopeOrTarget(string attrName) { await VerifyCSharpAsync(@" using System.Diagnostics.CodeAnalysis; [module: " + attrName + @"(""Test"", ""Declaration"", Target=""C"")] [module: " + attrName + @"(""Test"", ""Declaration"", Scope=""Type"")] public class C { } ", new[] { new WarningOnNamePrefixDeclarationAnalyzer("C") }, Diagnostic("Declaration", "C")); } [Theory] [MemberData(nameof(SimpleAttributeNames))] public async Task InvalidAttributeConstructorParameters(string attrName) { await VerifyBasicAsync(@" Imports System.Diagnostics.CodeAnalysis <module: " + attrName + @"UndeclaredIdentifier, ""Comment"")> <module: " + attrName + @"(""Test"", UndeclaredIdentifier)> <module: " + attrName + @"(""Test"", ""Comment"", Scope:=UndeclaredIdentifier, Target:=""C"")> <module: " + attrName + @"(""Test"", ""Comment"", Scope:=""Type"", Target:=UndeclaredIdentifier)> Class C End Class ", new[] { new WarningOnTypeDeclarationAnalyzer() }, Diagnostic("TypeDeclaration", "C").WithLocation(9, 7)); } #endregion protected async Task VerifyCSharpAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { await VerifyAsync(source, LanguageNames.CSharp, analyzers, diagnostics); } protected Task VerifyTokenDiagnosticsCSharpAsync(string markup, params DiagnosticDescription[] diagnostics) { return VerifyTokenDiagnosticsAsync(markup, LanguageNames.CSharp, diagnostics); } protected async Task VerifyBasicAsync(string source, string rootNamespace, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { Assert.False(string.IsNullOrWhiteSpace(rootNamespace), string.Format("Invalid root namespace '{0}'", rootNamespace)); await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics, rootNamespace: rootNamespace); } protected async Task VerifyBasicAsync(string source, DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { await VerifyAsync(source, LanguageNames.VisualBasic, analyzers, diagnostics); } protected Task VerifyTokenDiagnosticsBasicAsync(string markup, params DiagnosticDescription[] diagnostics) { return VerifyTokenDiagnosticsAsync(markup, LanguageNames.VisualBasic, diagnostics); } protected abstract Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null); // Generate a diagnostic on every token in the specified spans, and verify that only the specified diagnostics are not suppressed private Task VerifyTokenDiagnosticsAsync(string markup, string language, DiagnosticDescription[] diagnostics) { MarkupTestFile.GetSpans(markup, out var source, out ImmutableArray<TextSpan> spans); Assert.True(spans.Length > 0, "Must specify a span within which to generate diagnostics on each token"); return VerifyAsync(source, language, new DiagnosticAnalyzer[] { new WarningOnTokenAnalyzer(spans) }, diagnostics); } protected abstract bool ConsiderArgumentsForComparingDiagnostics { get; } protected DiagnosticDescription Diagnostic(string id, string squiggledText) { var arguments = this.ConsiderArgumentsForComparingDiagnostics && squiggledText != null ? new[] { squiggledText } : null; return new DiagnosticDescription(id, false, squiggledText, arguments, null, null, false); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Core/Implementation/IntelliSense/AsyncCompletion/CompletionSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; using VSUtilities = Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); internal const string TriggerLocation = nameof(TriggerLocation); internal const string ExpandedItemTriggerLocation = nameof(ExpandedItemTriggerLocation); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); internal const string Description = nameof(Description); internal const string PotentialCommitCharacters = nameof(PotentialCommitCharacters); internal const string ExcludedCommitCharacters = nameof(ExcludedCommitCharacters); internal const string NonBlockingCompletion = nameof(NonBlockingCompletion); internal const string TypeImportCompletionEnabled = nameof(TypeImportCompletionEnabled); internal const string TargetTypeFilterExperimentEnabled = nameof(TargetTypeFilterExperimentEnabled); private static readonly ImmutableArray<ImageElement> s_WarningImageAttributeImagesArray = ImmutableArray.Create(new ImageElement(Glyph.CompletionWarning.GetImageId(), EditorFeaturesResources.Warning_image_element)); private static readonly EditorOptionKey<bool> NonBlockingCompletionEditorOption = new(NonBlockingCompletion); // Use CWT to cache data needed to create VSCompletionItem, so the table would be cleared when Roslyn completion item cache is cleared. private static readonly ConditionalWeakTable<RoslynCompletionItem, StrongBox<VSCompletionItemData>> s_roslynItemToVsItemData = new(); private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet<string> _roles; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; private readonly VSUtilities.IUIThreadOperationExecutor _operationExecutor; private readonly IAsynchronousOperationListener _asyncListener; private bool _snippetCompletionTriggeredIndirectly; internal CompletionSource( ITextView textView, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, IThreadingContext threadingContext, VSUtilities.IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListener asyncListener) : base(threadingContext) { _textView = textView; _streamingPresenter = streamingPresenter; _operationExecutor = operationExecutor; _asyncListener = asyncListener; _isDebuggerTextView = textView is IDebuggerTextView; _roles = textView.Roles.ToImmutableHashSet(); } public AsyncCompletionData.CompletionStartData InitializeCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, CancellationToken cancellationToken) { // We take sourceText from document to get a snapshot span. // We would like to be sure that nobody changes buffers at the same time. AssertIsForeground(); if (_textView.Selection.Mode == TextSelectionMode.Box) { // No completion with multiple selection return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } // The Editor supports the option per textView. // There could be mixed desired behavior per textView and even per same completion session. // The right fix would be to send this information as a result of the method. // Then, the Editor would choose the right behavior for mixed cases. _textView.Options.GlobalOptions.SetOptionValue(NonBlockingCompletionEditorOption, !document.Project.Solution.Workspace.Options.GetOption(CompletionOptions.BlockForCompletionItems2, service.Language)); // In case of calls with multiple completion services for the same view (e.g. TypeScript and C#), those completion services must not be called simultaneously for the same session. // Therefore, in each completion session we use a list of commit character for a specific completion service and a specific content type. _textView.Properties[PotentialCommitCharacters] = service.GetRules().DefaultCommitCharacters; // Reset a flag which means a snippet triggered by ? + Tab. // Set it later if met the condition. _snippetCompletionTriggeredIndirectly = false; CheckForExperimentStatus(_textView, document); var sourceText = document.GetTextSynchronously(cancellationToken); return ShouldTriggerCompletion(trigger, triggerLocation, sourceText, document, service) ? new AsyncCompletionData.CompletionStartData( participation: AsyncCompletionData.CompletionParticipation.ProvidesItems, applicableToSpan: new SnapshotSpan( triggerLocation.Snapshot, service.GetDefaultCompletionListSpan(sourceText, triggerLocation.Position).ToSpan())) : AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; // For telemetry reporting purpose static void CheckForExperimentStatus(ITextView textView, Document document) { var options = document.Project.Solution.Options; textView.Properties[TargetTypeFilterExperimentEnabled] = options.GetOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag); var importCompletionOptionValue = options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); var importCompletionExperimentValue = options.GetOption(CompletionOptions.TypeImportCompletionFeatureFlag); var isTypeImportEnababled = importCompletionOptionValue == true || (importCompletionOptionValue == null && importCompletionExperimentValue); textView.Properties[TypeImportCompletionEnabled] = isTypeImportEnababled; } } private bool ShouldTriggerCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SourceText sourceText, Document document, CompletionService completionService) { // The trigger reason guarantees that user wants a completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Invoke || trigger.Reason == AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique) { return true; } // Enter does not trigger completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\n') { return false; } //The user may be trying to invoke snippets through question-tab. // We may provide a completion after that. // Otherwise, tab should not be a completion trigger. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t') { return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position); } var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); // The completion service decides that user may want a completion. if (completionService.ShouldTriggerCompletion(document.Project, sourceText, triggerLocation.Position, roslynTrigger)) { return true; } return false; } private bool TryInvokeSnippetCompletion( CompletionService completionService, Document document, SourceText text, int caretPoint) { var rules = completionService.GetRules(); // Do not invoke snippet if the corresponding rule is not set in options. if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab) { return false; } var syntaxFactsOpt = document.GetLanguageService<ISyntaxFactsService>(); // Snippets are included if the user types: <quesiton><tab> // If at least one condition for snippets do not hold, bail out. if (syntaxFactsOpt == null || caretPoint < 3 || text[caretPoint - 2] != '?' || !QuestionMarkIsPrecededByIdentifierAndWhitespace(text, caretPoint - 2, syntaxFactsOpt)) { return false; } // Because <question><tab> is actually a command to bring up snippets, // we delete the last <question> that was typed. var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty); document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None); _snippetCompletionTriggeredIndirectly = true; return true; } public Task<AsyncCompletionData.CompletionContext> GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } public async Task<AsyncCompletionData.CompletionContext> GetExpandedCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionExpander expander, AsyncCompletionData.CompletionTrigger intialTrigger, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { // We only want to provide expanded items for Roslyn's expander. if ((object)expander == FilterSet.Expander && session.Properties.TryGetProperty(ExpandedItemTriggerLocation, out SnapshotPoint initialTriggerLocation)) { return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, isExpanded: true, cancellationToken).ConfigureAwait(false); } return AsyncCompletionData.CompletionContext.Empty; } private async Task<AsyncCompletionData.CompletionContext> GetCompletionContextWorkerAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, bool isExpanded, CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetRequiredLanguageService<CompletionService>(); var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); if (_snippetCompletionTriggeredIndirectly) { roslynTrigger = new CompletionTrigger(CompletionTriggerKind.Snippets); } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = documentOptions .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); if (_isDebuggerTextView) { options = options .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, options, cancellationToken).ConfigureAwait(false); ImmutableArray<VSCompletionItem> items; AsyncCompletionData.SuggestionItemOptions? suggestionItemOptions; var filterSet = new FilterSet(); if (completionList == null) { items = ImmutableArray<VSCompletionItem>.Empty; suggestionItemOptions = null; } else { var itemsBuilder = new ArrayBuilder<VSCompletionItem>(completionList.Items.Length); foreach (var roslynItem in completionList.Items) { cancellationToken.ThrowIfCancellationRequested(); var item = Convert(document, roslynItem, filterSet, triggerLocation); itemsBuilder.Add(item); } items = itemsBuilder.ToImmutableAndFree(); suggestionItemOptions = completionList.SuggestionModeItem != null ? new AsyncCompletionData.SuggestionItemOptions( completionList.SuggestionModeItem.DisplayText, completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) ? description : string.Empty) : null; // Store around the span this completion list applies to. We'll use this later // to pass this value in when we're committing a completion list item. // It's OK to overwrite this value when expanded items are requested. session.Properties[CompletionListSpan] = completionList.Span; // This is a code supporting original completion scenarios: // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) { session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; } var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); if (excludedCommitCharacters.Length > 0) { if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharactersBefore)) { excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); } session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; } } // We need to remember the trigger location for when a completion service claims expanded items are available // since the initial trigger we are able to get from IAsyncCompletionSession might not be the same (e.g. in projection scenarios) // so when they are requested via expander later, we can retrieve it. // Technically we should save the trigger location for each individual service that made such claim, but in reality only Roslyn's // completion service uses expander, so we can get away with not making such distinction. if (!isExpanded && expandItemsAvailable) { session.Properties[ExpandedItemTriggerLocation] = triggerLocation; } // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection : AsyncCompletionData.InitialSelectionHint.SoftSelection, filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task<object?> GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); if (item is null) throw new ArgumentNullException(nameof(item)); if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !item.Properties.TryGetProperty(TriggerLocation, out SnapshotPoint triggerLocation)) { return null; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) return null; var service = document.GetLanguageService<CompletionService>(); if (service == null) return null; var description = await service.GetDescriptionAsync(document, roslynItem, cancellationToken).ConfigureAwait(false); var context = new IntellisenseQuickInfoBuilderContext( document, ThreadingContext, _operationExecutor, _asyncListener, _streamingPresenter); var elements = IntelliSense.Helpers.BuildInteractiveTextElements(description.TaggedParts, context).ToArray(); if (elements.Length == 0) { return new ClassifiedTextElement(); } else if (elements.Length == 1) { return elements[0]; } else { return new ContainerElement(ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } } /// <summary> /// We'd like to cache VS Completion item directly to avoid allocation completely. However it holds references /// to transient objects, which would cause memory leak (among other potential issues) if cached. /// So as a compromise, we cache data that can be calculated from Roslyn completion item to avoid repeated /// calculation cost for cached Roslyn completion items. /// </summary> private readonly struct VSCompletionItemData { public VSCompletionItemData( string displayText, ImageElement icon, ImmutableArray<AsyncCompletionData.CompletionFilter> filters, int filterSetData, ImmutableArray<ImageElement> attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } public string DisplayText { get; } public ImageElement Icon { get; } public ImmutableArray<AsyncCompletionData.CompletionFilter> Filters { get; } /// <summary> /// This is the bit vector value from the FilterSet of this item. /// </summary> public int FilterSetData { get; } public ImmutableArray<ImageElement> AttributeIcons { get; } public string InsertionText { get; } } private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem, FilterSet filterSet, SnapshotPoint initialTriggerLocation) { VSCompletionItemData itemData; if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray<ImageElement>.Empty; itemData = new VSCompletionItemData( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox<VSCompletionItemData>(itemData)); } } var item = new VSCompletionItem( displayText: itemData.DisplayText, source: this, icon: itemData.Icon, filters: itemData.Filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: itemData.InsertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, automationText: roslynItem.AutomationText ?? roslynItem.DisplayText, attributeIcons: itemData.AttributeIcons); item.Properties.AddProperty(RoslynItem, roslynItem); item.Properties.AddProperty(TriggerLocation, initialTriggerLocation); return item; } private static ImmutableArray<char> GetExcludedCommitCharacters(ImmutableArray<RoslynCompletionItem> roslynItems) { var hashSet = new HashSet<char>(); foreach (var roslynItem in roslynItems) { foreach (var rule in roslynItem.Rules.FilterCharacterRules) { if (rule.Kind == CharacterSetModificationKind.Add) { foreach (var c in rule.Characters) { hashSet.Add(c); } } } } return hashSet.ToImmutableArray(); } internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { var startOfLine = text.Lines.GetLineFromPosition(questionPosition).Start; // First, skip all the whitespace. var current = startOfLine; while (current < questionPosition && char.IsWhiteSpace(text[current])) { current++; } if (current < questionPosition && syntaxFacts.IsIdentifierStartCharacter(text[current])) { current++; } else { return false; } while (current < questionPosition && syntaxFacts.IsIdentifierPartCharacter(text[current])) { current++; } return current == questionPosition; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Editor; using AsyncCompletionData = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem; using VSCompletionItem = Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data.CompletionItem; using VSUtilities = Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion { internal sealed class CompletionSource : ForegroundThreadAffinitizedObject, IAsyncExpandingCompletionSource { internal const string RoslynItem = nameof(RoslynItem); internal const string TriggerLocation = nameof(TriggerLocation); internal const string ExpandedItemTriggerLocation = nameof(ExpandedItemTriggerLocation); internal const string CompletionListSpan = nameof(CompletionListSpan); internal const string InsertionText = nameof(InsertionText); internal const string HasSuggestionItemOptions = nameof(HasSuggestionItemOptions); internal const string Description = nameof(Description); internal const string PotentialCommitCharacters = nameof(PotentialCommitCharacters); internal const string ExcludedCommitCharacters = nameof(ExcludedCommitCharacters); internal const string NonBlockingCompletion = nameof(NonBlockingCompletion); internal const string TypeImportCompletionEnabled = nameof(TypeImportCompletionEnabled); internal const string TargetTypeFilterExperimentEnabled = nameof(TargetTypeFilterExperimentEnabled); private static readonly ImmutableArray<ImageElement> s_WarningImageAttributeImagesArray = ImmutableArray.Create(new ImageElement(Glyph.CompletionWarning.GetImageId(), EditorFeaturesResources.Warning_image_element)); private static readonly EditorOptionKey<bool> NonBlockingCompletionEditorOption = new(NonBlockingCompletion); // Use CWT to cache data needed to create VSCompletionItem, so the table would be cleared when Roslyn completion item cache is cleared. private static readonly ConditionalWeakTable<RoslynCompletionItem, StrongBox<VSCompletionItemData>> s_roslynItemToVsItemData = new(); private readonly ITextView _textView; private readonly bool _isDebuggerTextView; private readonly ImmutableHashSet<string> _roles; private readonly Lazy<IStreamingFindUsagesPresenter> _streamingPresenter; private readonly VSUtilities.IUIThreadOperationExecutor _operationExecutor; private readonly IAsynchronousOperationListener _asyncListener; private bool _snippetCompletionTriggeredIndirectly; internal CompletionSource( ITextView textView, Lazy<IStreamingFindUsagesPresenter> streamingPresenter, IThreadingContext threadingContext, VSUtilities.IUIThreadOperationExecutor operationExecutor, IAsynchronousOperationListener asyncListener) : base(threadingContext) { _textView = textView; _streamingPresenter = streamingPresenter; _operationExecutor = operationExecutor; _asyncListener = asyncListener; _isDebuggerTextView = textView is IDebuggerTextView; _roles = textView.Roles.ToImmutableHashSet(); } public AsyncCompletionData.CompletionStartData InitializeCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, CancellationToken cancellationToken) { // We take sourceText from document to get a snapshot span. // We would like to be sure that nobody changes buffers at the same time. AssertIsForeground(); if (_textView.Selection.Mode == TextSelectionMode.Box) { // No completion with multiple selection return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } var service = document.GetLanguageService<CompletionService>(); if (service == null) { return AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; } // The Editor supports the option per textView. // There could be mixed desired behavior per textView and even per same completion session. // The right fix would be to send this information as a result of the method. // Then, the Editor would choose the right behavior for mixed cases. _textView.Options.GlobalOptions.SetOptionValue(NonBlockingCompletionEditorOption, !document.Project.Solution.Workspace.Options.GetOption(CompletionOptions.BlockForCompletionItems2, service.Language)); // In case of calls with multiple completion services for the same view (e.g. TypeScript and C#), those completion services must not be called simultaneously for the same session. // Therefore, in each completion session we use a list of commit character for a specific completion service and a specific content type. _textView.Properties[PotentialCommitCharacters] = service.GetRules().DefaultCommitCharacters; // Reset a flag which means a snippet triggered by ? + Tab. // Set it later if met the condition. _snippetCompletionTriggeredIndirectly = false; CheckForExperimentStatus(_textView, document); var sourceText = document.GetTextSynchronously(cancellationToken); return ShouldTriggerCompletion(trigger, triggerLocation, sourceText, document, service) ? new AsyncCompletionData.CompletionStartData( participation: AsyncCompletionData.CompletionParticipation.ProvidesItems, applicableToSpan: new SnapshotSpan( triggerLocation.Snapshot, service.GetDefaultCompletionListSpan(sourceText, triggerLocation.Position).ToSpan())) : AsyncCompletionData.CompletionStartData.DoesNotParticipateInCompletion; // For telemetry reporting purpose static void CheckForExperimentStatus(ITextView textView, Document document) { var options = document.Project.Solution.Options; textView.Properties[TargetTypeFilterExperimentEnabled] = options.GetOption(CompletionOptions.TargetTypedCompletionFilterFeatureFlag); var importCompletionOptionValue = options.GetOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, document.Project.Language); var importCompletionExperimentValue = options.GetOption(CompletionOptions.TypeImportCompletionFeatureFlag); var isTypeImportEnababled = importCompletionOptionValue == true || (importCompletionOptionValue == null && importCompletionExperimentValue); textView.Properties[TypeImportCompletionEnabled] = isTypeImportEnababled; } } private bool ShouldTriggerCompletion( AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SourceText sourceText, Document document, CompletionService completionService) { // The trigger reason guarantees that user wants a completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Invoke || trigger.Reason == AsyncCompletionData.CompletionTriggerReason.InvokeAndCommitIfUnique) { return true; } // Enter does not trigger completion. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\n') { return false; } //The user may be trying to invoke snippets through question-tab. // We may provide a completion after that. // Otherwise, tab should not be a completion trigger. if (trigger.Reason == AsyncCompletionData.CompletionTriggerReason.Insertion && trigger.Character == '\t') { return TryInvokeSnippetCompletion(completionService, document, sourceText, triggerLocation.Position); } var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); // The completion service decides that user may want a completion. if (completionService.ShouldTriggerCompletion(document.Project, sourceText, triggerLocation.Position, roslynTrigger)) { return true; } return false; } private bool TryInvokeSnippetCompletion( CompletionService completionService, Document document, SourceText text, int caretPoint) { var rules = completionService.GetRules(); // Do not invoke snippet if the corresponding rule is not set in options. if (rules.SnippetsRule != SnippetsRule.IncludeAfterTypingIdentifierQuestionTab) { return false; } var syntaxFactsOpt = document.GetLanguageService<ISyntaxFactsService>(); // Snippets are included if the user types: <quesiton><tab> // If at least one condition for snippets do not hold, bail out. if (syntaxFactsOpt == null || caretPoint < 3 || text[caretPoint - 2] != '?' || !QuestionMarkIsPrecededByIdentifierAndWhitespace(text, caretPoint - 2, syntaxFactsOpt)) { return false; } // Because <question><tab> is actually a command to bring up snippets, // we delete the last <question> that was typed. var textChange = new TextChange(TextSpan.FromBounds(caretPoint - 2, caretPoint), string.Empty); document.Project.Solution.Workspace.ApplyTextChanges(document.Id, textChange, CancellationToken.None); _snippetCompletionTriggeredIndirectly = true; return true; } public Task<AsyncCompletionData.CompletionContext> GetCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); return GetCompletionContextWorkerAsync(session, trigger, triggerLocation, isExpanded: false, cancellationToken); } public async Task<AsyncCompletionData.CompletionContext> GetExpandedCompletionContextAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionExpander expander, AsyncCompletionData.CompletionTrigger intialTrigger, SnapshotSpan applicableToSpan, CancellationToken cancellationToken) { // We only want to provide expanded items for Roslyn's expander. if ((object)expander == FilterSet.Expander && session.Properties.TryGetProperty(ExpandedItemTriggerLocation, out SnapshotPoint initialTriggerLocation)) { return await GetCompletionContextWorkerAsync(session, intialTrigger, initialTriggerLocation, isExpanded: true, cancellationToken).ConfigureAwait(false); } return AsyncCompletionData.CompletionContext.Empty; } private async Task<AsyncCompletionData.CompletionContext> GetCompletionContextWorkerAsync( IAsyncCompletionSession session, AsyncCompletionData.CompletionTrigger trigger, SnapshotPoint triggerLocation, bool isExpanded, CancellationToken cancellationToken) { var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) { return AsyncCompletionData.CompletionContext.Empty; } var completionService = document.GetRequiredLanguageService<CompletionService>(); var roslynTrigger = Helpers.GetRoslynTrigger(trigger, triggerLocation); if (_snippetCompletionTriggeredIndirectly) { roslynTrigger = new CompletionTrigger(CompletionTriggerKind.Snippets); } var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var options = documentOptions .WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, isExpanded); if (_isDebuggerTextView) { options = options .WithChangedOption(CompletionControllerOptions.FilterOutOfScopeLocals, false) .WithChangedOption(CompletionControllerOptions.ShowXmlDocCommentCompletion, false); } var (completionList, expandItemsAvailable) = await completionService.GetCompletionsInternalAsync( document, triggerLocation, roslynTrigger, _roles, options, cancellationToken).ConfigureAwait(false); ImmutableArray<VSCompletionItem> items; AsyncCompletionData.SuggestionItemOptions? suggestionItemOptions; var filterSet = new FilterSet(); if (completionList == null) { items = ImmutableArray<VSCompletionItem>.Empty; suggestionItemOptions = null; } else { var itemsBuilder = new ArrayBuilder<VSCompletionItem>(completionList.Items.Length); foreach (var roslynItem in completionList.Items) { cancellationToken.ThrowIfCancellationRequested(); var item = Convert(document, roslynItem, filterSet, triggerLocation); itemsBuilder.Add(item); } items = itemsBuilder.ToImmutableAndFree(); suggestionItemOptions = completionList.SuggestionModeItem != null ? new AsyncCompletionData.SuggestionItemOptions( completionList.SuggestionModeItem.DisplayText, completionList.SuggestionModeItem.Properties.TryGetValue(Description, out var description) ? description : string.Empty) : null; // Store around the span this completion list applies to. We'll use this later // to pass this value in when we're committing a completion list item. // It's OK to overwrite this value when expanded items are requested. session.Properties[CompletionListSpan] = completionList.Span; // This is a code supporting original completion scenarios: // Controller.Session_ComputeModel: if completionList.SuggestionModeItem != null, then suggestionMode = true // If there are suggestionItemOptions, then later HandleNormalFiltering should set selection to SoftSelection. if (!session.Properties.TryGetProperty(HasSuggestionItemOptions, out bool hasSuggestionItemOptionsBefore) || !hasSuggestionItemOptionsBefore) { session.Properties[HasSuggestionItemOptions] = suggestionItemOptions != null; } var excludedCommitCharacters = GetExcludedCommitCharacters(completionList.Items); if (excludedCommitCharacters.Length > 0) { if (session.Properties.TryGetProperty(ExcludedCommitCharacters, out ImmutableArray<char> excludedCommitCharactersBefore)) { excludedCommitCharacters = excludedCommitCharacters.Union(excludedCommitCharactersBefore).ToImmutableArray(); } session.Properties[ExcludedCommitCharacters] = excludedCommitCharacters; } } // We need to remember the trigger location for when a completion service claims expanded items are available // since the initial trigger we are able to get from IAsyncCompletionSession might not be the same (e.g. in projection scenarios) // so when they are requested via expander later, we can retrieve it. // Technically we should save the trigger location for each individual service that made such claim, but in reality only Roslyn's // completion service uses expander, so we can get away with not making such distinction. if (!isExpanded && expandItemsAvailable) { session.Properties[ExpandedItemTriggerLocation] = triggerLocation; } // It's possible that some providers can provide expanded items, in which case we will need to show expander as unselected. return new AsyncCompletionData.CompletionContext( items, suggestionItemOptions, suggestionItemOptions == null ? AsyncCompletionData.InitialSelectionHint.RegularSelection : AsyncCompletionData.InitialSelectionHint.SoftSelection, filterSet.GetFilterStatesInSet(addUnselectedExpander: expandItemsAvailable)); } public async Task<object?> GetDescriptionAsync(IAsyncCompletionSession session, VSCompletionItem item, CancellationToken cancellationToken) { if (session is null) throw new ArgumentNullException(nameof(session)); if (item is null) throw new ArgumentNullException(nameof(item)); if (!item.Properties.TryGetProperty(RoslynItem, out RoslynCompletionItem roslynItem) || !item.Properties.TryGetProperty(TriggerLocation, out SnapshotPoint triggerLocation)) { return null; } var document = triggerLocation.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document == null) return null; var service = document.GetLanguageService<CompletionService>(); if (service == null) return null; var description = await service.GetDescriptionAsync(document, roslynItem, cancellationToken).ConfigureAwait(false); var context = new IntellisenseQuickInfoBuilderContext( document, ThreadingContext, _operationExecutor, _asyncListener, _streamingPresenter); var elements = IntelliSense.Helpers.BuildInteractiveTextElements(description.TaggedParts, context).ToArray(); if (elements.Length == 0) { return new ClassifiedTextElement(); } else if (elements.Length == 1) { return elements[0]; } else { return new ContainerElement(ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding, elements); } } /// <summary> /// We'd like to cache VS Completion item directly to avoid allocation completely. However it holds references /// to transient objects, which would cause memory leak (among other potential issues) if cached. /// So as a compromise, we cache data that can be calculated from Roslyn completion item to avoid repeated /// calculation cost for cached Roslyn completion items. /// </summary> private readonly struct VSCompletionItemData { public VSCompletionItemData( string displayText, ImageElement icon, ImmutableArray<AsyncCompletionData.CompletionFilter> filters, int filterSetData, ImmutableArray<ImageElement> attributeIcons, string insertionText) { DisplayText = displayText; Icon = icon; Filters = filters; FilterSetData = filterSetData; AttributeIcons = attributeIcons; InsertionText = insertionText; } public string DisplayText { get; } public ImageElement Icon { get; } public ImmutableArray<AsyncCompletionData.CompletionFilter> Filters { get; } /// <summary> /// This is the bit vector value from the FilterSet of this item. /// </summary> public int FilterSetData { get; } public ImmutableArray<ImageElement> AttributeIcons { get; } public string InsertionText { get; } } private VSCompletionItem Convert( Document document, RoslynCompletionItem roslynItem, FilterSet filterSet, SnapshotPoint initialTriggerLocation) { VSCompletionItemData itemData; if (roslynItem.Flags.IsCached() && s_roslynItemToVsItemData.TryGetValue(roslynItem, out var boxedItemData)) { itemData = boxedItemData.Value; filterSet.CombineData(itemData.FilterSetData); } else { var imageId = roslynItem.Tags.GetFirstGlyph().GetImageId(); var (filters, filterSetData) = filterSet.GetFiltersAndAddToSet(roslynItem); // roslynItem generated by providers can contain an insertionText in a property bag. // We will not use it but other providers may need it. // We actually will calculate the insertion text once again when called TryCommit. if (!roslynItem.Properties.TryGetValue(InsertionText, out var insertionText)) { insertionText = roslynItem.DisplayText; } var supportedPlatforms = SymbolCompletionItem.GetSupportedPlatforms(roslynItem, document.Project.Solution); var attributeImages = supportedPlatforms != null ? s_WarningImageAttributeImagesArray : ImmutableArray<ImageElement>.Empty; itemData = new VSCompletionItemData( displayText: roslynItem.GetEntireDisplayText(), icon: new ImageElement(new ImageId(imageId.Guid, imageId.Id), roslynItem.DisplayText), filters: filters, filterSetData: filterSetData, attributeIcons: attributeImages, insertionText: insertionText); // It doesn't make sense to cache VS item data for those Roslyn items created from scratch for each session, // since CWT uses object identity for comparison. if (roslynItem.Flags.IsCached()) { s_roslynItemToVsItemData.Add(roslynItem, new StrongBox<VSCompletionItemData>(itemData)); } } var item = new VSCompletionItem( displayText: itemData.DisplayText, source: this, icon: itemData.Icon, filters: itemData.Filters, suffix: roslynItem.InlineDescription, // InlineDescription will be right-aligned in the selection popup insertText: itemData.InsertionText, sortText: roslynItem.SortText, filterText: roslynItem.FilterText, automationText: roslynItem.AutomationText ?? roslynItem.DisplayText, attributeIcons: itemData.AttributeIcons); item.Properties.AddProperty(RoslynItem, roslynItem); item.Properties.AddProperty(TriggerLocation, initialTriggerLocation); return item; } private static ImmutableArray<char> GetExcludedCommitCharacters(ImmutableArray<RoslynCompletionItem> roslynItems) { var hashSet = new HashSet<char>(); foreach (var roslynItem in roslynItems) { foreach (var rule in roslynItem.Rules.FilterCharacterRules) { if (rule.Kind == CharacterSetModificationKind.Add) { foreach (var c in rule.Characters) { hashSet.Add(c); } } } } return hashSet.ToImmutableArray(); } internal static bool QuestionMarkIsPrecededByIdentifierAndWhitespace( SourceText text, int questionPosition, ISyntaxFactsService syntaxFacts) { var startOfLine = text.Lines.GetLineFromPosition(questionPosition).Start; // First, skip all the whitespace. var current = startOfLine; while (current < questionPosition && char.IsWhiteSpace(text[current])) { current++; } if (current < questionPosition && syntaxFacts.IsIdentifierStartCharacter(text[current])) { current++; } else { return false; } while (current < questionPosition && syntaxFacts.IsIdentifierPartCharacter(text[current])) { current++; } return current == questionPosition; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/VisualBasicTest/Diagnostics/AddImport/AddImportTests_NuGet.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Packaging Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Moq Imports ProviderData = System.Tuple(Of Microsoft.CodeAnalysis.Packaging.IPackageInstallerService, Microsoft.CodeAnalysis.SymbolSearch.ISymbolSearchService) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImport <Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Class AddImportNuGetTests Inherits AbstractAddImportTests Private Const NugetOrgSource = "nuget.org" Private Shared ReadOnly NuGetPackageSources As ImmutableArray(Of PackageSource) = ImmutableArray.Create(New PackageSource(NugetOrgSource, "http://nuget.org")) Protected Overrides Sub InitializeWorkspace(workspace As TestWorkspace, parameters As TestParameters) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options. WithChangedOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic, True). WithChangedOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic, True))) End Sub Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) ' This is used by inherited tests to ensure the properties of diagnostic analyzers are correct. It's not ' needed by the tests in this class, but can't throw an exception. Return (Nothing, Nothing) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, parameters As TestParameters) As (DiagnosticAnalyzer, CodeFixProvider) Dim data = DirectCast(parameters.fixProviderData, ProviderData) Return (Nothing, New VisualBasicAddImportCodeFixProvider(data.Item1, data.Item2)) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact> Public Async Function TestSearchPackageSingleName() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestSearchPackageMultipleNames() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NS1.NS2 Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestFailedInstallDoesNotChangeFile() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(False) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestMissingIfPackageAlreadyInstalled() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestMissingInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object))) End Function <Fact> Public Async Function TestOptionsOffered() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "2.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0", "2.0")) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Dim data = New ProviderData(installerServiceMock.Object, packageServiceMock.Object) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "1.0"), parameters:=New TestParameters(fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "2.0"), parameters:=New TestParameters(index:=1, fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", FeaturesResources.Find_and_install_latest_version, parameters:=New TestParameters(index:=2, fixProviderData:=data)) End Function <Fact> Public Async Function TestInstallGetsCalledNoVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function <Fact> Public Async Function TestInstallGetsCalledWithVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0")) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", "1.0", It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function Private Shared Function CreateSearchResult(packageName As String, typeName As String, nameParts As ImmutableArray(Of String)) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return CreateSearchResult(New PackageWithTypeResult( packageName:=packageName, rank:=0, typeName:=typeName, version:=Nothing, containingNamespaceNames:=nameParts)) End Function Private Shared Function CreateSearchResult(ParamArray results As PackageWithTypeResult()) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return ValueTaskFactory.FromResult(ImmutableArray.Create(results)) End Function Private Shared Function CreateNameParts(ParamArray parts As String()) As ImmutableArray(Of String) Return parts.ToImmutableArray() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Packaging Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.SymbolSearch Imports Microsoft.CodeAnalysis.VisualBasic.AddImport Imports Moq Imports ProviderData = System.Tuple(Of Microsoft.CodeAnalysis.Packaging.IPackageInstallerService, Microsoft.CodeAnalysis.SymbolSearch.ISymbolSearchService) Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeActions.AddImport <Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Class AddImportNuGetTests Inherits AbstractAddImportTests Private Const NugetOrgSource = "nuget.org" Private Shared ReadOnly NuGetPackageSources As ImmutableArray(Of PackageSource) = ImmutableArray.Create(New PackageSource(NugetOrgSource, "http://nuget.org")) Protected Overrides Sub InitializeWorkspace(workspace As TestWorkspace, parameters As TestParameters) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options. WithChangedOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.VisualBasic, True). WithChangedOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.VisualBasic, True))) End Sub Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) ' This is used by inherited tests to ensure the properties of diagnostic analyzers are correct. It's not ' needed by the tests in this class, but can't throw an exception. Return (Nothing, Nothing) End Function Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace, parameters As TestParameters) As (DiagnosticAnalyzer, CodeFixProvider) Dim data = DirectCast(parameters.fixProviderData, ProviderData) Return (Nothing, New VisualBasicAddImportCodeFixProvider(data.Item1, data.Item2)) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact> Public Async Function TestSearchPackageSingleName() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestSearchPackageMultipleNames() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NS1.NS2 Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestFailedInstallDoesNotChangeFile() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", It.IsAny(Of String), It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(False) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) End Function <Fact> Public Async Function TestMissingIfPackageAlreadyInstalled() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.IsInstalled(It.IsAny(Of Workspace)(), It.IsAny(Of ProjectId)(), "NuGetPackage")). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Await TestMissingInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", New TestParameters(fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object))) End Function <Fact> Public Async Function TestOptionsOffered() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "2.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0", "2.0")) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))) Dim data = New ProviderData(installerServiceMock.Object, packageServiceMock.Object) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "1.0"), parameters:=New TestParameters(fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", String.Format(FeaturesResources.Use_local_version_0, "2.0"), parameters:=New TestParameters(index:=1, fixProviderData:=data)) Await TestSmartTagTextAsync( " Class C Dim n As [|NuGetType|] End Class", FeaturesResources.Find_and_install_latest_version, parameters:=New TestParameters(index:=2, fixProviderData:=data)) End Function <Fact> Public Async Function TestInstallGetsCalledNoVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetInstalledVersions("NuGetPackage")).Returns(ImmutableArray(Of String).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", Nothing, It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function <Fact> Public Async Function TestInstallGetsCalledWithVersion() As Task Dim installerServiceMock = New Mock(Of IPackageInstallerService)(MockBehavior.Strict) installerServiceMock.Setup(Function(i) i.IsEnabled(It.IsAny(Of ProjectId))).Returns(True) installerServiceMock.Setup(Function(i) i.IsInstalled(It.IsAny(Of Workspace), It.IsAny(Of ProjectId), "NuGetPackage")).Returns(False) installerServiceMock.Setup(Function(i) i.GetProjectsWithInstalledPackage(It.IsAny(Of Solution), "NuGetPackage", "1.0")).Returns(ImmutableArray(Of Project).Empty) installerServiceMock.Setup(Function(i) i.TryGetPackageSources()).Returns(NuGetPackageSources) installerServiceMock.Setup(Function(s) s.GetInstalledVersions("NuGetPackage")). Returns(ImmutableArray.Create("1.0")) installerServiceMock.Setup(Function(s) s.TryInstallPackage(It.IsAny(Of Workspace), It.IsAny(Of DocumentId), It.IsAny(Of String), "NuGetPackage", "1.0", It.IsAny(Of Boolean), It.IsAny(Of IProgressTracker)(), It.IsAny(Of CancellationToken))). Returns(True) Dim packageServiceMock = New Mock(Of ISymbolSearchService)(MockBehavior.Strict) packageServiceMock.Setup(Function(s) s.FindReferenceAssembliesWithTypeAsync("NuGetType", 0, It.IsAny(Of CancellationToken))). Returns(Function() ValueTaskFactory.FromResult(ImmutableArray(Of ReferenceAssemblyWithTypeResult).Empty)) packageServiceMock.Setup(Function(s) s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny(Of CancellationToken)())). Returns(Function() CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))) Await TestInRegularAndScriptAsync( " Class C Dim n As [|NuGetType|] End Class", " Imports NuGetNamespace Class C Dim n As NuGetType End Class", fixProviderData:=New ProviderData(installerServiceMock.Object, packageServiceMock.Object)) installerServiceMock.Verify() End Function Private Shared Function CreateSearchResult(packageName As String, typeName As String, nameParts As ImmutableArray(Of String)) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return CreateSearchResult(New PackageWithTypeResult( packageName:=packageName, rank:=0, typeName:=typeName, version:=Nothing, containingNamespaceNames:=nameParts)) End Function Private Shared Function CreateSearchResult(ParamArray results As PackageWithTypeResult()) As ValueTask(Of ImmutableArray(Of PackageWithTypeResult)) Return ValueTaskFactory.FromResult(ImmutableArray.Create(results)) End Function Private Shared Function CreateNameParts(ParamArray parts As String()) As ImmutableArray(Of String) Return parts.ToImmutableArray() End Function End Class End Namespace
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Compilers/VisualBasic/Test/Syntax/Parser/InterpolatedStringParsingTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Roslyn.Test.Utilities Public Class InterpolatedStringParsingTests Inherits BasicTestBase <Fact> Public Sub EmptyString() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($"""") End Sub End Module") End Sub <Fact> Public Sub NoInterpolations() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, World!"") End Sub End Module") End Sub <Fact> Public Sub OnlyInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""Hello, World!""}"") End Sub End Module") End Sub <Fact> Public Sub SimpleInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {name}!"") End Sub End Module") End Sub <Fact> Public Sub ParenthesizedInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {(firstName & lastName)}!"") End Sub End Module") End Sub <Fact> Public Sub ComplexInterpolation_QueryExpression() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {From name In names Select name.Length}!"") End Sub End Module") End Sub <Fact> Public Sub EscapedBraces() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{{ {x}, {y} }}"") End Sub End Module") End Sub <Fact> Public Sub EmbeddedBracesWorkaround() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""{""}{x}, {y}{""}""}"") End Sub End Module") End Sub <Fact> Public Sub AlignmentClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine(""Header 1 | Header 2 | Header 3"") Console.WriteLine($""{items(0),9}|{items(1),9}|{items(2),9}"") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue:C02}."") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause_WithTwoColons() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue::C02}."") End Sub End Module") End Sub <Fact> Public Sub AlignmentClauseAndFormatClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue,10:C02}."") End Sub End Module") End Sub <Fact> Public Sub MultilineText() ParseAndVerify( "Module Program Sub Main() Console.WriteLine( $""Name: {name} Age: {age} ====="") End Sub End Module") End Sub <Fact> Public Sub ERR_InterpolationFormatWhitespace() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC37249: Format specifier may not contain trailing whitespace. Console.WriteLine($"Hello, {EventArgs.Empty:C02 }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAfterOpenBraceAndBeforeCloseBraceWithoutFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, { EventArgs.Empty }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, { ~ BC30201: Expression expected. Console.WriteLine($"Hello, { ~ BC30370: '}' expected. Console.WriteLine($"Hello, { ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty,-10 :C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30201: Expression expected. :C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. :C02}!") ~ BC30648: String constants must end with a double quote. :C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClauseCommaToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty, -10:C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30204: Integer constant expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30035: Syntax error. -10:C02}!") ~ BC30201: Expression expected. -10:C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. -10:C02}!") ~ BC30648: String constants must end with a double quote. -10:C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClauseColonToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty: C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30201: Expression expected. C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. C02}!") ~ BC30648: String constants must end with a double quote. C02}!") ~~~ </expected>) End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($) End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace() Parse( "Module Program Sub Main() Console.WriteLine($""{"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,5:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace() Parse( "Module Program Sub Main() Console.WriteLine($""}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($ End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{For"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{`"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{` End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 + End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1, End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,& End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5 End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByAColon() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(:C02}"") Console.WriteLine($""{CStr(1:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByATwoColons() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(::C02}"") Console.WriteLine($""{CStr(1::C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_ExtraCloseBraceFollowingInterpolationWithNoFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""{1}}"") End Sub End Module") End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_1() Parse( "Module Program Sub Main() Dim x = $""{ " + vbCr + vbCr + "1 }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30201: Expression expected. Dim x = $"{ ~ BC30370: '}' expected. Dim x = $"{ ~ BC30801: Labels that are numbers must be followed by colons. 1 ~~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_2() Parse( "Module Program Sub Main() Dim x = $""{ 1 " + vbCr + vbCr + " }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30370: '}' expected. Dim x = $"{ 1 ~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Roslyn.Test.Utilities Public Class InterpolatedStringParsingTests Inherits BasicTestBase <Fact> Public Sub EmptyString() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($"""") End Sub End Module") End Sub <Fact> Public Sub NoInterpolations() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, World!"") End Sub End Module") End Sub <Fact> Public Sub OnlyInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""Hello, World!""}"") End Sub End Module") End Sub <Fact> Public Sub SimpleInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {name}!"") End Sub End Module") End Sub <Fact> Public Sub ParenthesizedInterpolation() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {(firstName & lastName)}!"") End Sub End Module") End Sub <Fact> Public Sub ComplexInterpolation_QueryExpression() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""Hello, {From name In names Select name.Length}!"") End Sub End Module") End Sub <Fact> Public Sub EscapedBraces() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{{ {x}, {y} }}"") End Sub End Module") End Sub <Fact> Public Sub EmbeddedBracesWorkaround() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""{""{""}{x}, {y}{""}""}"") End Sub End Module") End Sub <Fact> Public Sub AlignmentClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine(""Header 1 | Header 2 | Header 3"") Console.WriteLine($""{items(0),9}|{items(1),9}|{items(2),9}"") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue:C02}."") End Sub End Module") End Sub <Fact> Public Sub FormatStringClause_WithTwoColons() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue::C02}."") End Sub End Module") End Sub <Fact> Public Sub AlignmentClauseAndFormatClause() ParseAndVerify( "Module Program Sub Main() Console.WriteLine($""You owe: {balanceDue,10:C02}."") End Sub End Module") End Sub <Fact> Public Sub MultilineText() ParseAndVerify( "Module Program Sub Main() Console.WriteLine( $""Name: {name} Age: {age} ====="") End Sub End Module") End Sub <Fact> Public Sub ERR_InterpolationFormatWhitespace() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC37249: Format specifier may not contain trailing whitespace. Console.WriteLine($"Hello, {EventArgs.Empty:C02 }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAfterOpenBraceAndBeforeCloseBraceWithoutFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, { EventArgs.Empty }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, { ~ BC30201: Expression expected. Console.WriteLine($"Hello, { ~ BC30370: '}' expected. Console.WriteLine($"Hello, { ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty,-10 :C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty,-10 ~ BC30201: Expression expected. :C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. :C02}!") ~ BC30648: String constants must end with a double quote. :C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterAlignmentClauseCommaToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty, -10:C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30204: Integer constant expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty, ~ BC30035: Syntax error. -10:C02}!") ~ BC30201: Expression expected. -10:C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. -10:C02}!") ~ BC30648: String constants must end with a double quote. -10:C02}!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty:C02 }!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty:C02 ~ BC30648: String constants must end with a double quote. }!") ~~~ </expected>) End Sub <Fact> Public Sub Error_NewLineAfterFormatClauseColonToken() Parse( "Module Program Sub Main() Console.WriteLine($""Hello, {EventArgs.Empty: C02}!"") End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30198: ')' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30370: '}' expected. Console.WriteLine($"Hello, {EventArgs.Empty: ~ BC30201: Expression expected. C02}!") ~ BC30800: Method arguments must be enclosed in parentheses. C02}!") ~ BC30648: String constants must end with a double quote. C02}!") ~~~ </expected>) End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($) End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote() Parse( "Module Program Sub Main() Console.WriteLine($"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace() Parse( "Module Program Sub Main() Console.WriteLine($""{"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionWithAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,5:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpressionAndAlignmentAndFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{,:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace() Parse( "Module Program Sub Main() Console.WriteLine($""}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_DollarSignMissingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($ End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingClosingDoubleQuote_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingCloseBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{`}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingOpenBrace_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""}"" End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{For"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{`"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 +"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,&"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5:"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionKeyword_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{For End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_NonExpressionCharacter_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{` End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{(1 + End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1, End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_BadAlignment_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,& End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_MissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentWithMissingFormatString_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1,5: End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_AlignmentAndFormatStringOutOfOrder_InUnclosedInterpolation_NestedInIncompleteExpression() Parse( "Module Program Sub Main() Console.WriteLine($""{1:C02,-5 End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByAColon() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(:C02}"") Console.WriteLine($""{CStr(1:C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_IncompleteExpression_FollowedByATwoColons() Parse( "Module Program Sub Main() Console.WriteLine($""{CStr(::C02}"") Console.WriteLine($""{CStr(1::C02}"") End Sub End Module") End Sub <Fact> Public Sub ErrorRecovery_ExtraCloseBraceFollowingInterpolationWithNoFormatClause() Parse( "Module Program Sub Main() Console.WriteLine($""{1}}"") End Sub End Module") End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_1() Parse( "Module Program Sub Main() Dim x = $""{ " + vbCr + vbCr + "1 }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30201: Expression expected. Dim x = $"{ ~ BC30370: '}' expected. Dim x = $"{ ~ BC30801: Labels that are numbers must be followed by colons. 1 ~~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub <Fact, WorkItem(6341, "https://github.com/dotnet/roslyn/issues/6341")> Public Sub LineBreakInInterpolation_2() Parse( "Module Program Sub Main() Dim x = $""{ 1 " + vbCr + vbCr + " }"" End Sub End Module" ).AssertTheseDiagnostics( <expected> BC30625: 'Module' statement must end with a matching 'End Module'. Module Program ~~~~~~~~~~~~~~ BC30026: 'End Sub' expected. Sub Main() ~~~~~~~~~~ BC30370: '}' expected. Dim x = $"{ 1 ~ BC30648: String constants must end with a double quote. }" ~~ </expected>) End Sub End Class
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/EmbeddedLanguages/RegularExpressions/CSharpRegexParserTests_BasicTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // These tests were created by trying to enumerate all codepaths in the lexer/parser. public partial class CSharpRegexParserTests { [Fact] public void TestEmpty() { Test(@"""""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[0..0)"" Text="""" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOneWhitespace_IgnorePatternWhitespace() { Test(@""" """, @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text="" "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestTwoWhitespace_IgnorePatternWhitespace() { Test(@""" """, @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text="" "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestEmptyParenComment() { Test(@"""(?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?#)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleParenComment() { Test(@"""(?# )""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?# )</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?# )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnterminatedParenComment1() { Test(@"""(?#""", $@"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[9..12)"" Text=""(?#"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?#"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnterminatedParenComment2() { Test(@"""(?# """, $@"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?# </CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[9..13)"" Text=""(?# "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?# "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestMultipleComments1() { Test(@"""(?#)(?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?#)(?#)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestMultipleComments2() { Test(@"""(?#)(?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?#)(?#)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestMultipleComments3() { Test(@"""(?#) (?#)""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </TextToken> </Text> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?#) (?#)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestMultipleComments4() { Test(@"""(?#) (?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?#) (?#)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass1() { Test(@"@""[a\p{Lu}(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[a\p{Lu}(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass2() { Test(@"@""[a\0(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a\0(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass3() { Test(@"@""[a\a(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>a</TextToken> </SimpleEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a\a(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass4() { Test(@"@""[a\x00(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""[a\x00(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass5() { Test(@"@""[a\u0000(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[a\u0000(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass6() { Test(@"@""[a\](?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>]</TextToken> </SimpleEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a\](?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenQuestion1() { Test(@"""(?""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""(?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenQuestion2() { Test(@"""(?""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""(?"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestOpenQuestion3() { Test(@"""(? """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(? "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenQuestion4() { Test(@"""(? """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(? "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestSimpleOptionsNode1() { Test(@"""(?i)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?i)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleOptionsNode2() { Test(@"""(?im)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>im</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?im)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleOptionsNode3() { Test(@"""(?im-x)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>im-x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?im-x)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleOptionsNode4() { Test(@"""(?im-x+n)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>im-x+n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?im-x+n)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesNotChangeWhitespaceScanning() { Test(@"""(?i) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?i) "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesChangeWhitespaceScanning() { Test(@"""(?x) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?x) "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesChangeWhitespaceScanning2() { Test(@""" (?x) """, @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text="" (?x) "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesChangeWhitespaceScanning3() { Test(@""" (?-x) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text="" (?-x) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestOptionRestoredWhenGroupPops() { Test(@""" ( (?-x) ) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <SimpleOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..20)"" Text="" ( (?-x) ) "" /> <Capture Name=""1"" Span=""[10..19)"" Text=""( (?-x) )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedOptionGroup1() { Test(@""" (?-x:) """, @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text="" (?-x:) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedOptionGroup2() { Test(@""" (?-x: ) """, @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text="" (?-x: ) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedOptionGroup3() { Test(@""" (?-x: (?+x: ) ) """, @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>+x</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </NestedOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..26)"" Text="" (?-x: (?+x: ) ) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncompleteOptionsGroup1() { Test(@"""(?-x""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?-x"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncompleteOptionsGroup2() { Test(@"""(?-x """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?-x "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncorrectOptionsGroup3() { Test(@"""(?-x :""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> :</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?-x :"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncorrectOptionsGroup4() { Test(@"""(?-x )""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[14..15)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?-x )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncorrectOptionsGroup5() { Test(@"""(?-x :)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> :</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[15..16)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?-x :)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCloseParen() { Test(@""")""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[9..10)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text="")"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSingleChar() { Test(@"""a""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""a"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTwoCharsChar() { Test(@"""ab""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>ab</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""ab"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifier() { Test(@"""a*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuestionQuantifier() { Test(@"""a*?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a*?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifier() { Test(@"""a+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuestionQuantifier() { Test(@"""a+?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a+?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifier() { Test(@"""a?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuestionQuantifier() { Test(@"""a??""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a??"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEmptySimpleGroup() { Test(@"""()""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""()"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestGroupWithSingleElement() { Test(@"""(a)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(a)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestGroupWithMissingCloseParen() { Test(@"""(""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[10..10)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""("" /> <Capture Name=""1"" Span=""[9..10)"" Text=""("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestGroupWithElementWithMissingCloseParen() { Test(@"""(a""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""(a"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""(a"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void JustBar() { Test(@"""|""", @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""|"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void SpaceBar() { Test(@""" |""", @"<Tree> <CompilationUnit> <Alternation> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text="" |"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void BarSpace() { Test(@"""| """, @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""| "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void SpaceBarSpace() { Test(@""" | """, @"<Tree> <CompilationUnit> <Alternation> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text="" | "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void JustBar_IgnoreWhitespace() { Test(@"""|""", @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""|"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void SpaceBar_IgnoreWhitespace() { Test(@""" |""", @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text="" |"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void BarSpace_IgnoreWhitespace() { Test(@"""| """, @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""| "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void SpaceBarSpace_IgnoreWhitespace() { Test(@""" | """, @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>|</BarToken> <Sequence /> </Alternation> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text="" | "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void DoubleBar() { Test(@"""||""", @"<Tree> <CompilationUnit> <Alternation> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""||"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void BarInGroup() { Test(@"""(|)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(|)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(|)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestExactNumericQuantifier() { Test(@"""a{0}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a{0}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenRangeNumericQuantifier() { Test(@"""a{0,}""", @"<Tree> <CompilationUnit> <Sequence> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0,}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestClosedRangeNumericQuantifier() { Test(@"""a{0,1}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0,1}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLargeExactRangeNumericQuantifier1() { Test(@"""a{2147483647}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2147483647"">2147483647</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""a{2147483647}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false, allowOutOfMemory: true); } [Fact] public void TestLargeExactRangeNumericQuantifier2() { Test(@"""a{2147483648}""", $@"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[11..21)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""a{{2147483648}}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestLargeOpenRangeNumericQuantifier1() { Test(@"""a{2147483647,}""", @"<Tree> <CompilationUnit> <Sequence> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2147483647"">2147483647</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..23)"" Text=""a{2147483647,}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false, allowOutOfMemory: true); } [Fact] public void TestLargeOpenRangeNumericQuantifier2() { Test(@"""a{2147483648,}""", $@"<Tree> <CompilationUnit> <Sequence> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[11..21)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..23)"" Text=""a{{2147483648,}}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestLargeClosedRangeNumericQuantifier1() { Test(@"""a{0,2147483647}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2147483647"">2147483647</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..24)"" Text=""a{0,2147483647}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestLargeClosedRangeNumericQuantifier2() { Test(@"""a{0,2147483648}""", $@"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[13..23)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..24)"" Text=""a{{0,2147483648}}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestBadMinMaxClosedRangeNumericQuantifier() { Test(@"""a{1,0}""", $@"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""0"">0</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_x_y_with_x_less_than_y.Replace(">", "&gt;")}"" Span=""[13..14)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{{1,0}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyExactNumericQuantifier() { Test(@"""a{0}?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0}?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyOpenNumericQuantifier() { Test(@"""a{0,}?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0,}?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyClosedNumericQuantifier() { Test(@"""a{0,1}?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0,1}?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier1() { Test(@"""a{""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier2() { Test(@"""a{0""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a{0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier3() { Test(@"""a{0,""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a{0,"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier4() { Test(@"""a{0,1""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,1</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0,1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNotNumericQuantifier1() { Test(@"""a{0 }""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0 }"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier2() { Test(@"""a{0, }""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0, }"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier3() { Test(@"""a{0 ,}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0 ,}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier4() { Test(@"""a{0 ,1}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,1}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0 ,1}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier5() { Test(@"""a{0, 1}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>1}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0, 1}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier6() { Test(@"""a{0,1 }""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,1</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0,1 }"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestLegalOpenCloseBrace1() { Test(@"@""{}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""{}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestLegalOpenCloseBrace2() { Test(@"@""{1, 2}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{1, 2}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""{1, 2}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestDanglingNumericQuantifier1() { Test(@"@""{1}""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>1}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""{{1}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestDanglingNumericQuantifier2() { Test(@"@""{1,2}""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>1,2}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""{{1,2}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyQuantifierDueToIgnoredWhitespace() { Test(@"""a* ?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a* ?"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNonLazyQuantifierDueToNonIgnoredWhitespace() { Test(@"""a* ?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken> </TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a* ?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifierAtStart() { Test(@"""*""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>*</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifierAtStartOfGroup() { Test(@"""(*)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>*</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(*)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifierAfterQuantifier() { Test(@"""a**""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>*</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[11..12)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a**"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifierAtStart() { Test(@"""+""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>+</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifierAtStartOfGroup() { Test(@"""(+)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>+</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(+)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifierAfterQuantifier() { Test(@"""a*+""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>+</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[11..12)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a*+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifierAtStart() { Test(@"""?""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifierAtStartOfGroup() { Test(@"""(?)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifierAfterQuantifier() { Test(@"""a*??""", $@"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>?</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "?")}"" Span=""[12..13)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a*??"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericQuantifierAtStart() { Test(@"""{0}""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""{{0}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericQuantifierAtStartOfGroup() { Test(@"""({0})""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0}}</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""({{0}})"" /> <Capture Name=""1"" Span=""[9..14)"" Text=""({{0}})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericQuantifierAfterQuantifier() { Test(@"""a*{0}""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[11..12)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a*{{0}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonNumericQuantifierAtStart() { Test(@"""{0""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""{0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonNumericQuantifierAtStartOfGroup() { Test(@"""({0)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>{0</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""({0)"" /> <Capture Name=""1"" Span=""[9..13)"" Text=""({0)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonNumericQuantifierAfterQuantifier() { Test(@"""a*{0""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>{0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a*{0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEscapeAtEnd1() { Test(@"@""\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[10..11)"" Text=""\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEscapeAtEnd2() { Test(@"""\\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[9..11)"" Text=""\\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""\\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleEscape() { Test(@"@""\w""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\w"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPrimaryEscapes1() { Test(@"@""\b\B\A\G\Z\z\w\W\s\W\s\S\d\D""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>B</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>A</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>G</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>Z</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>z</TextToken> </AnchorEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""\b\B\A\G\Z\z\w\W\s\W\s\S\d\D"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape1() { Test(@"@""\c""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Missing_control_character}"" Span=""[11..12)"" Text=""c"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\c"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape2() { Test(@"@""\c<""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""&lt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape3() { Test(@"@""\ca""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\ca"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape4() { Test(@"@""\cA""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cA"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape5() { Test(@"@""\c A""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken> A</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\c A"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape6() { Test(@"@""\c(a)""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\c(a)"" /> <Capture Name=""1"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape7() { Test(@"@""\c>""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape8() { Test(@"@""\c?""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape9() { Test(@"@""\c@""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>@</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c@"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape10() { Test(@"@""\c^""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>^</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c^"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape11() { Test(@"@""\c_""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>_</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c_"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape12() { Test(@"@""\c`""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>`</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""`"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c`"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape13() { Test(@"@""\c{""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape14() { Test(@"@""\ca""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\ca"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape15() { Test(@"@""\cA""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cA"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape16() { Test(@"@""\cz""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>z</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cz"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape17() { Test(@"@""\cZ""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>Z</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cZ"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape18() { Test(@"@""\c\""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>\</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape19() { Test(@"@""\c]""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>]</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnknownEscape1() { Test(@"@""\m""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>m</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "m")}"" Span=""[11..12)"" Text=""m"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\m"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape1() { Test(@"@""\x""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\x"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape2() { Test(@"@""\x """, $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\x "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape3() { Test(@"@""\x0""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>0</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\x0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape4() { Test(@"@""\x0 """, $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>0</TextToken> </HexEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\x0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape5() { Test(@"@""\x00""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\x00"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape6() { Test(@"@""\x00 """, @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\x00 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape7() { Test(@"@""\x000""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\x000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape8() { Test(@"@""\xff""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>ff</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xff"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape9() { Test(@"@""\xFF""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>FF</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xFF"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape10() { Test(@"@""\xfF""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>fF</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xfF"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape11() { Test(@"@""\xfff""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>ff</TextToken> </HexEscape> <Text> <TextToken>f</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\xfff"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape12() { Test(@"@""\xgg""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> <Text> <TextToken>gg</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xgg"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnknownEscape2() { Test(@"@""\m """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>m</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "m")}"" Span=""[11..12)"" Text=""m"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\m "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape1() { Test(@"@""\u""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\u"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape2() { Test(@"@""\u0""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\u0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape3() { Test(@"@""\u00""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>00</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..14)"" Text=""\u00"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\u00"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape4() { Test(@"@""\u000""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>000</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..15)"" Text=""\u000"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\u000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape5() { Test(@"@""\u0000""", @"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\u0000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape6() { Test(@"@""\u0000 """, @"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\u0000 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape7() { Test(@"@""\u """, $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\u "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape8() { Test(@"@""\u0 """, $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\u0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape9() { Test(@"@""\ugggg""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> <Text> <TextToken>gggg</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\ugggg"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape1() { Test(@"@""\0""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape2() { Test(@"@""\0 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape3() { Test(@"@""\00""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>00</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\00"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape4() { Test(@"@""\00 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>00</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\00 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape5() { Test(@"@""\000""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape6() { Test(@"@""\000 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\000 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape7() { Test(@"@""\0000""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\0000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape8() { Test(@"@""\0000 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\0000 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape9() { Test(@"@""\7""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""7"">7</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 7)}"" Span=""[11..12)"" Text=""7"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\7"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape10() { Test(@"@""\78""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>7</TextToken> </OctalEscape> <Text> <TextToken>8</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\78"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape11() { Test(@"@""\8""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""8"">8</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 8)}"" Span=""[11..12)"" Text=""8"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\8"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscapeEcmascript1() { Test(@"@""\40""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>40</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\40"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript2() { Test(@"@""\401""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>40</TextToken> </OctalEscape> <Text> <TextToken>1</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\401"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript3() { Test(@"@""\37""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>37</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\37"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript4() { Test(@"@""\371""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>371</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\371"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript5() { Test(@"@""\0000""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\0000"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEscape1() { Test(@"@""\k""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\k"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape2() { Test(@"@""\k """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape3() { Test(@"@""\k<""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape4() { Test(@"@""\k< """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape5() { Test(@"@""\k<0""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape6() { Test(@"@""\k<0 """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape7() { Test(@"@""\k<0>""", @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape8() { Test(@"@""\k<0> """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape9() { Test(@"@""\k<00> """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\k&lt;00&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape10() { Test(@"@""\k<a> """, $@"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[13..14)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;a&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape11() { Test(@"@""(?<a>)\k<a> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?&lt;a&gt;)\k&lt;a&gt; "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEcmaEscape1() { Test(@"@""\k""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\k"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape2() { Test(@"@""\k """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape3() { Test(@"@""\k<""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k&lt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape4() { Test(@"@""\k< """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape5() { Test(@"@""\k<0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;0"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape6() { Test(@"@""\k<0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0 "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape7() { Test(@"@""\k<0>""", @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape8() { Test(@"@""\k<0> """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureQuoteEscape3() { Test(@"@""\k'""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape4() { Test(@"@""\k' """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>' </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape5() { Test(@"@""\k'0""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k'0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape6() { Test(@"@""\k'0 """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k'0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape7() { Test(@"@""\k'0'""", @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k'0'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape8() { Test(@"@""\k'0' """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k'0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape9() { Test(@"@""\k'00' """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">00</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\k'00' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape10() { Test(@"@""\k'a' """, $@"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[13..14)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k'a' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape11() { Test(@"@""(?<a>)\k'a' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?&lt;a&gt;)\k'a' "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureWrongQuote1() { Test(@"@""\k<0' """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0' </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureWrongQuote2() { Test(@"@""\k'0> """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'0&gt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k'0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape1() { Test(@"@""\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[10..11)"" Text=""\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape2() { Test(@"@""\ """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken> </TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\ "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape3() { Test(@"@""\<""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape4() { Test(@"@""\< """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape5() { Test(@"@""\<0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt;0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape6() { Test(@"@""\<0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape7() { Test(@"@""\<0>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape8() { Test(@"@""\<0> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape9() { Test(@"@""\<00> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\&lt;00&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape10() { Test(@"@""\<a> """, $@"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[12..13)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;a&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape11() { Test(@"@""(?<a>)\<a> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(?&lt;a&gt;)\&lt;a&gt; "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEcmaEscape1() { Test(@"@""\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[10..11)"" Text=""\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""\"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape2() { Test(@"@""\ """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken> </TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\ "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape3() { Test(@"@""\<""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\&lt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape4() { Test(@"@""\< """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape5() { Test(@"@""\<0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt;0"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape6() { Test(@"@""\<0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0 "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape7() { Test(@"@""\<0>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape8() { Test(@"@""\<0> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureQuoteEscape3() { Test(@"@""\'""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape4() { Test(@"@""\' """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape5() { Test(@"@""\'0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\'0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape6() { Test(@"@""\'0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\'0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape7() { Test(@"@""\'0'""", @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\'0'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape8() { Test(@"@""\'0' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\'0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape9() { Test(@"@""\'00' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">00</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\'00' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape10() { Test(@"@""\'a' """, $@"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[12..13)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\'a' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape11() { Test(@"@""(?<a>)\'a' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(?&lt;a&gt;)\'a' "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureWrongQuote1() { Test(@"@""\<0' """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0' </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureWrongQuote2() { Test(@"@""\'0> """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken>0&gt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\'0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDefinedCategoryEscape() { Test(@"""\\p{Cc}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Cc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""\\p{Cc}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDefinedCategoryEscapeWithSpaces1() { Test(@"""\\p{ Cc }""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{ Cc }}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""\\p{{ Cc }}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDefinedCategoryEscapeWithSpaces2() { Test(@"""\\p{ Cc }""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>Cc</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""\\p{{ Cc }}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestDefinedCategoryEscapeWithSpaces3() { Test(@"""\\p {Cc}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>{{Cc}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""\\p {{Cc}}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestUndefinedCategoryEscape() { Test(@"""\\p{xxx}""", $@"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>xxx</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "xxx")}"" Span=""[13..16)"" Text=""xxx"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""\\p{{xxx}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape1() { Test(@"""\\p""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""\\p"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape2() { Test(@"""\\p{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""\\p{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape3() { Test(@"""\\p{}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""\\p{{}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape4() { Test(@"""\\p{} """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{}} </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unknown_property}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""\\p{{}} "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape5() { Test(@"""\\p {} """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken> {{}} </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""\\p {{}} "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape6() { Test(@"""\\p{Cc """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{Cc </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""\\p{{Cc "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCategoryNameWithDash() { Test(@"""\\p{IsArabicPresentationForms-A}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsArabicPresentationForms-A</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""\\p{IsArabicPresentationForms-A}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping1() { Test(@"""(?:)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?:)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping2() { Test(@"""(?:a)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?:a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping3() { Test(@"""(?:""", $@"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken /> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping4() { Test(@"""(?: """, $@"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken /> </NonCapturingGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?: "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestPositiveLookaheadGrouping1() { Test(@"""(?=)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?=)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookaheadGrouping2() { Test(@"""(?=a)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?=a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookaheadGrouping3() { Test(@"""(?=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookaheadGrouping4() { Test(@"""(?= """, $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookaheadGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?= "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNegativeLookaheadGrouping1() { Test(@"""(?!)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?!)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookaheadGrouping2() { Test(@"""(?!a)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?!a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookaheadGrouping3() { Test(@"""(?!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookaheadGrouping4() { Test(@"""(?! """, $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookaheadGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?! "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAtomicGrouping1() { Test(@"""(?>)""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAtomicGrouping2() { Test(@"""(?>a)""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAtomicGrouping3() { Test(@"""(?>""", $@"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAtomicGrouping4() { Test(@"""(?> """, $@"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </AtomicGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&gt; "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestPositiveLookbehindGrouping1() { Test(@"""(?<=)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;=)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookbehindGrouping2() { Test(@"""(?<=a)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;=a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookbehindGrouping3() { Test(@"""(?<=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookbehindGrouping4() { Test(@"""(?<= """, $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookbehindGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;= "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNegativeLookbehindGrouping1() { Test(@"""(?<!)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;!)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookbehindGrouping2() { Test(@"""(?<!a)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;!a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookbehindGrouping3() { Test(@"""(?<!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookbehindGrouping4() { Test(@"""(?<! """, $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookbehindGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;! "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture1() { Test(@"""(?<""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?&lt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture2() { Test(@"""(?<>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text=""&gt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture3() { Test(@"""(?<a""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;a"" /> <Capture Name=""1"" Span=""[9..13)"" Text=""(?&lt;a"" /> <Capture Name=""a"" Span=""[9..13)"" Text=""(?&lt;a"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture4() { Test(@"""(?<a>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;a&gt;"" /> <Capture Name=""1"" Span=""[9..14)"" Text=""(?&lt;a&gt;"" /> <Capture Name=""a"" Span=""[9..14)"" Text=""(?&lt;a&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture5() { Test(@"""(?<a>a""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;a&gt;a"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;a"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;a"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture6() { Test(@"""(?<a>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;a&gt;a)"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;a&gt;a)"" /> <Capture Name=""a"" Span=""[9..16)"" Text=""(?&lt;a&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture7() { Test(@"""(?<a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> &gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNamedCapture8() { Test(@"""(?<a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture9() { Test(@"""(?< a>a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> a&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt; a&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNamedCapture10() { Test(@"""(?< a>a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>a&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt; a&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture11() { Test(@"""(?< a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> a &gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt; a &gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNamedCapture12() { Test(@"""(?< a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>a</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt; a &gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture13() { Test(@"""(?<ab>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""ab"">ab</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;ab&gt;a)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;ab&gt;a)"" /> <Capture Name=""ab"" Span=""[9..17)"" Text=""(?&lt;ab&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestZeroNumberCapture() { Test(@"""(?<0>a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[12..13)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;0&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNumericNumberCapture1() { Test(@"""(?<1>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;1&gt;a)"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;1&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNumericNumberCapture2() { Test(@"""(?<10>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""10"">10</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;10&gt;a)"" /> <Capture Name=""10"" Span=""[9..17)"" Text=""(?&lt;10&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNumericNumberCapture3() { Test(@"""(?<1>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;1&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;1&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericNumberCapture4() { Test(@"""(?<1> )""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericNumberCapture6() { Test(@"""(?<1> )""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestBalancingGrouping1() { Test(@"""(?<-""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..13)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;-"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping2() { Test(@"""(?<-0""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;-0"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping3() { Test(@"""(?<-0)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;-0)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping4() { Test(@"""(?<-0>""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;-0&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping5() { Test(@"""(?<-0>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping6() { Test(@"""(?<-0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;-0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping7() { Test(@"""(?<- 0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;- 0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping8() { Test(@"""(?<- 0>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;- 0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping9() { Test(@"""(?<-00>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;-00&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping10() { Test(@"""(?<a-""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..14)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;a-"" /> <Capture Name=""1"" Span=""[9..14)"" Text=""(?&lt;a-"" /> <Capture Name=""a"" Span=""[9..14)"" Text=""(?&lt;a-"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping11() { Test(@"""(?<a-0""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;a-0"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a-0"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a-0"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping12() { Test(@"""(?<a-0)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;a-0)"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;a-0)"" /> <Capture Name=""a"" Span=""[9..16)"" Text=""(?&lt;a-0)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping13() { Test(@"""(?<a-0>""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;a-0&gt;"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;a-0&gt;"" /> <Capture Name=""a"" Span=""[9..16)"" Text=""(?&lt;a-0&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping14() { Test(@"""(?<a-0>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping15() { Test(@"""(?<a-0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;a-0 &gt;)"" /> <Capture Name=""1"" Span=""[9..18)"" Text=""(?&lt;a-0 &gt;)"" /> <Capture Name=""a"" Span=""[9..18)"" Text=""(?&lt;a-0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping16() { Test(@"""(?<a- 0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..19)"" Text=""(?&lt;a- 0 &gt;)"" /> <Capture Name=""1"" Span=""[9..19)"" Text=""(?&lt;a- 0 &gt;)"" /> <Capture Name=""a"" Span=""[9..19)"" Text=""(?&lt;a- 0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping17() { Test(@"""(?<a- 0>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;a- 0&gt;)"" /> <Capture Name=""1"" Span=""[9..18)"" Text=""(?&lt;a- 0&gt;)"" /> <Capture Name=""a"" Span=""[9..18)"" Text=""(?&lt;a- 0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping18() { Test(@"""(?<a-00>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;a-00&gt;)"" /> <Capture Name=""1"" Span=""[9..18)"" Text=""(?&lt;a-00&gt;)"" /> <Capture Name=""a"" Span=""[9..18)"" Text=""(?&lt;a-00&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingUndefinedReference1() { Test(@"""(?<-1>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[13..14)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;-1&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingDefinedReferenceBehind() { Test(@"""()(?<-1>)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""()(?&lt;-1&gt;)"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingDefinedReferenceAhead() { Test(@"""(?<-1>)()""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;-1&gt;)()"" /> <Capture Name=""1"" Span=""[16..18)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNamedReferenceBehind() { Test(@"""(?<a>)(?<-a>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;a&gt;)(?&lt;-a&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNamedReferenceAhead() { Test(@"""(?<-a>)(?<a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;-a&gt;)(?&lt;a&gt;)"" /> <Capture Name=""1"" Span=""[16..22)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[16..22)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNumberedReferenceBehind() { Test(@"""(?<4>)(?<-4>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;4&gt;)(?&lt;-4&gt;)"" /> <Capture Name=""4"" Span=""[9..15)"" Text=""(?&lt;4&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNumberedReferenceAhead() { Test(@"""(?<-4>)(?<4>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;-4&gt;)(?&lt;4&gt;)"" /> <Capture Name=""4"" Span=""[16..22)"" Text=""(?&lt;4&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumberedExists() { Test(@"""(?<a>)(?<b>)(?<-1>)(?<-2>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..35)"" Text=""(?&lt;a&gt;)(?&lt;b&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""b"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers() { Test(@"""()()(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[38..39)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""()()(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> <Capture Name=""2"" Span=""[11..13)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers1() { Test(@"""()(?<a>)(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[42..43)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""()(?&lt;a&gt;)(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> <Capture Name=""2"" Span=""[11..17)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[11..17)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers2() { Test(@"""(?<a>)()(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[42..43)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;a&gt;)()(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers3() { Test(@"""(?<a>)(?<b>)(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[46..47)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..49)"" Text=""(?&lt;a&gt;)(?&lt;b&gt;)(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""b"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers4() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)()()""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)()()"" /> <Capture Name=""1"" Span=""[37..39)"" Text=""()"" /> <Capture Name=""2"" Span=""[39..41)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers5_1() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)()(?""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[27..28)"" Text=""2"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[39..40)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[40..41)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[41..41)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)()(?"" /> <Capture Name=""1"" Span=""[37..39)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers5() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)()(?<a>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)()(?&lt;a&gt;)"" /> <Capture Name=""1"" Span=""[37..39)"" Text=""()"" /> <Capture Name=""2"" Span=""[39..45)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[39..45)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers6() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)(?<a>)()""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)(?&lt;a&gt;)()"" /> <Capture Name=""1"" Span=""[43..45)"" Text=""()"" /> <Capture Name=""2"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers7_1() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)(?<a>)(?""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[27..28)"" Text=""2"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[43..44)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[44..45)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[45..45)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)(?&lt;a&gt;)(?"" /> <Capture Name=""1"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers7() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)(?<a>)(?<b>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..49)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)(?&lt;a&gt;)(?&lt;b&gt;)"" /> <Capture Name=""1"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""2"" Span=""[43..49)"" Text=""(?&lt;b&gt;)"" /> <Capture Name=""a"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""b"" Span=""[43..49)"" Text=""(?&lt;b&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestReferenceToBalancingGroupCaptureName1() { Test(@"""(?<a-0>)(?<b-a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..25)"" Text=""(?&lt;a-0&gt;)(?&lt;b-a&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""2"" Span=""[17..25)"" Text=""(?&lt;b-a&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""b"" Span=""[17..25)"" Text=""(?&lt;b-a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestReferenceToBalancingGroupCaptureName2() { Test(@"""(?<a-0>)(?<-a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..24)"" Text=""(?&lt;a-0&gt;)(?&lt;-a&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestReferenceToSameBalancingGroup() { Test(@"""(?<a-a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a-a&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-a&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestQuoteNamedCapture() { Test(@"""(?'a')""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?'a')"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?'a')"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?'a')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestQuoteBalancingCapture1() { Test(@"""(?'-0')""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?'-0')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestQuoteBalancingCapture2() { Test(@"""(?'a-0')""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?'a-0')"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?'a-0')"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?'a-0')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestMismatchedOpenCloseCapture1() { Test(@"""(?<a-0')""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>'</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text=""'"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a-0')"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0')"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestMismatchedOpenCloseCapture2() { Test(@"""(?'a-0>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken /> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?'a-0&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?'a-0&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?'a-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestConditionalCapture1() { Test(@"""(?(""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?("" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture2() { Test(@"""(?(0""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken /> <Sequence /> <CloseParenToken /> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed}"" Span=""[12..13)"" Text=""0"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?(0"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture3() { Test(@"""(?(0)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken /> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(0)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture4() { Test(@"""(?(0))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(0))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture5() { Test(@"""(?(0)a)""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(0)a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture6() { Test(@"""(?(0)a|)""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(0)a|)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture7() { Test(@"""(?(0)a|b)""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?(0)a|b)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture8() { Test(@"""(?(0)a|b|)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Too_many_bars_in_conditional_grouping}"" Span=""[17..18)"" Text=""|"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..19)"" Text=""(?(0)a|b|)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture9() { Test(@"""(?(0)a|b|c)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>c</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Too_many_bars_in_conditional_grouping}"" Span=""[17..18)"" Text=""|"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..20)"" Text=""(?(0)a|b|c)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture10() { Test(@"""(?(0 )""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken /> <Sequence /> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed}"" Span=""[12..13)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(0 )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture11() { Test(@"""(?(1))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Reference_to_undefined_group}"" Span=""[12..13)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(1))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture12() { Test(@"""(?(00))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">00</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(00))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture1() { Test(@"""(?(a))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(a))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture2() { Test(@"""(?<a>)(?(a))""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..21)"" Text=""(?&lt;a&gt;)(?(a))"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture3() { Test(@"""(?<a>)(?(a ))""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;a&gt;)(?(a ))"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture4() { Test(@"""(?<a>)(?( a))""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;a&gt;)(?( a))"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedGroupsInConditionalGrouping1() { Test(@"""(?(()a()))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..19)"" Text=""(?(()a()))"" /> <Capture Name=""1"" Span=""[12..14)"" Text=""()"" /> <Capture Name=""2"" Span=""[15..17)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNestedGroupsInConditionalGrouping2() { Test(@"""(?((?<x>)a(?<y>)))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""x"">x</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Text> <TextToken>a</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""y"">y</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..27)"" Text=""(?((?&lt;x&gt;)a(?&lt;y&gt;)))"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(?&lt;x&gt;)"" /> <Capture Name=""2"" Span=""[19..25)"" Text=""(?&lt;y&gt;)"" /> <Capture Name=""x"" Span=""[12..18)"" Text=""(?&lt;x&gt;)"" /> <Capture Name=""y"" Span=""[19..25)"" Text=""(?&lt;y&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureInConditionalGrouping1() { Test(@"""(?(?'""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <SingleQuoteToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..14)"" Text=""(?'"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(?'"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCaptureInConditionalGrouping2() { Test(@"""(?(?'x'))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""x"">x</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?(?'x'))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCommentInConditionalGrouping1() { Test(@"""(?(?#""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>#</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[11..14)"" Text=""(?#"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..12)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[12..13)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(?#"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCommentInConditionalGrouping2() { Test(@"""(?(?#)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..12)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[12..13)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(?#)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCommentInConditionalGrouping3() { Test(@"""(?(?#))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>#))</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..12)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[12..13)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(?#))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping1() { Test(@"""(?(?<""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..14)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(?&lt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping2() { Test(@"""(?(?<a""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..14)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(?&lt;a"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping3() { Test(@"""(?(?<a>""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(?&lt;a&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping4() { Test(@"""(?(?<a>)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping5() { Test(@"""(?(?<a>))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?(?&lt;a&gt;))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestLookbehindAssertionInConditionalGrouping1() { Test(@"""(?(?<=))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(?&lt;=))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestLookbehindAssertionInConditionalGrouping2() { Test(@"""(?(?<!))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(?&lt;!))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestBackreference1() { Test(@"@""\1""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[11..12)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference2() { Test(@"@""\1 """, $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[11..12)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\1 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference3() { Test(@"@""()\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference4() { Test(@"@""()\1 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""()\1 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference5() { Test(@"@""()\10 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>10</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()\10 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEcmascriptBackreference1() { Test(@"@""\1""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\1"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference2() { Test(@"@""\1 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\1 "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference3() { Test(@"@""()\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmaBackreference4() { Test(@"@""()\1 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""()\1 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference5() { Test(@"@""()\10 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""10"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()\10 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference6() { Test(@"@""()()()()()()()()()()\10 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""10"">10</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..34)"" Text=""()()()()()()()()()()\10 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> <Capture Name=""3"" Span=""[14..16)"" Text=""()"" /> <Capture Name=""4"" Span=""[16..18)"" Text=""()"" /> <Capture Name=""5"" Span=""[18..20)"" Text=""()"" /> <Capture Name=""6"" Span=""[20..22)"" Text=""()"" /> <Capture Name=""7"" Span=""[22..24)"" Text=""()"" /> <Capture Name=""8"" Span=""[24..26)"" Text=""()"" /> <Capture Name=""9"" Span=""[26..28)"" Text=""()"" /> <Capture Name=""10"" Span=""[28..30)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCharacterClass1() { Test(@"@""[""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence /> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""["" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass2() { Test(@"@""[ """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[ "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass3() { Test(@"@""[]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass4() { Test(@"@""[] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>] </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass5() { Test(@"@""[a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass6() { Test(@"@""[a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass7() { Test(@"@""[a-""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken /> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a-"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass8() { Test(@"@""[a- """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken> </TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[a- "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass9() { Test(@"@""[a-]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[a-]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass10() { Test(@"@""[a-] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass11() { Test(@"@""[a-b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass12() { Test(@"@""[a-b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass13() { Test(@"@""[a-[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass14() { Test(@"@""[a-b-[c]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>c</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-b-[c]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass15() { Test(@"@""[a-[b]-c] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> <Text> <TextToken>-c</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-[b]-c] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass16() { Test(@"@""[[a]-b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>-b] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[[a]-b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass17() { Test(@"@""[[a]-[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>-</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[[a]-[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass18() { Test(@"@""[\w-a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\w-a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass19() { Test(@"@""[a-\w] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "w")}"" Span=""[13..15)"" Text=""\w"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-\w] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass20() { Test(@"@""[\p{llll}-a] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>llll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "llll")}"" Span=""[14..18)"" Text=""llll"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[\p{{llll}}-a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass21() { Test(@"@""[\p{Lu}-a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[\p{Lu}-a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass22() { Test(@"@""[a-\p{Lu}] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "p")}"" Span=""[13..15)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-\p{{Lu}}] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass23() { Test(@"@""[a-[:Ll:]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:Ll:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-[:Ll:]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass24() { Test(@"@""[a-[:Ll]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:Ll</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-[:Ll]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass25() { Test(@"@""[a-[:""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-[:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass26() { Test(@"@""[a-[:L""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:L</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-[:L"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass27() { Test(@"@""[a-[:L:""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:L:</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-[:L:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass28() { Test(@"@""[a-[:L:]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:L:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[18..18)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-[:L:]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass29() { Test(@"@""[\-]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[\-]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass30() { Test(@"@""[a-b-c] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>-c</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-b-c] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass31() { Test(@"@""[-b-c] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>c</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[-b-c] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass32() { Test(@"@""[-[b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-[b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[-[b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass33() { Test(@"@""[-[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-[b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[-[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass34() { Test(@"@""[--b """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>-</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[--b "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass35() { Test(@"@""[--b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>-</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[--b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass36() { Test(@"@""[--[b """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[--[b "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass37() { Test(@"@""[--[b] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[12..12)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[--[b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass38() { Test(@"@""[--[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[--[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass39() { Test(@"@""[a--[b """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>[b </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a--[b "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass40() { Test(@"@""[,--[a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>,</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[,--[a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass41() { Test(@"@""[,--[a]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>,</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[,--[a]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass42() { Test(@"@""[\s-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\s-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass43() { Test(@"@""[\p{Lu}-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[\p{Lu}-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass44() { Test(@"@""[\p{Lu}-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[\p{Lu}-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegatedCharacterClass1() { Test(@"@""[a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange1() { Test(@"@""[\c<-\c>]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <CharacterClassRange> <Text> <TextToken>&lt;</TextToken> </Text> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[13..14)"" Text=""&lt;"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[17..18)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\c&lt;-\c&gt;]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange2() { Test(@"@""[\c>-\c<]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </CharacterClassRange> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[13..14)"" Text=""&gt;"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[17..18)"" Text=""&lt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\c&gt;-\c&lt;]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange3() { Test(@"@""[\c>-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[13..14)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\c&gt;-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange4() { Test(@"@""[a-\c>]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[15..16)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-\c&gt;]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange5() { Test(@"@""[a--]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a--]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange6() { Test(@"@""[--a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>-</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[--a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange7() { Test(@"@""[a-\-]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-\-]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange8() { Test(@"@""[\--a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\--a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange9() { Test(@"@""[\0-\1]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\0-\1]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange10() { Test(@"@""[\1-\0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[13..14)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\1-\0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange11() { Test(@"@""[\0-\01]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>01</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\0-\01]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange12() { Test(@"@""[\01-\0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>01</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\01-\0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange13() { Test(@"@""[[:x:]-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <PosixProperty> <TextToken>[:x:]</TextToken> </PosixProperty> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[[:x:]-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange14() { Test(@"@""[a-[:x:]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:x:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-[:x:]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange15() { Test(@"@""[\0-\ca]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\0-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange16() { Test(@"@""[\ca-\0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\ca-\0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange17() { Test(@"@""[\ca-\cA]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\ca-\cA]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange18() { Test(@"@""[\cA-\ca]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cA-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange19() { Test(@"@""[\u0-\u1]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>1</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[11..14)"" Text=""\u0"" /> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[15..18)"" Text=""\u1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\u0-\u1]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange20() { Test(@"@""[\u1-\u0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>1</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[11..14)"" Text=""\u1"" /> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[15..18)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\u1-\u0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange21() { Test(@"@""[\u0000-\u0000]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""[\u0000-\u0000]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange22() { Test(@"@""[\u0000-\u0001]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""[\u0000-\u0001]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange23() { Test(@"@""[\u0001-\u0000]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[17..18)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""[\u0001-\u0000]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange24() { Test(@"@""[\u0001-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[\u0001-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange25() { Test(@"@""[a-\u0001]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-\u0001]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange26() { Test(@"@""[a-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange27() { Test(@"@""[a-A]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>A</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-A]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange28() { Test(@"@""[A-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[A-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange29() { Test(@"@""[a-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-a]"" /> </Captures> </Tree>", RegexOptions.IgnoreCase); } [Fact] public void TestCharacterClassRange30() { Test(@"@""[a-A]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>A</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-A]"" /> </Captures> </Tree>", RegexOptions.IgnoreCase); } [Fact] public void TestCharacterClassRange31() { Test(@"@""[A-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[A-a]"" /> </Captures> </Tree>", RegexOptions.IgnoreCase); } [Fact] public void TestCharacterClassRange32() { Test(@"@""[a-\x61]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>61</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\x61]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange33() { Test(@"@""[\x61-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>61</TextToken> </HexEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\x61-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange34() { Test(@"@""[a-\x60]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>60</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\x60]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange35() { Test(@"@""[\x62-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>62</TextToken> </HexEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[15..16)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\x62-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange36() { Test(@"@""[a-\x62]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>62</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\x62]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange37() { Test(@"@""[\x62-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>62</TextToken> </HexEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[15..16)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\x62-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange38() { Test(@"@""[\3-\cc]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>3</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\3-\cc]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange39() { Test(@"@""[\cc-\3]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>3</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\cc-\3]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange40() { Test(@"@""[\2-\cc]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>2</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\2-\cc]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange41() { Test(@"@""[\cc-\2]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>2</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\cc-\2]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange42() { Test(@"@""[\4-\cc]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>4</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[13..14)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\4-\cc]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange43() { Test(@"@""[\cc-\4]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>4</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\cc-\4]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange44() { Test(@"@""[\ca-\cb]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\ca-\cb]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange45() { Test(@"@""[\ca-\cB]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\ca-\cB]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange46() { Test(@"@""[\cA-\cb]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cA-\cb]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange47() { Test(@"@""[\cA-\cB]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cA-\cB]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange48() { Test(@"@""[\cb-\ca]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cb-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange49() { Test(@"@""[\cb-\cA]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cb-\cA]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange50() { Test(@"@""[\cB-\ca]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cB-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange51() { Test(@"@""[\cB-\cA]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cB-\cA]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange52() { Test(@"@""[\--a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\--a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange53() { Test(@"@""[\--#]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>-#</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\--#]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange54() { Test(@"@""[a-\-]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-\-]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange55() { Test(@"@""[a-\-b]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-\-b]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange56() { Test(@"@""[a-\-\-b]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-\-\-b]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange57() { Test(@"@""[b-\-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[b-\-a]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange58() { Test(@"@""[b-\-\-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[b-\-\-a]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange59() { Test(@"@""[a-\-\D]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\-\D]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange60() { Test(@"@""[a-\-\-\D]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-\-\-\D]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange61() { Test(@"@""[a -\-\b]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassRange> <Text> <TextToken> </TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a -\-\b]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange62() { Test(@"@""[ab-\-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[13..14)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[ab-\-a]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCaptures1() { Test(@"@""()\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures2() { Test(@"@""()\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[13..14)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures3() { Test(@"@""()()\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()()\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures4() { Test(@"@""()\1""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[13..14)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures5() { Test(@"@""()\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[13..14)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures6() { Test(@"@""()()\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[15..16)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()()\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures7() { Test(@"@""()()(?n)\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()()(?n)\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures8() { Test(@"@""()(?n)()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()(?n)()\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures9() { Test(@"@""(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures10() { Test(@"@""()()(?n)\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()()(?n)\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures11() { Test(@"@""()(?n)()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()(?n)()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures12() { Test(@"@""(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures13() { Test(@"@""()()(?-n)\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?-n)\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures14() { Test(@"@""()(?-n)()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()(?-n)()\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures15() { Test(@"@""(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures16() { Test(@"@""()()(?-n)\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[20..21)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?-n)\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures17() { Test(@"@""()(?-n)()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()(?-n)()\1\2"" /> <Capture Name=""1"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures18() { Test(@"@""(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures19() { Test(@"@""()()(?n:\1\2)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?n:\1\2)"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures20() { Test(@"@""()()(?n:\1\2)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?n:\1\2)"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures21() { Test(@"@""()()(?-n:\1\2)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""()()(?-n:\1\2)"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures22() { Test(@"@""()()(?-n:\1\2)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[20..21)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""()()(?-n:\1\2)"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures23() { Test(@"@""(?n:)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?n:)()()\1\2"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures24() { Test(@"@""(?n:)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[20..21)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?n:)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures25() { Test(@"@""(?-n:)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?-n:)()()\1\2"" /> <Capture Name=""1"" Span=""[16..18)"" Text=""()"" /> <Capture Name=""2"" Span=""[18..20)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures26() { Test(@"@""(?-n:)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[21..22)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[23..24)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?-n:)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures27() { Test(@"@""(?n)(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?n)(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[19..21)"" Text=""()"" /> <Capture Name=""2"" Span=""[21..23)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures28() { Test(@"@""(?n)(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?n)(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[19..21)"" Text=""()"" /> <Capture Name=""2"" Span=""[21..23)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures29() { Test(@"@""(?-n)(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[24..25)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[26..27)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?-n)(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures30() { Test(@"@""(?-n)(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[24..25)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[26..27)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?-n)(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Text.RegularExpressions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.EmbeddedLanguages.RegularExpressions { // These tests were created by trying to enumerate all codepaths in the lexer/parser. public partial class CSharpRegexParserTests { [Fact] public void TestEmpty() { Test(@"""""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[0..0)"" Text="""" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOneWhitespace_IgnorePatternWhitespace() { Test(@""" """, @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text="" "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestTwoWhitespace_IgnorePatternWhitespace() { Test(@""" """, @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text="" "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestEmptyParenComment() { Test(@"""(?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?#)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleParenComment() { Test(@"""(?# )""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?# )</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?# )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnterminatedParenComment1() { Test(@"""(?#""", $@"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[9..12)"" Text=""(?#"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?#"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnterminatedParenComment2() { Test(@"""(?# """, $@"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?# </CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[9..13)"" Text=""(?# "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?# "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestMultipleComments1() { Test(@"""(?#)(?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?#)(?#)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestMultipleComments2() { Test(@"""(?#)(?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?#)(?#)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestMultipleComments3() { Test(@"""(?#) (?#)""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken> <Trivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </TextToken> </Text> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?#) (?#)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestMultipleComments4() { Test(@"""(?#) (?#)""", @"<Tree> <CompilationUnit> <Sequence /> <EndOfFile> <Trivia> <CommentTrivia>(?#)</CommentTrivia> <WhitespaceTrivia> </WhitespaceTrivia> <CommentTrivia>(?#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?#) (?#)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass1() { Test(@"@""[a\p{Lu}(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[a\p{Lu}(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass2() { Test(@"@""[a\0(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a\0(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass3() { Test(@"@""[a\a(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>a</TextToken> </SimpleEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a\a(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass4() { Test(@"@""[a\x00(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""[a\x00(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass5() { Test(@"@""[a\u0000(?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""[a\u0000(?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDoNotTreatAsCommentAfterEscapeInCharacterClass6() { Test(@"@""[a\](?#)b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>]</TextToken> </SimpleEscape> <Text> <TextToken>(?#)b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a\](?#)b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenQuestion1() { Test(@"""(?""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""(?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenQuestion2() { Test(@"""(?""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""(?"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestOpenQuestion3() { Test(@"""(? """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(? "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenQuestion4() { Test(@"""(? """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(? "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestSimpleOptionsNode1() { Test(@"""(?i)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?i)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleOptionsNode2() { Test(@"""(?im)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>im</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?im)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleOptionsNode3() { Test(@"""(?im-x)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>im-x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?im-x)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleOptionsNode4() { Test(@"""(?im-x+n)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>im-x+n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?im-x+n)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesNotChangeWhitespaceScanning() { Test(@"""(?i) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>i</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?i) "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesChangeWhitespaceScanning() { Test(@"""(?x) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?x) "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesChangeWhitespaceScanning2() { Test(@""" (?x) """, @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken> </TextToken> </Text> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text="" (?x) "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOptionThatDoesChangeWhitespaceScanning3() { Test(@""" (?-x) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text="" (?-x) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestOptionRestoredWhenGroupPops() { Test(@""" ( (?-x) ) """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <Sequence> <SimpleOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..20)"" Text="" ( (?-x) ) "" /> <Capture Name=""1"" Span=""[10..19)"" Text=""( (?-x) )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedOptionGroup1() { Test(@""" (?-x:) """, @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text="" (?-x:) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedOptionGroup2() { Test(@""" (?-x: ) """, @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text="" (?-x: ) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedOptionGroup3() { Test(@""" (?-x: (?+x: ) ) """, @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken> </TextToken> </Text> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>+x</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </NestedOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..26)"" Text="" (?-x: (?+x: ) ) "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncompleteOptionsGroup1() { Test(@"""(?-x""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?-x"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncompleteOptionsGroup2() { Test(@"""(?-x """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?-x "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncorrectOptionsGroup3() { Test(@"""(?-x :""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> :</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?-x :"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncorrectOptionsGroup4() { Test(@"""(?-x )""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> </TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[14..15)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?-x )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestIncorrectOptionsGroup5() { Test(@"""(?-x :)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-x</OptionsToken> <CloseParenToken /> </SimpleOptionsGrouping> <Text> <TextToken> :</TextToken> </Text> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[15..16)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?-x :)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCloseParen() { Test(@""")""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>)</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Too_many_close_parens}"" Span=""[9..10)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text="")"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSingleChar() { Test(@"""a""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""a"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTwoCharsChar() { Test(@"""ab""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>ab</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""ab"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifier() { Test(@"""a*""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuestionQuantifier() { Test(@"""a*?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a*?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifier() { Test(@"""a+""", @"<Tree> <CompilationUnit> <Sequence> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuestionQuantifier() { Test(@"""a+?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OneOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <PlusToken>+</PlusToken> </OneOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a+?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifier() { Test(@"""a?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuestionQuantifier() { Test(@"""a??""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken>a</TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a??"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEmptySimpleGroup() { Test(@"""()""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""()"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestGroupWithSingleElement() { Test(@"""(a)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(a)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestGroupWithMissingCloseParen() { Test(@"""(""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[10..10)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""("" /> <Capture Name=""1"" Span=""[9..10)"" Text=""("" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestGroupWithElementWithMissingCloseParen() { Test(@"""(a""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""(a"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""(a"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void JustBar() { Test(@"""|""", @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""|"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void SpaceBar() { Test(@""" |""", @"<Tree> <CompilationUnit> <Alternation> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text="" |"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void BarSpace() { Test(@"""| """, @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""| "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void SpaceBarSpace() { Test(@""" | """, @"<Tree> <CompilationUnit> <Alternation> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text="" | "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void JustBar_IgnoreWhitespace() { Test(@"""|""", @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""|"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void SpaceBar_IgnoreWhitespace() { Test(@""" |""", @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text="" |"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void BarSpace_IgnoreWhitespace() { Test(@"""| """, @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""| "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void SpaceBarSpace_IgnoreWhitespace() { Test(@""" | """, @"<Tree> <CompilationUnit> <Alternation> <Sequence /> <BarToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>|</BarToken> <Sequence /> </Alternation> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text="" | "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void DoubleBar() { Test(@"""||""", @"<Tree> <CompilationUnit> <Alternation> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <BarToken>|</BarToken> <Sequence /> </Alternation> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""||"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void BarInGroup() { Test(@"""(|)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Alternation> <Sequence /> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(|)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(|)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestExactNumericQuantifier() { Test(@"""a{0}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a{0}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOpenRangeNumericQuantifier() { Test(@"""a{0,}""", @"<Tree> <CompilationUnit> <Sequence> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0,}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestClosedRangeNumericQuantifier() { Test(@"""a{0,1}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0,1}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLargeExactRangeNumericQuantifier1() { Test(@"""a{2147483647}""", @"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2147483647"">2147483647</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""a{2147483647}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false, allowOutOfMemory: true); } [Fact] public void TestLargeExactRangeNumericQuantifier2() { Test(@"""a{2147483648}""", $@"<Tree> <CompilationUnit> <Sequence> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ExactNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[11..21)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""a{{2147483648}}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestLargeOpenRangeNumericQuantifier1() { Test(@"""a{2147483647,}""", @"<Tree> <CompilationUnit> <Sequence> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""2147483647"">2147483647</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..23)"" Text=""a{2147483647,}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false, allowOutOfMemory: true); } [Fact] public void TestLargeOpenRangeNumericQuantifier2() { Test(@"""a{2147483648,}""", $@"<Tree> <CompilationUnit> <Sequence> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}}</CloseBraceToken> </OpenRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[11..21)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..23)"" Text=""a{{2147483648,}}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestLargeClosedRangeNumericQuantifier1() { Test(@"""a{0,2147483647}""", @"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""2147483647"">2147483647</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..24)"" Text=""a{0,2147483647}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestLargeClosedRangeNumericQuantifier2() { Test(@"""a{0,2147483648}""", $@"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""-2147483648"">2147483648</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_group_numbers_must_be_less_than_or_equal_to_Int32_MaxValue}"" Span=""[13..23)"" Text=""2147483648"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..24)"" Text=""a{{0,2147483648}}"" /> </Captures> </Tree>", RegexOptions.None, runSubTreeTests: false); } [Fact] public void TestBadMinMaxClosedRangeNumericQuantifier() { Test(@"""a{1,0}""", $@"<Tree> <CompilationUnit> <Sequence> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{{</OpenBraceToken> <NumberToken value=""1"">1</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""0"">0</NumberToken> <CloseBraceToken>}}</CloseBraceToken> </ClosedRangeNumericQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_x_y_with_x_less_than_y.Replace(">", "&gt;")}"" Span=""[13..14)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{{1,0}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyExactNumericQuantifier() { Test(@"""a{0}?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ExactNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ExactNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0}?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyOpenNumericQuantifier() { Test(@"""a{0,}?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <OpenRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <CloseBraceToken>}</CloseBraceToken> </OpenRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0,}?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyClosedNumericQuantifier() { Test(@"""a{0,1}?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ClosedRangeNumericQuantifier> <Text> <TextToken>a</TextToken> </Text> <OpenBraceToken>{</OpenBraceToken> <NumberToken value=""0"">0</NumberToken> <CommaToken>,</CommaToken> <NumberToken value=""1"">1</NumberToken> <CloseBraceToken>}</CloseBraceToken> </ClosedRangeNumericQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0,1}?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier1() { Test(@"""a{""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""a{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier2() { Test(@"""a{0""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a{0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier3() { Test(@"""a{0,""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a{0,"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestIncompleteNumericQuantifier4() { Test(@"""a{0,1""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,1</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0,1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNotNumericQuantifier1() { Test(@"""a{0 }""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a{0 }"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier2() { Test(@"""a{0, }""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0, }"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier3() { Test(@"""a{0 ,}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""a{0 ,}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier4() { Test(@"""a{0 ,1}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>,1}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0 ,1}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier5() { Test(@"""a{0, 1}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>1}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0, 1}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNotNumericQuantifier6() { Test(@"""a{0,1 }""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>a{0,1</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""a{0,1 }"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestLegalOpenCloseBrace1() { Test(@"@""{}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""{}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestLegalOpenCloseBrace2() { Test(@"@""{1, 2}""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{1, 2}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""{1, 2}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestDanglingNumericQuantifier1() { Test(@"@""{1}""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>1}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""{{1}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact, WorkItem(41425, "https://github.com/dotnet/roslyn/issues/41425")] public void TestDanglingNumericQuantifier2() { Test(@"@""{1,2}""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>1,2}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""{{1,2}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestLazyQuantifierDueToIgnoredWhitespace() { Test(@"""a* ?""", @"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>?</QuestionToken> </LazyQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a* ?"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNonLazyQuantifierDueToNonIgnoredWhitespace() { Test(@"""a* ?""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <ZeroOrOneQuantifier> <Text> <TextToken> </TextToken> </Text> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a* ?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifierAtStart() { Test(@"""*""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>*</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""*"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifierAtStartOfGroup() { Test(@"""(*)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>*</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(*)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(*)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAsteriskQuantifierAfterQuantifier() { Test(@"""a**""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>*</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "*")}"" Span=""[11..12)"" Text=""*"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a**"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifierAtStart() { Test(@"""+""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>+</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifierAtStartOfGroup() { Test(@"""(+)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>+</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(+)"" /> <Capture Name=""1"" Span=""[9..12)"" Text=""(+)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPlusQuantifierAfterQuantifier() { Test(@"""a*+""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>+</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "+")}"" Span=""[11..12)"" Text=""+"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""a*+"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifierAtStart() { Test(@"""?""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..10)"" Text=""?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifierAtStartOfGroup() { Test(@"""(?)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestQuestionQuantifierAfterQuantifier() { Test(@"""a*??""", $@"<Tree> <CompilationUnit> <Sequence> <LazyQuantifier> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <QuestionToken>?</QuestionToken> </LazyQuantifier> <Text> <TextToken>?</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "?")}"" Span=""[12..13)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a*??"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericQuantifierAtStart() { Test(@"""{0}""", $@"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[9..10)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""{{0}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericQuantifierAtStartOfGroup() { Test(@"""({0})""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0}}</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[10..11)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""({{0}})"" /> <Capture Name=""1"" Span=""[9..14)"" Text=""({{0}})"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericQuantifierAfterQuantifier() { Test(@"""a*{0}""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken>0}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Nested_quantifier_0, "{")}"" Span=""[11..12)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""a*{{0}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonNumericQuantifierAtStart() { Test(@"""{0""", @"<Tree> <CompilationUnit> <Sequence> <Text> <TextToken>{0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""{0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonNumericQuantifierAtStartOfGroup() { Test(@"""({0)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>{0</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""({0)"" /> <Capture Name=""1"" Span=""[9..13)"" Text=""({0)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonNumericQuantifierAfterQuantifier() { Test(@"""a*{0""", @"<Tree> <CompilationUnit> <Sequence> <ZeroOrMoreQuantifier> <Text> <TextToken>a</TextToken> </Text> <AsteriskToken>*</AsteriskToken> </ZeroOrMoreQuantifier> <Text> <TextToken>{0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""a*{0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEscapeAtEnd1() { Test(@"@""\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[10..11)"" Text=""\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEscapeAtEnd2() { Test(@"""\\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[9..11)"" Text=""\\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..11)"" Text=""\\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestSimpleEscape() { Test(@"@""\w""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\w"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPrimaryEscapes1() { Test(@"@""\b\B\A\G\Z\z\w\W\s\W\s\S\d\D""", @"<Tree> <CompilationUnit> <Sequence> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>B</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>A</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>G</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>Z</TextToken> </AnchorEscape> <AnchorEscape> <BackslashToken>\</BackslashToken> <TextToken>z</TextToken> </AnchorEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>W</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>S</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>d</TextToken> </CharacterClassEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..38)"" Text=""\b\B\A\G\Z\z\w\W\s\W\s\S\d\D"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape1() { Test(@"@""\c""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Missing_control_character}"" Span=""[11..12)"" Text=""c"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\c"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape2() { Test(@"@""\c<""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""&lt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape3() { Test(@"@""\ca""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\ca"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape4() { Test(@"@""\cA""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cA"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape5() { Test(@"@""\c A""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken> A</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\c A"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape6() { Test(@"@""\c(a)""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\c(a)"" /> <Capture Name=""1"" Span=""[12..15)"" Text=""(a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape7() { Test(@"@""\c>""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape8() { Test(@"@""\c?""", $@"<Tree> <CompilationUnit> <Sequence> <ZeroOrOneQuantifier> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <QuestionToken>?</QuestionToken> </ZeroOrOneQuantifier> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""?"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c?"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape9() { Test(@"@""\c@""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>@</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c@"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape10() { Test(@"@""\c^""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>^</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c^"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape11() { Test(@"@""\c_""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>_</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c_"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape12() { Test(@"@""\c`""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>`</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""`"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c`"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape13() { Test(@"@""\c{""", $@"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[12..13)"" Text=""{{"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape14() { Test(@"@""\ca""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\ca"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape15() { Test(@"@""\cA""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cA"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape16() { Test(@"@""\cz""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>z</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cz"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape17() { Test(@"@""\cZ""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>Z</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\cZ"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape18() { Test(@"@""\c\""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>\</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestControlEscape19() { Test(@"@""\c]""", @"<Tree> <CompilationUnit> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>]</TextToken> </ControlEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\c]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnknownEscape1() { Test(@"@""\m""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>m</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "m")}"" Span=""[11..12)"" Text=""m"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\m"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape1() { Test(@"@""\x""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\x"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape2() { Test(@"@""\x """, $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\x "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape3() { Test(@"@""\x0""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>0</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\x0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape4() { Test(@"@""\x0 """, $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>0</TextToken> </HexEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\x0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\x0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape5() { Test(@"@""\x00""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\x00"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape6() { Test(@"@""\x00 """, @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\x00 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape7() { Test(@"@""\x000""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>00</TextToken> </HexEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\x000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape8() { Test(@"@""\xff""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>ff</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xff"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape9() { Test(@"@""\xFF""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>FF</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xFF"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape10() { Test(@"@""\xfF""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>fF</TextToken> </HexEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xfF"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape11() { Test(@"@""\xfff""", @"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>ff</TextToken> </HexEscape> <Text> <TextToken>f</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\xfff"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestHexEscape12() { Test(@"@""\xgg""", $@"<Tree> <CompilationUnit> <Sequence> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken /> </HexEscape> <Text> <TextToken>gg</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\x"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\xgg"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnknownEscape2() { Test(@"@""\m """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>m</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "m")}"" Span=""[11..12)"" Text=""m"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\m "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape1() { Test(@"@""\u""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\u"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape2() { Test(@"@""\u0""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\u0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape3() { Test(@"@""\u00""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>00</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..14)"" Text=""\u00"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\u00"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape4() { Test(@"@""\u000""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>000</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..15)"" Text=""\u000"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\u000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape5() { Test(@"@""\u0000""", @"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\u0000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape6() { Test(@"@""\u0000 """, @"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\u0000 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape7() { Test(@"@""\u """, $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\u "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape8() { Test(@"@""\u0 """, $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..13)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\u0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestUnicodeEscape9() { Test(@"@""\ugggg""", $@"<Tree> <CompilationUnit> <Sequence> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken /> </UnicodeEscape> <Text> <TextToken>gggg</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[10..12)"" Text=""\u"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\ugggg"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape1() { Test(@"@""\0""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape2() { Test(@"@""\0 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape3() { Test(@"@""\00""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>00</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\00"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape4() { Test(@"@""\00 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>00</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\00 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape5() { Test(@"@""\000""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape6() { Test(@"@""\000 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\000 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape7() { Test(@"@""\0000""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\0000"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape8() { Test(@"@""\0000 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\0000 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape9() { Test(@"@""\7""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""7"">7</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 7)}"" Span=""[11..12)"" Text=""7"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\7"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape10() { Test(@"@""\78""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>7</TextToken> </OctalEscape> <Text> <TextToken>8</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\78"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscape11() { Test(@"@""\8""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""8"">8</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 8)}"" Span=""[11..12)"" Text=""8"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\8"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestOctalEscapeEcmascript1() { Test(@"@""\40""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>40</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\40"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript2() { Test(@"@""\401""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>40</TextToken> </OctalEscape> <Text> <TextToken>1</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\401"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript3() { Test(@"@""\37""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>37</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\37"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript4() { Test(@"@""\371""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>371</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\371"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestOctalEscapeEcmascript5() { Test(@"@""\0000""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>000</TextToken> </OctalEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\0000"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEscape1() { Test(@"@""\k""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\k"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape2() { Test(@"@""\k """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape3() { Test(@"@""\k<""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape4() { Test(@"@""\k< """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape5() { Test(@"@""\k<0""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape6() { Test(@"@""\k<0 """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape7() { Test(@"@""\k<0>""", @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape8() { Test(@"@""\k<0> """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape9() { Test(@"@""\k<00> """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\k&lt;00&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape10() { Test(@"@""\k<a> """, $@"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[13..14)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;a&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEscape11() { Test(@"@""(?<a>)\k<a> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?&lt;a&gt;)\k&lt;a&gt; "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureEcmaEscape1() { Test(@"@""\k""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\k"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape2() { Test(@"@""\k """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape3() { Test(@"@""\k<""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k&lt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape4() { Test(@"@""\k< """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape5() { Test(@"@""\k<0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k&lt;0"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape6() { Test(@"@""\k<0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0 "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape7() { Test(@"@""\k<0>""", @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureEcmaEscape8() { Test(@"@""\k<0> """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestKCaptureQuoteEscape3() { Test(@"@""\k'""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_named_back_reference.Replace("<", "&lt;").Replace(">", "&gt;")}"" Span=""[10..12)"" Text=""\k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\k'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape4() { Test(@"@""\k' """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>' </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape5() { Test(@"@""\k'0""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\k'0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape6() { Test(@"@""\k'0 """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k'0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape7() { Test(@"@""\k'0'""", @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\k'0'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape8() { Test(@"@""\k'0' """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k'0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape9() { Test(@"@""\k'00' """, @"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">00</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""\k'00' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape10() { Test(@"@""\k'a' """, $@"<Tree> <CompilationUnit> <Sequence> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[13..14)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k'a' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureQuoteEscape11() { Test(@"@""(?<a>)\k'a' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <KCaptureEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </KCaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?&lt;a&gt;)\k'a' "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureWrongQuote1() { Test(@"@""\k<0' """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>&lt;0' </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k&lt;0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestKCaptureWrongQuote2() { Test(@"@""\k'0> """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>k</TextToken> </SimpleEscape> <Text> <TextToken>'0&gt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unrecognized_escape_sequence_0, "k")}"" Span=""[11..12)"" Text=""k"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\k'0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape1() { Test(@"@""\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[10..11)"" Text=""\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""\"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape2() { Test(@"@""\ """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken> </TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\ "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape3() { Test(@"@""\<""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\&lt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape4() { Test(@"@""\< """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape5() { Test(@"@""\<0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt;0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape6() { Test(@"@""\<0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape7() { Test(@"@""\<0>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape8() { Test(@"@""\<0> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape9() { Test(@"@""\<00> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\&lt;00&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape10() { Test(@"@""\<a> """, $@"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[12..13)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;a&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEscape11() { Test(@"@""(?<a>)\<a> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(?&lt;a&gt;)\&lt;a&gt; "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureEcmaEscape1() { Test(@"@""\""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken /> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Illegal_backslash_at_end_of_pattern}"" Span=""[10..11)"" Text=""\"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""\"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape2() { Test(@"@""\ """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken> </TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\ "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape3() { Test(@"@""\<""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\&lt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape4() { Test(@"@""\< """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape5() { Test(@"@""\<0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\&lt;0"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape6() { Test(@"@""\<0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0 "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape7() { Test(@"@""\<0>""", @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\&lt;0&gt;"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureEcmaEscape8() { Test(@"@""\<0> """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;0&gt; "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCaptureQuoteEscape3() { Test(@"@""\'""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape4() { Test(@"@""\' """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape5() { Test(@"@""\'0""", @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken>0</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\'0"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape6() { Test(@"@""\'0 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\'0 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape7() { Test(@"@""\'0'""", @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""\'0'"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape8() { Test(@"@""\'0' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\'0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape9() { Test(@"@""\'00' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <NumberToken value=""0"">00</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""\'00' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape10() { Test(@"@""\'a' """, $@"<Tree> <CompilationUnit> <Sequence> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_name_0, "a")}"" Span=""[12..13)"" Text=""a"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\'a' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureQuoteEscape11() { Test(@"@""(?<a>)\'a' """, @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureEscape> <BackslashToken>\</BackslashToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> </CaptureEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""(?&lt;a&gt;)\'a' "" /> <Capture Name=""1"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[10..16)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureWrongQuote1() { Test(@"@""\<0' """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>&lt;</TextToken> </SimpleEscape> <Text> <TextToken>0' </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\&lt;0' "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureWrongQuote2() { Test(@"@""\'0> """, @"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>'</TextToken> </SimpleEscape> <Text> <TextToken>0&gt; </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""\'0&gt; "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDefinedCategoryEscape() { Test(@"""\\p{Cc}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Cc</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""\\p{Cc}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDefinedCategoryEscapeWithSpaces1() { Test(@"""\\p{ Cc }""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{ Cc }}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""\\p{{ Cc }}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestDefinedCategoryEscapeWithSpaces2() { Test(@"""\\p{ Cc }""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>Cc</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""\\p{{ Cc }}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestDefinedCategoryEscapeWithSpaces3() { Test(@"""\\p {Cc}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>{{Cc}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""\\p {{Cc}}"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestUndefinedCategoryEscape() { Test(@"""\\p{xxx}""", $@"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>xxx</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "xxx")}"" Span=""[13..16)"" Text=""xxx"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""\\p{{xxx}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape1() { Test(@"""\\p""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""\\p"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape2() { Test(@"""\\p{""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""\\p{{"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape3() { Test(@"""\\p{}""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{}}</TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""\\p{{}}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape4() { Test(@"""\\p{} """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{}} </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unknown_property}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""\\p{{}} "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape5() { Test(@"""\\p {} """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken> {{}} </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""\\p {{}} "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestTooShortCategoryEscape6() { Test(@"""\\p{Cc """, $@"<Tree> <CompilationUnit> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> </SimpleEscape> <Text> <TextToken>{{Cc </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Incomplete_character_escape}"" Span=""[9..12)"" Text=""\\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""\\p{{Cc "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCategoryNameWithDash() { Test(@"""\\p{IsArabicPresentationForms-A}""", @"<Tree> <CompilationUnit> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>IsArabicPresentationForms-A</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""\\p{IsArabicPresentationForms-A}"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping1() { Test(@"""(?:)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?:)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping2() { Test(@"""(?:a)""", @"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?:a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping3() { Test(@"""(?:""", $@"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken /> </NonCapturingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNonCapturingGrouping4() { Test(@"""(?: """, $@"<Tree> <CompilationUnit> <Sequence> <NonCapturingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken /> </NonCapturingGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?: "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestPositiveLookaheadGrouping1() { Test(@"""(?=)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?=)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookaheadGrouping2() { Test(@"""(?=a)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?=a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookaheadGrouping3() { Test(@"""(?=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookaheadGrouping4() { Test(@"""(?= """, $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookaheadGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?= "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNegativeLookaheadGrouping1() { Test(@"""(?!)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?!)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookaheadGrouping2() { Test(@"""(?!a)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?!a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookaheadGrouping3() { Test(@"""(?!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookaheadGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookaheadGrouping4() { Test(@"""(?! """, $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookaheadGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookaheadGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?! "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAtomicGrouping1() { Test(@"""(?>)""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAtomicGrouping2() { Test(@"""(?>a)""", @"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAtomicGrouping3() { Test(@"""(?>""", $@"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </AtomicGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?&gt;"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestAtomicGrouping4() { Test(@"""(?> """, $@"<Tree> <CompilationUnit> <Sequence> <AtomicGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </AtomicGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&gt; "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestPositiveLookbehindGrouping1() { Test(@"""(?<=)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;=)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookbehindGrouping2() { Test(@"""(?<=a)""", @"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;=a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookbehindGrouping3() { Test(@"""(?<=""", $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;="" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestPositiveLookbehindGrouping4() { Test(@"""(?<= """, $@"<Tree> <CompilationUnit> <Sequence> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken /> </PositiveLookbehindGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;= "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNegativeLookbehindGrouping1() { Test(@"""(?<!)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;!)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookbehindGrouping2() { Test(@"""(?<!a)""", @"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;!a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookbehindGrouping3() { Test(@"""(?<!""", $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookbehindGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;!"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegativeLookbehindGrouping4() { Test(@"""(?<! """, $@"<Tree> <CompilationUnit> <Sequence> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken /> </NegativeLookbehindGrouping> </Sequence> <EndOfFile> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;! "" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture1() { Test(@"""(?<""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?&lt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture2() { Test(@"""(?<>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text=""&gt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture3() { Test(@"""(?<a""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;a"" /> <Capture Name=""1"" Span=""[9..13)"" Text=""(?&lt;a"" /> <Capture Name=""a"" Span=""[9..13)"" Text=""(?&lt;a"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture4() { Test(@"""(?<a>""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;a&gt;"" /> <Capture Name=""1"" Span=""[9..14)"" Text=""(?&lt;a&gt;"" /> <Capture Name=""a"" Span=""[9..14)"" Text=""(?&lt;a&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture5() { Test(@"""(?<a>a""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken /> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;a&gt;a"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;a"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;a"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture6() { Test(@"""(?<a>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;a&gt;a)"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;a&gt;a)"" /> <Capture Name=""a"" Span=""[9..16)"" Text=""(?&lt;a&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture7() { Test(@"""(?<a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> &gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNamedCapture8() { Test(@"""(?<a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a &gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture9() { Test(@"""(?< a>a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> a&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt; a&gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNamedCapture10() { Test(@"""(?< a>a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>a&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt; a&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture11() { Test(@"""(?< a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> a &gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt; a &gt;a)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNamedCapture12() { Test(@"""(?< a >a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>a</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[12..13)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt; a &gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedCapture13() { Test(@"""(?<ab>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""ab"">ab</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;ab&gt;a)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;ab&gt;a)"" /> <Capture Name=""ab"" Span=""[9..17)"" Text=""(?&lt;ab&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestZeroNumberCapture() { Test(@"""(?<0>a)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Capture_number_cannot_be_zero}"" Span=""[12..13)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;0&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNumericNumberCapture1() { Test(@"""(?<1>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;1&gt;a)"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;1&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNumericNumberCapture2() { Test(@"""(?<10>a)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""10"">10</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;10&gt;a)"" /> <Capture Name=""10"" Span=""[9..17)"" Text=""(?&lt;10&gt;a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNumericNumberCapture3() { Test(@"""(?<1>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;1&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;1&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericNumberCapture4() { Test(@"""(?<1> )""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNumericNumberCapture6() { Test(@"""(?<1> )""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;1&gt; )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestBalancingGrouping1() { Test(@"""(?<-""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..13)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?&lt;-"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping2() { Test(@"""(?<-0""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;-0"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping3() { Test(@"""(?<-0)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;-0)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping4() { Test(@"""(?<-0>""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;-0&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping5() { Test(@"""(?<-0>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping6() { Test(@"""(?<-0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;-0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping7() { Test(@"""(?<- 0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;- 0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping8() { Test(@"""(?<- 0>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[13..14)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;- 0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping9() { Test(@"""(?<-00>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;-00&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping10() { Test(@"""(?<a-""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..14)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?&lt;a-"" /> <Capture Name=""1"" Span=""[9..14)"" Text=""(?&lt;a-"" /> <Capture Name=""a"" Span=""[9..14)"" Text=""(?&lt;a-"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping11() { Test(@"""(?<a-0""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[9..12)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?&lt;a-0"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a-0"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a-0"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping12() { Test(@"""(?<a-0)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text="")"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;a-0)"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;a-0)"" /> <Capture Name=""a"" Span=""[9..16)"" Text=""(?&lt;a-0)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping13() { Test(@"""(?<a-0>""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;a-0&gt;"" /> <Capture Name=""1"" Span=""[9..16)"" Text=""(?&lt;a-0&gt;"" /> <Capture Name=""a"" Span=""[9..16)"" Text=""(?&lt;a-0&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping14() { Test(@"""(?<a-0>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping15() { Test(@"""(?<a-0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;a-0 &gt;)"" /> <Capture Name=""1"" Span=""[9..18)"" Text=""(?&lt;a-0 &gt;)"" /> <Capture Name=""a"" Span=""[9..18)"" Text=""(?&lt;a-0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping16() { Test(@"""(?<a- 0 >)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0</TextToken> </Text> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..19)"" Text=""(?&lt;a- 0 &gt;)"" /> <Capture Name=""1"" Span=""[9..19)"" Text=""(?&lt;a- 0 &gt;)"" /> <Capture Name=""a"" Span=""[9..19)"" Text=""(?&lt;a- 0 &gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping17() { Test(@"""(?<a- 0>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>0&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[14..15)"" Text="" "" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;a- 0&gt;)"" /> <Capture Name=""1"" Span=""[9..18)"" Text=""(?&lt;a- 0&gt;)"" /> <Capture Name=""a"" Span=""[9..18)"" Text=""(?&lt;a- 0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGrouping18() { Test(@"""(?<a-00>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">00</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;a-00&gt;)"" /> <Capture Name=""1"" Span=""[9..18)"" Text=""(?&lt;a-00&gt;)"" /> <Capture Name=""a"" Span=""[9..18)"" Text=""(?&lt;a-00&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingUndefinedReference1() { Test(@"""(?<-1>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[13..14)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?&lt;-1&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingDefinedReferenceBehind() { Test(@"""()(?<-1>)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""()(?&lt;-1&gt;)"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingDefinedReferenceAhead() { Test(@"""(?<-1>)()""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?&lt;-1&gt;)()"" /> <Capture Name=""1"" Span=""[16..18)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNamedReferenceBehind() { Test(@"""(?<a>)(?<-a>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;a&gt;)(?&lt;-a&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNamedReferenceAhead() { Test(@"""(?<-a>)(?<a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;-a&gt;)(?&lt;a&gt;)"" /> <Capture Name=""1"" Span=""[16..22)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[16..22)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNumberedReferenceBehind() { Test(@"""(?<4>)(?<-4>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;4&gt;)(?&lt;-4&gt;)"" /> <Capture Name=""4"" Span=""[9..15)"" Text=""(?&lt;4&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingNumberedReferenceAhead() { Test(@"""(?<-4>)(?<4>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <NumberToken value=""4"">4</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;-4&gt;)(?&lt;4&gt;)"" /> <Capture Name=""4"" Span=""[16..22)"" Text=""(?&lt;4&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumberedExists() { Test(@"""(?<a>)(?<b>)(?<-1>)(?<-2>)""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..35)"" Text=""(?&lt;a&gt;)(?&lt;b&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""b"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers() { Test(@"""()()(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[38..39)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""()()(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> <Capture Name=""2"" Span=""[11..13)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers1() { Test(@"""()(?<a>)(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[42..43)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""()(?&lt;a&gt;)(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[9..11)"" Text=""()"" /> <Capture Name=""2"" Span=""[11..17)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[11..17)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers2() { Test(@"""(?<a>)()(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[42..43)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;a&gt;)()(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers3() { Test(@"""(?<a>)(?<b>)(?<-0>)(?<-1>)(?<-2>)(?<-3>)""", $@"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[46..47)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..49)"" Text=""(?&lt;a&gt;)(?&lt;b&gt;)(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""2"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""b"" Span=""[15..21)"" Text=""(?&lt;b&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers4() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)()()""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)()()"" /> <Capture Name=""1"" Span=""[37..39)"" Text=""()"" /> <Capture Name=""2"" Span=""[39..41)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers5_1() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)()(?""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[27..28)"" Text=""2"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[39..40)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[40..41)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[41..41)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..41)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)()(?"" /> <Capture Name=""1"" Span=""[37..39)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers5() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)()(?<a>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)()(?&lt;a&gt;)"" /> <Capture Name=""1"" Span=""[37..39)"" Text=""()"" /> <Capture Name=""2"" Span=""[39..45)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[39..45)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers6() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)(?<a>)()""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)(?&lt;a&gt;)()"" /> <Capture Name=""1"" Span=""[43..45)"" Text=""()"" /> <Capture Name=""2"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers7_1() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)(?<a>)(?""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[27..28)"" Text=""2"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[43..44)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[44..45)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[45..45)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..45)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)(?&lt;a&gt;)(?"" /> <Capture Name=""1"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestBalancingGroupingAutoNumbers7() { Test(@"""(?<-0>)(?<-1>)(?<-2>)(?<-3>)(?<a>)(?<b>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""1"">1</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""2"">2</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""3"">3</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 3)}"" Span=""[34..35)"" Text=""3"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..49)"" Text=""(?&lt;-0&gt;)(?&lt;-1&gt;)(?&lt;-2&gt;)(?&lt;-3&gt;)(?&lt;a&gt;)(?&lt;b&gt;)"" /> <Capture Name=""1"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""2"" Span=""[43..49)"" Text=""(?&lt;b&gt;)"" /> <Capture Name=""a"" Span=""[37..43)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""b"" Span=""[43..49)"" Text=""(?&lt;b&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestReferenceToBalancingGroupCaptureName1() { Test(@"""(?<a-0>)(?<b-a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""b"">b</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..25)"" Text=""(?&lt;a-0&gt;)(?&lt;b-a&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""2"" Span=""[17..25)"" Text=""(?&lt;b-a&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""b"" Span=""[17..25)"" Text=""(?&lt;b-a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestReferenceToBalancingGroupCaptureName2() { Test(@"""(?<a-0>)(?<-a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..24)"" Text=""(?&lt;a-0&gt;)(?&lt;-a&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestReferenceToSameBalancingGroup() { Test(@"""(?<a-a>)""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a-a&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-a&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestQuoteNamedCapture() { Test(@"""(?'a')""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?'a')"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?'a')"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?'a')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestQuoteBalancingCapture1() { Test(@"""(?'-0')""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?'-0')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestQuoteBalancingCapture2() { Test(@"""(?'a-0')""", @"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?'a-0')"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?'a-0')"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?'a-0')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestMismatchedOpenCloseCapture1() { Test(@"""(?<a-0')""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <GreaterThanToken /> <Sequence> <Text> <TextToken>'</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text=""'"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?&lt;a-0')"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?&lt;a-0')"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?&lt;a-0')"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestMismatchedOpenCloseCapture2() { Test(@"""(?'a-0>)""", $@"<Tree> <CompilationUnit> <Sequence> <BalancingGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <MinusToken>-</MinusToken> <NumberToken value=""0"">0</NumberToken> <SingleQuoteToken /> <Sequence> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </BalancingGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Invalid_group_name_Group_names_must_begin_with_a_word_character}"" Span=""[15..16)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?'a-0&gt;)"" /> <Capture Name=""1"" Span=""[9..17)"" Text=""(?'a-0&gt;)"" /> <Capture Name=""a"" Span=""[9..17)"" Text=""(?'a-0&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace, allowIndexOutOfRange: true); } [Fact] public void TestConditionalCapture1() { Test(@"""(?(""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..12)"" Text=""(?("" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture2() { Test(@"""(?(0""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken /> <Sequence /> <CloseParenToken /> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed}"" Span=""[12..13)"" Text=""0"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..13)"" Text=""(?(0"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture3() { Test(@"""(?(0)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken /> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(0)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture4() { Test(@"""(?(0))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(0))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture5() { Test(@"""(?(0)a)""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(0)a)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture6() { Test(@"""(?(0)a|)""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(0)a|)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture7() { Test(@"""(?(0)a|b)""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?(0)a|b)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture8() { Test(@"""(?(0)a|b|)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <BarToken>|</BarToken> <Sequence /> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Too_many_bars_in_conditional_grouping}"" Span=""[17..18)"" Text=""|"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..19)"" Text=""(?(0)a|b|)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture9() { Test(@"""(?(0)a|b|c)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken>)</CloseParenToken> <Alternation> <Alternation> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> </Alternation> <BarToken>|</BarToken> <Sequence> <Text> <TextToken>c</TextToken> </Text> </Sequence> </Alternation> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Too_many_bars_in_conditional_grouping}"" Span=""[17..18)"" Text=""|"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..20)"" Text=""(?(0)a|b|c)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture10() { Test(@"""(?(0 )""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">0</NumberToken> <CloseParenToken /> <Sequence /> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Malformed}"" Span=""[12..13)"" Text=""0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(0 )"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture11() { Test(@"""(?(1))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""1"">1</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Reference_to_undefined_group}"" Span=""[12..13)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(1))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestConditionalCapture12() { Test(@"""(?(00))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <NumberToken value=""0"">00</NumberToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(00))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture1() { Test(@"""(?(a))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(a))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture2() { Test(@"""(?<a>)(?(a))""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ConditionalCaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OpenParenToken>(</OpenParenToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <CloseParenToken>)</CloseParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalCaptureGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..21)"" Text=""(?&lt;a&gt;)(?(a))"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture3() { Test(@"""(?<a>)(?(a ))""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseParenToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;a&gt;)(?(a ))"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNamedConditionalCapture4() { Test(@"""(?<a>)(?( a))""", @"<Tree> <CompilationUnit> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken> <Trivia> <WhitespaceTrivia> </WhitespaceTrivia> </Trivia>a</TextToken> </Text> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..22)"" Text=""(?&lt;a&gt;)(?( a))"" /> <Capture Name=""1"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> <Capture Name=""a"" Span=""[9..15)"" Text=""(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestNestedGroupsInConditionalGrouping1() { Test(@"""(?(()a()))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Text> <TextToken>a</TextToken> </Text> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..19)"" Text=""(?(()a()))"" /> <Capture Name=""1"" Span=""[12..14)"" Text=""()"" /> <Capture Name=""2"" Span=""[15..17)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNestedGroupsInConditionalGrouping2() { Test(@"""(?((?<x>)a(?<y>)))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""x"">x</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Text> <TextToken>a</TextToken> </Text> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""y"">y</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> </Sequence> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..27)"" Text=""(?((?&lt;x&gt;)a(?&lt;y&gt;)))"" /> <Capture Name=""1"" Span=""[12..18)"" Text=""(?&lt;x&gt;)"" /> <Capture Name=""2"" Span=""[19..25)"" Text=""(?&lt;y&gt;)"" /> <Capture Name=""x"" Span=""[12..18)"" Text=""(?&lt;x&gt;)"" /> <Capture Name=""y"" Span=""[19..25)"" Text=""(?&lt;y&gt;)"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptureInConditionalGrouping1() { Test(@"""(?(?'""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken /> <SingleQuoteToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..14)"" Text=""(?'"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(?'"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCaptureInConditionalGrouping2() { Test(@"""(?(?'x'))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SingleQuoteToken>'</SingleQuoteToken> <CaptureNameToken value=""x"">x</CaptureNameToken> <SingleQuoteToken>'</SingleQuoteToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?(?'x'))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCommentInConditionalGrouping1() { Test(@"""(?(?#""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>#</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_regex_comment}"" Span=""[11..14)"" Text=""(?#"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..12)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[12..13)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(?#"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCommentInConditionalGrouping2() { Test(@"""(?(?#)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>#)</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..12)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[12..13)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(?#)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestCommentInConditionalGrouping3() { Test(@"""(?(?#))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence> <Text> <TextToken>?</TextToken> </Text> </Sequence> <CloseParenToken /> </SimpleGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile> <Trivia> <CommentTrivia>#))</CommentTrivia> </Trivia> </EndOfFile> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_cannot_be_comments}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..12)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Quantifier_x_y_following_nothing}"" Span=""[12..13)"" Text=""?"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(?#))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping1() { Test(@"""(?(?<""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken /> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..14)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..14)"" Text=""(?(?&lt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping2() { Test(@"""(?(?<a""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken /> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_grouping_construct}"" Span=""[11..14)"" Text=""(?&lt;"" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..15)"" Text=""(?(?&lt;a"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping3() { Test(@"""(?(?<a>""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken /> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..16)"" Text=""(?(?&lt;a&gt;"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping4() { Test(@"""(?(?<a>)""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence /> <CloseParenToken /> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> <Diagnostic Message=""{FeaturesResources.Not_enough_close_parens}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(?&lt;a&gt;)"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestAngleCaptureInConditionalGrouping5() { Test(@"""(?(?<a>))""", $@"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <CaptureGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <CaptureNameToken value=""a"">a</CaptureNameToken> <GreaterThanToken>&gt;</GreaterThanToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </CaptureGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Alternation_conditions_do_not_capture_and_cannot_be_named}"" Span=""[9..10)"" Text=""("" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[9..18)"" Text=""(?(?&lt;a&gt;))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestLookbehindAssertionInConditionalGrouping1() { Test(@"""(?(?<=))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <PositiveLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <EqualsToken>=</EqualsToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </PositiveLookbehindGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(?&lt;=))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestLookbehindAssertionInConditionalGrouping2() { Test(@"""(?(?<!))""", @"<Tree> <CompilationUnit> <Sequence> <ConditionalExpressionGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <NegativeLookbehindGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <LessThanToken>&lt;</LessThanToken> <ExclamationToken>!</ExclamationToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NegativeLookbehindGrouping> <Sequence /> <CloseParenToken>)</CloseParenToken> </ConditionalExpressionGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[9..17)"" Text=""(?(?&lt;!))"" /> </Captures> </Tree>", RegexOptions.IgnorePatternWhitespace); } [Fact] public void TestBackreference1() { Test(@"@""\1""", $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[11..12)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\1"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference2() { Test(@"@""\1 """, $@"<Tree> <CompilationUnit> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[11..12)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\1 "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference3() { Test(@"@""()\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference4() { Test(@"@""()\1 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""()\1 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestBackreference5() { Test(@"@""()\10 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>10</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()\10 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestEcmascriptBackreference1() { Test(@"@""\1""", @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""\1"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference2() { Test(@"@""\1 """, @"<Tree> <CompilationUnit> <Sequence> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""\1 "" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference3() { Test(@"@""()\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmaBackreference4() { Test(@"@""()\1 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""()\1 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference5() { Test(@"@""()\10 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""10"">1</NumberToken> </BackreferenceEscape> <Text> <TextToken>0 </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()\10 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestEcmascriptBackreference6() { Test(@"@""()()()()()()()()()()\10 """, @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""10"">10</NumberToken> </BackreferenceEscape> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..34)"" Text=""()()()()()()()()()()\10 "" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> <Capture Name=""3"" Span=""[14..16)"" Text=""()"" /> <Capture Name=""4"" Span=""[16..18)"" Text=""()"" /> <Capture Name=""5"" Span=""[18..20)"" Text=""()"" /> <Capture Name=""6"" Span=""[20..22)"" Text=""()"" /> <Capture Name=""7"" Span=""[22..24)"" Text=""()"" /> <Capture Name=""8"" Span=""[24..26)"" Text=""()"" /> <Capture Name=""9"" Span=""[26..28)"" Text=""()"" /> <Capture Name=""10"" Span=""[28..30)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ECMAScript); } [Fact] public void TestCharacterClass1() { Test(@"@""[""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence /> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[11..11)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..11)"" Text=""["" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass2() { Test(@"@""[ """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[ "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass3() { Test(@"@""[]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>]</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..12)"" Text=""[]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass4() { Test(@"@""[] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>] </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass5() { Test(@"@""[a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass6() { Test(@"@""[a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass7() { Test(@"@""[a-""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken /> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[13..13)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a-"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass8() { Test(@"@""[a- """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken> </TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[14..14)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[a- "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass9() { Test(@"@""[a-]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[a-]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass10() { Test(@"@""[a-] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a-</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass11() { Test(@"@""[a-b]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-b]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass12() { Test(@"@""[a-b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass13() { Test(@"@""[a-[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass14() { Test(@"@""[a-b-[c]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>c</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-b-[c]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass15() { Test(@"@""[a-[b]-c] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> <Text> <TextToken>-c</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[12..12)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-[b]-c] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass16() { Test(@"@""[[a]-b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>-b] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[[a]-b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass17() { Test(@"@""[[a]-[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>-</TextToken> </Text> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[[a]-[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass18() { Test(@"@""[\w-a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\w-a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass19() { Test(@"@""[a-\w] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>w</TextToken> </CharacterClassEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "w")}"" Span=""[13..15)"" Text=""\w"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-\w] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass20() { Test(@"@""[\p{llll}-a] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>llll</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Unknown_property_0, "llll")}"" Span=""[14..18)"" Text=""llll"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""[\p{{llll}}-a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass21() { Test(@"@""[\p{Lu}-a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[\p{Lu}-a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass22() { Test(@"@""[a-\p{Lu}] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}}</CloseBraceToken> </CategoryEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Cannot_include_class_0_in_character_range, "p")}"" Span=""[13..15)"" Text=""\p"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-\p{{Lu}}] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass23() { Test(@"@""[a-[:Ll:]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:Ll:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..21)"" Text=""[a-[:Ll:]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass24() { Test(@"@""[a-[:Ll]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:Ll</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-[:Ll]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass25() { Test(@"@""[a-[:""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-[:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass26() { Test(@"@""[a-[:L""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:L</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-[:L"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass27() { Test(@"@""[a-[:L:""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:L:</TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-[:L:"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass28() { Test(@"@""[a-[:L:]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:L:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[18..18)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-[:L:]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass29() { Test(@"@""[\-]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""[\-]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass30() { Test(@"@""[a-b-c] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>-c</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-b-c] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass31() { Test(@"@""[-b-c] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>c</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[-b-c] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass32() { Test(@"@""[-[b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-[b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[-[b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass33() { Test(@"@""[-[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-[b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[-[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass34() { Test(@"@""[--b """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>-</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[15..15)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[--b "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass35() { Test(@"@""[--b] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>-</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>b</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[--b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass36() { Test(@"@""[--[b """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[16..16)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[--[b "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass37() { Test(@"@""[--[b] """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> <Text> <TextToken> </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.A_subtraction_must_be_the_last_element_in_a_character_class}"" Span=""[12..12)"" Text="""" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[--[b] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass38() { Test(@"@""[--[b]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>-</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[--[b]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass39() { Test(@"@""[a--[b """, $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>[b </TextToken> </Text> </Sequence> <CloseBracketToken /> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> <Diagnostic Message=""{FeaturesResources.Unterminated_character_class_set}"" Span=""[17..17)"" Text="""" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a--[b "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass40() { Test(@"@""[,--[a] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>,</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken> </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[,--[a] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass41() { Test(@"@""[,--[a]] """, @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>,</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> <Text> <TextToken>[a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> <Text> <TextToken>] </TextToken> </Text> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[,--[a]] "" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass42() { Test(@"@""[\s-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>s</TextToken> </CharacterClassEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\s-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass43() { Test(@"@""[\p{Lu}-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[\p{Lu}-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClass44() { Test(@"@""[\p{Lu}-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CategoryEscape> <BackslashToken>\</BackslashToken> <TextToken>p</TextToken> <OpenBraceToken>{</OpenBraceToken> <EscapeCategoryToken>Lu</EscapeCategoryToken> <CloseBraceToken>}</CloseBraceToken> </CategoryEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[\p{Lu}-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestNegatedCharacterClass1() { Test(@"@""[a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..13)"" Text=""[a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange1() { Test(@"@""[\c<-\c>]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <CharacterClassRange> <Text> <TextToken>&lt;</TextToken> </Text> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[13..14)"" Text=""&lt;"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[17..18)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\c&lt;-\c&gt;]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange2() { Test(@"@""[\c>-\c<]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </CharacterClassRange> <Text> <TextToken>&lt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[13..14)"" Text=""&gt;"" /> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[17..18)"" Text=""&lt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\c&gt;-\c&lt;]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange3() { Test(@"@""[\c>-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> <CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[13..14)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\c&gt;-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange4() { Test(@"@""[a-\c>]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken /> </ControlEscape> </CharacterClassRange> <Text> <TextToken>&gt;</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Unrecognized_control_character}"" Span=""[15..16)"" Text=""&gt;"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-\c&gt;]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange5() { Test(@"@""[a--]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>-</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a--]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange6() { Test(@"@""[--a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>-</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[--a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange7() { Test(@"@""[a-\-]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-\-]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange8() { Test(@"@""[\--a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\--a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange9() { Test(@"@""[\0-\1]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\0-\1]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange10() { Test(@"@""[\1-\0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>1</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[13..14)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[\1-\0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange11() { Test(@"@""[\0-\01]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>01</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\0-\01]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange12() { Test(@"@""[\01-\0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>01</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\01-\0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange13() { Test(@"@""[[:x:]-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <PosixProperty> <TextToken>[:x:]</TextToken> </PosixProperty> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[[:x:]-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange14() { Test(@"@""[a-[:x:]]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassSubtraction> <MinusToken>-</MinusToken> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>:x:</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </CharacterClassSubtraction> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-[:x:]]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange15() { Test(@"@""[\0-\ca]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\0-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange16() { Test(@"@""[\ca-\0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>0</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\ca-\0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange17() { Test(@"@""[\ca-\cA]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\ca-\cA]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange18() { Test(@"@""[\cA-\ca]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cA-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange19() { Test(@"@""[\u0-\u1]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>1</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[11..14)"" Text=""\u0"" /> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[15..18)"" Text=""\u1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\u0-\u1]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange20() { Test(@"@""[\u1-\u0]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>1</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[11..14)"" Text=""\u1"" /> <Diagnostic Message=""{FeaturesResources.Insufficient_hexadecimal_digits}"" Span=""[15..18)"" Text=""\u0"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\u1-\u0]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange21() { Test(@"@""[\u0000-\u0000]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""[\u0000-\u0000]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange22() { Test(@"@""[\u0000-\u0001]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""[\u0000-\u0001]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange23() { Test(@"@""[\u0001-\u0000]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0000</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[17..18)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..25)"" Text=""[\u0001-\u0000]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange24() { Test(@"@""[\u0001-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[\u0001-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange25() { Test(@"@""[a-\u0001]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <UnicodeEscape> <BackslashToken>\</BackslashToken> <TextToken>u</TextToken> <TextToken>0001</TextToken> </UnicodeEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-\u0001]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange26() { Test(@"@""[a-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange27() { Test(@"@""[a-A]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>A</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-A]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange28() { Test(@"@""[A-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[A-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange29() { Test(@"@""[a-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-a]"" /> </Captures> </Tree>", RegexOptions.IgnoreCase); } [Fact] public void TestCharacterClassRange30() { Test(@"@""[a-A]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>A</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[a-A]"" /> </Captures> </Tree>", RegexOptions.IgnoreCase); } [Fact] public void TestCharacterClassRange31() { Test(@"@""[A-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>A</TextToken> </Text> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..15)"" Text=""[A-a]"" /> </Captures> </Tree>", RegexOptions.IgnoreCase); } [Fact] public void TestCharacterClassRange32() { Test(@"@""[a-\x61]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>61</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\x61]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange33() { Test(@"@""[\x61-a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>61</TextToken> </HexEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\x61-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange34() { Test(@"@""[a-\x60]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>60</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\x60]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange35() { Test(@"@""[\x62-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>62</TextToken> </HexEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[15..16)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\x62-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange36() { Test(@"@""[a-\x62]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>62</TextToken> </HexEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\x62]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange37() { Test(@"@""[\x62-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <HexEscape> <BackslashToken>\</BackslashToken> <TextToken>x</TextToken> <TextToken>62</TextToken> </HexEscape> <MinusToken>-</MinusToken> <Text> <TextToken>a</TextToken> </Text> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[15..16)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\x62-a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange38() { Test(@"@""[\3-\cc]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>3</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\3-\cc]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange39() { Test(@"@""[\cc-\3]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>3</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\cc-\3]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange40() { Test(@"@""[\2-\cc]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>2</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\2-\cc]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange41() { Test(@"@""[\cc-\2]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>2</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\cc-\2]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange42() { Test(@"@""[\4-\cc]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>4</TextToken> </OctalEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[13..14)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\4-\cc]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange43() { Test(@"@""[\cc-\4]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>c</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <OctalEscape> <BackslashToken>\</BackslashToken> <TextToken>4</TextToken> </OctalEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[\cc-\4]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange44() { Test(@"@""[\ca-\cb]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\ca-\cb]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange45() { Test(@"@""[\ca-\cB]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\ca-\cB]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange46() { Test(@"@""[\cA-\cb]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cA-\cb]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange47() { Test(@"@""[\cA-\cB]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cA-\cB]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange48() { Test(@"@""[\cb-\ca]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cb-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange49() { Test(@"@""[\cb-\cA]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>b</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cb-\cA]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange50() { Test(@"@""[\cB-\ca]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>a</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cB-\ca]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange51() { Test(@"@""[\cB-\cA]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>B</TextToken> </ControlEscape> <MinusToken>-</MinusToken> <ControlEscape> <BackslashToken>\</BackslashToken> <TextToken>c</TextToken> <TextToken>A</TextToken> </ControlEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[14..15)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[\cB-\cA]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange52() { Test(@"@""[\--a]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>-a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\--a]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange53() { Test(@"@""[\--#]""", @"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>-#</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[\--#]"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCharacterClassRange54() { Test(@"@""[a-\-]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""[a-\-]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange55() { Test(@"@""[a-\-b]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[a-\-b]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange56() { Test(@"@""[a-\-\-b]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>b</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a-\-\-b]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange57() { Test(@"@""[b-\-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..17)"" Text=""[b-\-a]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange58() { Test(@"@""[b-\-\-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[b-\-\-a]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange59() { Test(@"@""[a-\-\D]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[a-\-\D]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange60() { Test(@"@""[a-\-\-\D]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> <CharacterClassEscape> <BackslashToken>\</BackslashToken> <TextToken>D</TextToken> </CharacterClassEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[12..13)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..20)"" Text=""[a-\-\-\D]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange61() { Test(@"@""[a -\-\b]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassRange> <Text> <TextToken> </TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>b</TextToken> </SimpleEscape> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..19)"" Text=""[a -\-\b]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCharacterClassRange62() { Test(@"@""[ab-\-a]""", $@"<Tree> <CompilationUnit> <Sequence> <CharacterClass> <OpenBracketToken>[</OpenBracketToken> <Sequence> <Text> <TextToken>a</TextToken> </Text> <CharacterClassRange> <Text> <TextToken>b</TextToken> </Text> <MinusToken>-</MinusToken> <SimpleEscape> <BackslashToken>\</BackslashToken> <TextToken>-</TextToken> </SimpleEscape> </CharacterClassRange> <Text> <TextToken>a</TextToken> </Text> </Sequence> <CloseBracketToken>]</CloseBracketToken> </CharacterClass> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{FeaturesResources.x_y_range_in_reverse_order}"" Span=""[13..14)"" Text=""-"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..18)"" Text=""[ab-\-a]"" /> </Captures> </Tree>", RegexOptions.None, allowDiagnosticsMismatch: true); } [Fact] public void TestCaptures1() { Test(@"@""()\1""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures2() { Test(@"@""()\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[13..14)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures3() { Test(@"@""()()\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()()\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures4() { Test(@"@""()\1""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[13..14)"" Text=""1"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\1"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures5() { Test(@"@""()\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[13..14)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..14)"" Text=""()\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures6() { Test(@"@""()()\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[15..16)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..16)"" Text=""()()\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures7() { Test(@"@""()()(?n)\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()()(?n)\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures8() { Test(@"@""()(?n)()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()(?n)()\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures9() { Test(@"@""(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures10() { Test(@"@""()()(?n)\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()()(?n)\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures11() { Test(@"@""()(?n)()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""()(?n)()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures12() { Test(@"@""(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..22)"" Text=""(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures13() { Test(@"@""()()(?-n)\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?-n)\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures14() { Test(@"@""()(?-n)()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()(?-n)()\1\2"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures15() { Test(@"@""(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures16() { Test(@"@""()()(?-n)\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[20..21)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?-n)\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures17() { Test(@"@""()(?-n)()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()(?-n)()\1\2"" /> <Capture Name=""1"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures18() { Test(@"@""(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures19() { Test(@"@""()()(?n:\1\2)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?n:\1\2)"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures20() { Test(@"@""()()(?n:\1\2)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[19..20)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[21..22)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""()()(?n:\1\2)"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures21() { Test(@"@""()()(?-n:\1\2)""", @"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""()()(?-n:\1\2)"" /> <Capture Name=""1"" Span=""[10..12)"" Text=""()"" /> <Capture Name=""2"" Span=""[12..14)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures22() { Test(@"@""()()(?-n:\1\2)""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[20..21)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""()()(?-n:\1\2)"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures23() { Test(@"@""(?n:)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?n:)()()\1\2"" /> <Capture Name=""1"" Span=""[15..17)"" Text=""()"" /> <Capture Name=""2"" Span=""[17..19)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures24() { Test(@"@""(?n:)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[20..21)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[22..23)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..23)"" Text=""(?n:)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures25() { Test(@"@""(?-n:)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?-n:)()()\1\2"" /> <Capture Name=""1"" Span=""[16..18)"" Text=""()"" /> <Capture Name=""2"" Span=""[18..20)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures26() { Test(@"@""(?-n:)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <NestedOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <ColonToken>:</ColonToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </NestedOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[21..22)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[23..24)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..24)"" Text=""(?-n:)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures27() { Test(@"@""(?n)(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?n)(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[19..21)"" Text=""()"" /> <Capture Name=""2"" Span=""[21..23)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures28() { Test(@"@""(?n)(?-n)()()\1\2""", @"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?n)(?-n)()()\1\2"" /> <Capture Name=""1"" Span=""[19..21)"" Text=""()"" /> <Capture Name=""2"" Span=""[21..23)"" Text=""()"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } [Fact] public void TestCaptures29() { Test(@"@""(?-n)(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[24..25)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[26..27)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?-n)(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.None); } [Fact] public void TestCaptures30() { Test(@"@""(?-n)(?n)()()\1\2""", $@"<Tree> <CompilationUnit> <Sequence> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>-n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleOptionsGrouping> <OpenParenToken>(</OpenParenToken> <QuestionToken>?</QuestionToken> <OptionsToken>n</OptionsToken> <CloseParenToken>)</CloseParenToken> </SimpleOptionsGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <SimpleGrouping> <OpenParenToken>(</OpenParenToken> <Sequence /> <CloseParenToken>)</CloseParenToken> </SimpleGrouping> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""1"">1</NumberToken> </BackreferenceEscape> <BackreferenceEscape> <BackslashToken>\</BackslashToken> <NumberToken value=""2"">2</NumberToken> </BackreferenceEscape> </Sequence> <EndOfFile /> </CompilationUnit> <Diagnostics> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 1)}"" Span=""[24..25)"" Text=""1"" /> <Diagnostic Message=""{string.Format(FeaturesResources.Reference_to_undefined_group_number_0, 2)}"" Span=""[26..27)"" Text=""2"" /> </Diagnostics> <Captures> <Capture Name=""0"" Span=""[10..27)"" Text=""(?-n)(?n)()()\1\2"" /> </Captures> </Tree>", RegexOptions.ExplicitCapture); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Def/Implementation/UnusedReferences/Dialog/RemoveUnusedReferencesDialogProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog { [Export(typeof(RemoveUnusedReferencesDialogProvider)), Shared] internal class RemoveUnusedReferencesDialogProvider { private readonly UnusedReferencesTableProvider _tableProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoveUnusedReferencesDialogProvider(UnusedReferencesTableProvider tableProvider) { _tableProvider = tableProvider; } public RemoveUnusedReferencesDialog CreateDialog() => new(_tableProvider); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.VisualStudio.LanguageServices.Implementation.UnusedReferences.Dialog { [Export(typeof(RemoveUnusedReferencesDialogProvider)), Shared] internal class RemoveUnusedReferencesDialogProvider { private readonly UnusedReferencesTableProvider _tableProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoveUnusedReferencesDialogProvider(UnusedReferencesTableProvider tableProvider) { _tableProvider = tableProvider; } public RemoveUnusedReferencesDialog CreateDialog() => new(_tableProvider); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/VisualStudio/Core/Impl/Options/NotificationOptionViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Represents a view model for <see cref="NotificationOption"/> /// </summary> internal class NotificationOptionViewModel { public NotificationOptionViewModel(NotificationOption notification, ImageMoniker moniker) { Notification = notification; Name = notification.Name; Moniker = moniker; } public ImageMoniker Moniker { get; } public string Name { get; } public NotificationOption Notification { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { /// <summary> /// Represents a view model for <see cref="NotificationOption"/> /// </summary> internal class NotificationOptionViewModel { public NotificationOptionViewModel(NotificationOption notification, ImageMoniker moniker) { Notification = notification; Name = notification.Name; Moniker = moniker; } public ImageMoniker Moniker { get; } public string Name { get; } public NotificationOption Notification { get; } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Features/Core/Portable/MetadataAsSource/AbstractMetadataAsSourceService+CompatAbstractMetadataFormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { protected abstract class CompatAbstractMetadataFormattingRule : AbstractMetadataFormattingRule { #pragma warning disable CS0809 // Obsolete member overrides non-obsolete member [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddSuppressOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddAnchorIndentationOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddIndentBlockOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddAlignTokensOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { var previousTokenCopy = previousToken; var currentTokenCopy = currentToken; var nextOperationCopy = nextOperation; return GetAdjustNewLinesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { var previousTokenCopy = previousToken; var currentTokenCopy = currentToken; var nextOperationCopy = nextOperation; return GetAdjustSpacesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy); } #pragma warning restore CS0809 // Obsolete member overrides non-obsolete member /// <summary> /// Returns SuppressWrappingIfOnSingleLineOperations under a node either by itself or by /// filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddSuppressOperationsSlow(List<SuppressOperation> list, SyntaxNode node, ref NextSuppressOperationAction nextOperation) => base.AddSuppressOperations(list, node, in nextOperation); /// <summary> /// returns AnchorIndentationOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAnchorIndentationOperationsSlow(List<AnchorIndentationOperation> list, SyntaxNode node, ref NextAnchorIndentationOperationAction nextOperation) => base.AddAnchorIndentationOperations(list, node, in nextOperation); /// <summary> /// returns IndentBlockOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddIndentBlockOperationsSlow(List<IndentBlockOperation> list, SyntaxNode node, ref NextIndentBlockOperationAction nextOperation) => base.AddIndentBlockOperations(list, node, in nextOperation); /// <summary> /// returns AlignTokensOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAlignTokensOperationsSlow(List<AlignTokensOperation> list, SyntaxNode node, ref NextAlignTokensOperationAction nextOperation) => base.AddAlignTokensOperations(list, node, in nextOperation); /// <summary> /// returns AdjustNewLinesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustNewLinesOperation GetAdjustNewLinesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustNewLinesOperation nextOperation) => base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); /// <summary> /// returns AdjustSpacesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustSpacesOperation GetAdjustSpacesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustSpacesOperation nextOperation) => base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.ComponentModel; using Microsoft.CodeAnalysis.Formatting.Rules; namespace Microsoft.CodeAnalysis.MetadataAsSource { internal partial class AbstractMetadataAsSourceService { protected abstract class CompatAbstractMetadataFormattingRule : AbstractMetadataFormattingRule { #pragma warning disable CS0809 // Obsolete member overrides non-obsolete member [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddSuppressOperations(List<SuppressOperation> list, SyntaxNode node, in NextSuppressOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddSuppressOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddAnchorIndentationOperations(List<AnchorIndentationOperation> list, SyntaxNode node, in NextAnchorIndentationOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddAnchorIndentationOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddIndentBlockOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override void AddAlignTokensOperations(List<AlignTokensOperation> list, SyntaxNode node, in NextAlignTokensOperationAction nextOperation) { var nextOperationCopy = nextOperation; AddAlignTokensOperationsSlow(list, node, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { var previousTokenCopy = previousToken; var currentTokenCopy = currentToken; var nextOperationCopy = nextOperation; return GetAdjustNewLinesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy); } [Obsolete("Do not call this method directly (it will Stack Overflow).", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public sealed override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { var previousTokenCopy = previousToken; var currentTokenCopy = currentToken; var nextOperationCopy = nextOperation; return GetAdjustSpacesOperationSlow(ref previousTokenCopy, ref currentTokenCopy, ref nextOperationCopy); } #pragma warning restore CS0809 // Obsolete member overrides non-obsolete member /// <summary> /// Returns SuppressWrappingIfOnSingleLineOperations under a node either by itself or by /// filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddSuppressOperationsSlow(List<SuppressOperation> list, SyntaxNode node, ref NextSuppressOperationAction nextOperation) => base.AddSuppressOperations(list, node, in nextOperation); /// <summary> /// returns AnchorIndentationOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAnchorIndentationOperationsSlow(List<AnchorIndentationOperation> list, SyntaxNode node, ref NextAnchorIndentationOperationAction nextOperation) => base.AddAnchorIndentationOperations(list, node, in nextOperation); /// <summary> /// returns IndentBlockOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddIndentBlockOperationsSlow(List<IndentBlockOperation> list, SyntaxNode node, ref NextIndentBlockOperationAction nextOperation) => base.AddIndentBlockOperations(list, node, in nextOperation); /// <summary> /// returns AlignTokensOperations under a node either by itself or by filtering/replacing operations returned by NextOperation /// </summary> public virtual void AddAlignTokensOperationsSlow(List<AlignTokensOperation> list, SyntaxNode node, ref NextAlignTokensOperationAction nextOperation) => base.AddAlignTokensOperations(list, node, in nextOperation); /// <summary> /// returns AdjustNewLinesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustNewLinesOperation GetAdjustNewLinesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustNewLinesOperation nextOperation) => base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); /// <summary> /// returns AdjustSpacesOperation between two tokens either by itself or by filtering/replacing a operation returned by NextOperation /// </summary> public virtual AdjustSpacesOperation GetAdjustSpacesOperationSlow(ref SyntaxToken previousToken, ref SyntaxToken currentToken, ref NextGetAdjustSpacesOperation nextOperation) => base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/Structure/SimpleLambdaExpressionStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class SimpleLambdaExpressionStructureTests : AbstractCSharpSyntaxNodeStructureTests<SimpleLambdaExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new SimpleLambdaExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambda() { const string code = @" class C { void M() { {|hint:$$f => {|textspan:{ x(); };|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInForLoop() { const string code = @" class C { void M() { for (Action a = x$$ => { }; true; a()) { } } }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall1() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$x => {|textspan:{ return x; }|}|}, ""other arguments}""); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall2() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$x => {|textspan:{ return x; }|}|}); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public class SimpleLambdaExpressionStructureTests : AbstractCSharpSyntaxNodeStructureTests<SimpleLambdaExpressionSyntax> { internal override AbstractSyntaxStructureProvider CreateProvider() => new SimpleLambdaExpressionStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambda() { const string code = @" class C { void M() { {|hint:$$f => {|textspan:{ x(); };|}|} } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInForLoop() { const string code = @" class C { void M() { for (Action a = x$$ => { }; true; a()) { } } }"; await VerifyNoBlockSpansAsync(code); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall1() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$x => {|textspan:{ return x; }|}|}, ""other arguments}""); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } [Fact, Trait(Traits.Feature, Traits.Features.Outlining)] public async Task TestLambdaInMethodCall2() { const string code = @" class C { void M() { someMethod(42, ""test"", false, {|hint:$$x => {|textspan:{ return x; }|}|}); } }"; await VerifyBlockSpansAsync(code, Region("textspan", "hint", CSharpStructureHelpers.Ellipsis, autoCollapse: false)); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveConfusingSuppression), Shared] internal sealed partial class CSharpRemoveConfusingSuppressionCodeFixProvider : CodeFixProvider { public const string RemoveOperator = nameof(RemoveOperator); public const string NegateExpression = nameof(NegateExpression); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpRemoveConfusingSuppressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Remove_operator_preserves_semantics, c => FixAllAsync(document, diagnostics, negate: false, c), RemoveOperator), context.Diagnostics); context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Negate_expression_changes_semantics, c => FixAllAsync(document, diagnostics, negate: true, c), NegateExpression), context.Diagnostics); return Task.CompletedTask; } private static async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, bool negate, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var generator = editor.Generator; var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var node = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); Debug.Assert(node.IsKind(SyntaxKind.IsExpression) || node.IsKind(SyntaxKind.IsPatternExpression)); // Negate the result if requested. var updatedNode = negate ? generator.Negate(generatorInternal, node, semanticModel, cancellationToken) : node; var isNode = updatedNode.DescendantNodesAndSelf().First( n => n.IsKind(SyntaxKind.IsExpression) || n.IsKind(SyntaxKind.IsPatternExpression)); var left = isNode switch { BinaryExpressionSyntax binary => binary.Left, IsPatternExpressionSyntax isPattern => isPattern.Expression, _ => throw ExceptionUtilities.UnexpectedValue(node), }; // Remove the suppression operator. var suppression = (PostfixUnaryExpressionSyntax)left; var withoutSuppression = suppression.Operand.WithAppendedTrailingTrivia(suppression.OperatorToken.GetAllTrivia()); var isWithoutSuppression = updatedNode.ReplaceNode(suppression, withoutSuppression); editor.ReplaceNode(node, isWithoutSuppression); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } public override FixAllProvider GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync( document, diagnostics, context.CodeActionEquivalenceKey == NegateExpression, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveConfusingSuppression), Shared] internal sealed partial class CSharpRemoveConfusingSuppressionCodeFixProvider : CodeFixProvider { public const string RemoveOperator = nameof(RemoveOperator); public const string NegateExpression = nameof(NegateExpression); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpRemoveConfusingSuppressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Remove_operator_preserves_semantics, c => FixAllAsync(document, diagnostics, negate: false, c), RemoveOperator), context.Diagnostics); context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Negate_expression_changes_semantics, c => FixAllAsync(document, diagnostics, negate: true, c), NegateExpression), context.Diagnostics); return Task.CompletedTask; } private static async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, bool negate, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var generator = editor.Generator; var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var node = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); Debug.Assert(node.IsKind(SyntaxKind.IsExpression) || node.IsKind(SyntaxKind.IsPatternExpression)); // Negate the result if requested. var updatedNode = negate ? generator.Negate(generatorInternal, node, semanticModel, cancellationToken) : node; var isNode = updatedNode.DescendantNodesAndSelf().First( n => n.IsKind(SyntaxKind.IsExpression) || n.IsKind(SyntaxKind.IsPatternExpression)); var left = isNode switch { BinaryExpressionSyntax binary => binary.Left, IsPatternExpressionSyntax isPattern => isPattern.Expression, _ => throw ExceptionUtilities.UnexpectedValue(node), }; // Remove the suppression operator. var suppression = (PostfixUnaryExpressionSyntax)left; var withoutSuppression = suppression.Operand.WithAppendedTrailingTrivia(suppression.OperatorToken.GetAllTrivia()); var isWithoutSuppression = updatedNode.ReplaceNode(suppression, withoutSuppression); editor.ReplaceNode(node, isWithoutSuppression); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } public override FixAllProvider GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync( document, diagnostics, context.CodeActionEquivalenceKey == NegateExpression, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/BadHintPath.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp"> <HintPath>BadHintPath.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.6</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp"> <HintPath>BadHintPath.dll</HintPath> </Reference> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/Core/Implementation/InlineRename/Taggers/ClassificationTypeDefinitions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal sealed class ClassificationTypeDefinitions { // Only used for theming, does not need localized public const string InlineRenameField = "Inline Rename Field Text"; [Export] [Name(InlineRenameField)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal readonly ClassificationTypeDefinition? InlineRenameFieldTypeDefinition; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel.Composition; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal sealed class ClassificationTypeDefinitions { // Only used for theming, does not need localized public const string InlineRenameField = "Inline Rename Field Text"; [Export] [Name(InlineRenameField)] [BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)] internal readonly ClassificationTypeDefinition? InlineRenameFieldTypeDefinition; } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest/EditAndContinue/StatementEditingTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class StatementEditingTests : EditingTestBase { #region Strings [Fact] public void StringLiteral_update() { var src1 = @" var x = ""Hello1""; "; var src2 = @" var x = ""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8"); } [Fact] public void InterpolatedStringText_update() { var src1 = @" var x = $""Hello1""; "; var src2 = @" var x = $""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8"); } [Fact] public void Interpolation_update() { var src1 = @" var x = $""Hello{123}""; "; var src2 = @" var x = $""Hello{124}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8"); } [Fact] public void InterpolationFormatClause_update() { var src1 = @" var x = $""Hello{123:N1}""; "; var src2 = @" var x = $""Hello{123:N2}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8"); } #endregion #region Variable Declaration [Fact] public void VariableDeclaration_Insert() { var src1 = "if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 1) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var x = 1;]@2", "Insert [var x = 1]@2", "Insert [x = 1]@6"); } [Fact] public void VariableDeclaration_Update() { var src1 = "int x = F(1), y = G(2);"; var src2 = "int x = F(3), y = G(4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x = F(1)]@6 -> [x = F(3)]@6", "Update [y = G(2)]@16 -> [y = G(4)]@16"); } [Fact] public void ParenthesizedVariableDeclaration_Update() { var src1 = @" var (x1, (x2, x3)) = (1, (2, true)); var (a1, a2) = (1, () => { return 7; }); "; var src2 = @" var (x1, (x2, x4)) = (1, (2, true)); var (a1, a3) = (1, () => { return 8; }); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x3]@18 -> [x4]@18", "Update [a2]@51 -> [a3]@51"); } [Fact] public void ParenthesizedVariableDeclaration_Insert() { var src1 = @"var (z1, z2) = (1, 2);"; var src2 = @"var (z1, z2, z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (z1, z2) = (1, 2);]@2 -> [var (z1, z2, z3) = (1, 2, 5);]@2", "Insert [z3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Delete() { var src1 = @"var (y1, y2, y3) = (1, 2, 7);"; var src2 = @"var (y1, y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (y1, y2, y3) = (1, 2, 7);]@2 -> [var (y1, y2) = (1, 4);]@2", "Delete [y3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed1() { var src1 = @"int a; (var z1, a) = (1, 2);"; var src2 = @"int a; (var z1, a, var z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, a) = (1, 2);]@9 -> [(var z1, a, var z3) = (1, 2, 5);]@9", "Insert [z3]@25"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed2() { var src1 = @"int a; (var z1, var z2) = (1, 2);"; var src2 = @"int a; (var z1, var z2, a) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, var z2) = (1, 2);]@9 -> [(var z1, var z2, a) = (1, 2, 5);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed1() { var src1 = @"int a; (var y1, var y2, a) = (1, 2, 7);"; var src2 = @"int a; (var y1, var y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, var y2, a) = (1, 2, 7);]@9 -> [(var y1, var y2) = (1, 4);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed2() { var src1 = @"int a; (var y1, a, var y3) = (1, 2, 7);"; var src2 = @"int a; (var y1, a) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, a, var y3) = (1, 2, 7);]@9 -> [(var y1, a) = (1, 4);]@9", "Delete [y3]@25"); } [Fact] public void VariableDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (c, d) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2"); } [Fact] public void VariableDeclaraions_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2); (int c, int d) = (3, 4);"; var src2 = @"int a; (int c, int d) = (3, 4); (a, int b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int c, int d) = (3, 4);]@30 -> @9"); } [Fact] public void VariableNames_Reorder() { var src1 = @"var (a, b) = (1, 2);"; var src2 = @"var (b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, b) = (1, 2);]@2 -> [var (b, a) = (2, 1);]@2", "Reorder [b]@10 -> @7"); } [Fact] public void VariableNames_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2);"; var src2 = @"int a; (int b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a, int b) = (1, 2);]@9 -> [(int b, a) = (2, 1);]@9"); } [Fact] public void VariableNamesAndDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (d, c) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2", "Reorder [d]@31 -> @7"); } [Fact] public void ParenthesizedVariableDeclaration_Reorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((b, c), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((b, c), a) = ((2, 3), 1);]@2", "Reorder [a]@7 -> @15"); } [Fact] public void ParenthesizedVariableDeclaration_DoubleReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((c, b), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = ((2, 3), 1);]@2", "Reorder [b]@11 -> @11", "Reorder [c]@14 -> @8"); } [Fact] public void ParenthesizedVariableDeclaration_ComplexReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3)); var (x, (y, z)) = (4, (5, 6));"; var src2 = @"var (x, (y, z)) = (4, (5, 6)); var ((c, b), a) = (1, (2, 3)); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (x, (y, z)) = (4, (5, 6));]@33 -> @2", "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = (1, (2, 3));]@33", "Reorder [b]@11 -> @42", "Reorder [c]@14 -> @39"); } #endregion #region Switch Statement [Fact] public void Switch1() { var src1 = "switch (a) { case 1: f(); break; } switch (b) { case 2: g(); break; }"; var src2 = "switch (b) { case 2: f(); break; } switch (a) { case 1: g(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [switch (b) { case 2: g(); break; }]@37 -> @2", "Update [case 1: f(); break;]@15 -> [case 2: f(); break;]@15", "Move [case 1: f(); break;]@15 -> @15", "Update [case 2: g(); break;]@50 -> [case 1: g(); break;]@50", "Move [case 2: g(); break;]@50 -> @50"); } [Fact] public void Switch_Case_Reorder() { var src1 = "switch (expr) { case 1: f(); break; case 2: case 3: case 4: g(); break; }"; var src2 = "switch (expr) { case 2: case 3: case 4: g(); break; case 1: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case 2: case 3: case 4: g(); break;]@40 -> @18"); } [Fact] public void Switch_Case_Update() { var src1 = "switch (expr) { case 1: f(); break; }"; var src2 = "switch (expr) { case 2: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: f(); break;]@18 -> [case 2: f(); break;]@18"); } [Fact] public void CasePatternLabel_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: return 1; } "; var src2 = @" switch(shape) { case Circle circle: return 1; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@55 -> [case Circle circle: return 1;]@26", "Update [c]@67 -> [circle]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } #endregion #region Switch Expression [Fact] public void MethodUpdate_UpdateSwitchExpression1() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression2() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 1 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression3() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } #endregion #region Try Catch Finally [Fact] public void TryInsert1() { var src1 = "x++;"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Insert [{ x++; }]@6", "Insert [catch { }]@15", "Move [x++;]@2 -> @8", "Insert [{ }]@21"); } [Fact] public void TryInsert2() { var src1 = "{ x++; }"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Move [{ x++; }]@2 -> @6", "Insert [catch { }]@15", "Insert [{ }]@21"); } [Fact] public void TryDelete1() { var src1 = "try { x++; } catch { }"; var src2 = "x++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [x++;]@8 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [{ x++; }]@6", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryDelete2() { var src1 = "try { x++; } catch { }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@6 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryReorder() { var src1 = "try { x++; } catch { /*1*/ } try { y++; } catch { /*2*/ }"; var src2 = "try { y++; } catch { /*2*/ } try { x++; } catch { /*1*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [try { y++; } catch { /*2*/ }]@31 -> @2"); } [Fact] public void Finally_DeleteHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@47 -> @39", "Delete [finally { /*3*/ }]@39"); } [Fact] public void Finally_InsertHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [finally { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @47"); } [Fact] public void CatchUpdate() { var src1 = "try { } catch (Exception e) { }"; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(Exception e)]@16 -> [(IOException e)]@16"); } [Fact] public void CatchInsert() { var src1 = "try { /*1*/ } catch (Exception e) { /*2*/ } "; var src2 = "try { /*1*/ } catch (IOException e) { /*3*/ } catch (Exception e) { /*2*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (IOException e) { /*3*/ }]@16", "Insert [(IOException e)]@22", "Insert [{ /*3*/ }]@38"); } [Fact] public void CatchBodyUpdate() { var src1 = "try { } catch (E e) { x++; }"; var src2 = "try { } catch (E e) { y++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@24 -> [y++;]@24"); } [Fact] public void CatchDelete() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [catch (Exception e) { }]@36", "Delete [(Exception e)]@42", "Delete [{ }]@56"); } [Fact] public void CatchReorder1() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @10"); } [Fact] public void CatchReorder2() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch (A e) { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @26", "Reorder [catch { }]@60 -> @10", "Insert [(A e)]@16"); } [Fact] public void CatchFilterReorder2() { var src1 = "try { } catch (Exception e) when (e != null) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch when (s == 1) { } catch (Exception e) { } catch (Exception e) when (e != null) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@51 -> @34", "Reorder [catch { }]@75 -> @10", "Insert [when (s == 1)]@16"); } [Fact] public void CatchInsertDelete() { var src1 = @" try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } finally { /*3*/ }"; var src2 = @" try { x++; } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E e) { /*1*/ }]@79", "Insert [(E e)]@85", "Move [{ /*1*/ }]@29 -> @91", "Delete [catch (E e) { /*1*/ }]@17", "Delete [(E e)]@23"); } [Fact] public void Catch_DeleteHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@52 -> @39", "Delete [catch (E2 e) { /*3*/ }]@39", "Delete [(E2 e)]@45"); } [Fact] public void Catch_InsertHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E2 e) { /*3*/ }]@39", "Insert [(E2 e)]@45", "Move [{ /*3*/ }]@39 -> @52"); } [Fact] public void Catch_DeleteHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@45 -> @39", "Delete [catch { /*3*/ }]@39"); } [Fact] public void Catch_InsertHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @45"); } [Fact] public void Catch_InsertFilter1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [when (e == null)]@29"); } [Fact] public void Catch_InsertFilter2() { var src1 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22"); } [Fact] public void Catch_InsertFilter3() { var src1 = "try { /*1*/ } catch { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22", "Insert [when (e == null)]@29"); } [Fact] public void Catch_DeleteDeclaration1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter1() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [when (e == null)]@29"); } [Fact] public void Catch_DeleteFilter2() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter3() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22", "Delete [when (e == null)]@29"); } [Fact] public void TryCatchFinally_DeleteHeader() { var src1 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var src2 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@6 -> @2", "Move [{ /*2*/ }]@22 -> @12", "Move [{ /*3*/ }]@40 -> @22", "Delete [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Delete [catch { /*2*/ }]@16", "Delete [finally { /*3*/ }]@32"); } [Fact] public void TryCatchFinally_InsertHeader() { var src1 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch { /*2*/ }]@16", "Insert [finally { /*3*/ }]@32", "Move [{ /*2*/ }]@12 -> @22", "Move [{ /*3*/ }]@22 -> @40"); } [Fact] public void TryFilterFinally_InsertHeader() { var src1 = "{ /*1*/ } if (a == 1) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch when (a == 1) { /*2*/ }]@16", "Insert [finally { /*3*/ }]@46", "Insert [when (a == 1)]@22", "Move [{ /*2*/ }]@24 -> @36", "Move [{ /*3*/ }]@34 -> @54", "Delete [if (a == 1) { /*2*/ }]@12"); } #endregion #region Blocks [Fact] public void Block_Insert() { var src1 = ""; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [{ x++; }]@2", "Insert [x++;]@4"); } [Fact] public void Block_Delete() { var src1 = "{ x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [{ x++; }]@2", "Delete [x++;]@4"); } [Fact] public void Block_Reorder() { var src1 = "{ x++; } { y++; }"; var src2 = "{ y++; } { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [{ y++; }]@11 -> @2"); } [Fact] public void Block_AddLine() { var src1 = "{ x++; }"; var src2 = @"{ // x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(); } #endregion #region Checked/Unchecked [Fact] public void Checked_Insert() { var src1 = ""; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Insert [{ x++; }]@10", "Insert [x++;]@12"); } [Fact] public void Checked_Delete() { var src1 = "checked { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [checked { x++; }]@2", "Delete [{ x++; }]@10", "Delete [x++;]@12"); } [Fact] public void Checked_Update() { var src1 = "checked { x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [checked { x++; }]@2 -> [unchecked { x++; }]@2"); } [Fact] public void Checked_DeleteHeader() { var src1 = "checked { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@10 -> @2", "Delete [checked { x++; }]@2"); } [Fact] public void Checked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Move [{ x++; }]@2 -> @10"); } [Fact] public void Unchecked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unchecked { x++; }]@2", "Move [{ x++; }]@2 -> @12"); } #endregion #region Unsafe [Fact] public void Unsafe_Insert() { var src1 = ""; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Insert [{ x++; }]@9", "Insert [x++;]@11"); } [Fact] public void Unsafe_Delete() { var src1 = "unsafe { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [unsafe { x++; }]@2", "Delete [{ x++; }]@9", "Delete [x++;]@11"); } [Fact] public void Unsafe_DeleteHeader() { var src1 = "unsafe { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@9 -> @2", "Delete [unsafe { x++; }]@2"); } [Fact] public void Unsafe_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Move [{ x++; }]@2 -> @9"); } #endregion #region Using Statement [Fact] public void Using1() { var src1 = @"using (a) { using (b) { Goo(); } }"; var src2 = @"using (a) { using (c) { using (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (c) { using (b) { Goo(); } }]@14", "Insert [{ using (b) { Goo(); } }]@24", "Move [using (b) { Goo(); }]@14 -> @26"); } [Fact] public void Using_DeleteHeader() { var src1 = @"using (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [using (a) { Goo(); }]@2"); } [Fact] public void Using_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"using (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Lock Statement [Fact] public void Lock1() { var src1 = @"lock (a) { lock (b) { Goo(); } }"; var src2 = @"lock (a) { lock (c) { lock (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (c) { lock (b) { Goo(); } }]@13", "Insert [{ lock (b) { Goo(); } }]@22", "Move [lock (b) { Goo(); }]@13 -> @24"); } [Fact] public void Lock_DeleteHeader() { var src1 = @"lock (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@11 -> @2", "Delete [lock (a) { Goo(); }]@2"); } [Fact] public void Lock_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"lock (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @11"); } #endregion #region ForEach Statement [Fact] public void ForEach1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var c in g) { foreach (var b in f) { Goo(); } }]@25", "Insert [{ foreach (var b in f) { Goo(); } }]@46", "Move [foreach (var b in f) { Goo(); }]@25 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "{ foreach (var b in f) { Goo(); } }", "{ foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { Goo(); }" }, { "{ Goo(); }", "{ Goo(); }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void ForEach_Swap1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var b in f) { foreach (var a in e) { Goo(); } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach (var b in f) { Goo(); }]@25 -> @2", "Move [foreach (var a in e) { foreach (var b in f) { Goo(); } }]@2 -> @25", "Move [Goo();]@48 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { Goo(); }" }, { "{ foreach (var b in f) { Goo(); } }", "{ Goo(); }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { foreach (var a in e) { Goo(); } }" }, { "{ Goo(); }", "{ foreach (var a in e) { Goo(); } }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void Foreach_DeleteHeader() { var src1 = @"foreach (var a in b) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@23 -> @2", "Delete [foreach (var a in b) { Goo(); }]@2"); } [Fact] public void Foreach_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"foreach (var a in b) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var a in b) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @23"); } [Fact] public void ForeachVariable_Update1() { var src1 = @" foreach (var (a1, a2) in e) { } foreach ((var b1, var b2) in e) { } foreach (var a in e1) { } "; var src2 = @" foreach (var (a1, a3) in e) { } foreach ((var b3, int b2) in e) { } foreach (_ in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach ((var b1, var b2) in e) { }]@37 -> [foreach ((var b3, int b2) in e) { }]@37", "Update [foreach (var a in e1) { }]@74 -> [foreach (_ in e1) { }]@74", "Update [a2]@22 -> [a3]@22", "Update [b1]@51 -> [b3]@51"); } [Fact] public void ForeachVariable_Update2() { var src1 = @" foreach (_ in e2) { } foreach (_ in e3) { A(); } "; var src2 = @" foreach (var b in e2) { } foreach (_ in e4) { A(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (_ in e2) { }]@4 -> [foreach (var b in e2) { }]@4", "Update [foreach (_ in e3) { A(); }]@27 -> [foreach (_ in e4) { A(); }]@31"); } [Fact] public void ForeachVariable_Insert() { var src1 = @" foreach (var (a3, a4) in e) { } foreach ((var b4, var b5) in e) { } "; var src2 = @" foreach (var (a3, a5, a4) in e) { } foreach ((var b6, var b4, var b5) in e) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a3, a4) in e) { }]@4 -> [foreach (var (a3, a5, a4) in e) { }]@4", "Update [foreach ((var b4, var b5) in e) { }]@37 -> [foreach ((var b6, var b4, var b5) in e) { }]@41", "Insert [a5]@22", "Insert [b6]@55"); } [Fact] public void ForeachVariable_Delete() { var src1 = @" foreach (var (a11, a12, a13) in e) { F(); } foreach ((var b7, var b8, var b9) in e) { G(); } "; var src2 = @" foreach (var (a12, a13) in e1) { F(); } foreach ((var b7, var b9) in e) { G(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a11, a12, a13) in e) { F(); }]@4 -> [foreach (var (a12, a13) in e1) { F(); }]@4", "Update [foreach ((var b7, var b8, var b9) in e) { G(); }]@49 -> [foreach ((var b7, var b9) in e) { G(); }]@45", "Delete [a11]@18", "Delete [b8]@71"); } [Fact] public void ForeachVariable_Reorder() { var src1 = @" foreach (var (a, b) in e1) { } foreach ((var x, var y) in e2) { } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [foreach ((var x, var y) in e2) { }]@36 -> @4"); } [Fact] public void ForeachVariableEmbedded_Reorder() { var src1 = @" foreach (var (a, b) in e1) { foreach ((var x, var y) in e2) { } } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach ((var x, var y) in e2) { }]@39 -> @4"); } #endregion #region For Statement [Fact] public void For1() { var src1 = @"for (int a = 0; a < 10; a++) { for (int a = 0; a < 20; a++) { Goo(); } }"; var src2 = @"for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } }]@33", "Insert [int b = 0]@38", "Insert [b < 10]@49", "Insert [b++]@57", "Insert [{ for (int a = 0; a < 20; a++) { Goo(); } }]@62", "Insert [b = 0]@42", "Move [for (int a = 0; a < 20; a++) { Goo(); }]@33 -> @64"); } [Fact] public void For_DeleteHeader() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@43 -> @2", "Delete [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Delete [int i = 10, j = 0]@7", "Delete [i = 10]@11", "Delete [j = 0]@19", "Delete [i > j]@26", "Delete [i--]@33", "Delete [j++]@38"); } [Fact] public void For_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Insert [int i = 10, j = 0]@7", "Insert [i > j]@26", "Insert [i--]@33", "Insert [j++]@38", "Move [{ Goo(); }]@2 -> @43", "Insert [i = 10]@11", "Insert [j = 0]@19"); } [Fact] public void For_DeclaratorsToInitializers() { var src1 = @"for (var i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [i = 10]@7", "Delete [var i = 10]@7", "Delete [i = 10]@11"); } [Fact] public void For_InitializersToDeclarators() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (var i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var i = 10, j = 0]@7", "Insert [i = 10]@11", "Insert [j = 0]@19", "Delete [i = 10]@7", "Delete [j = 0]@15"); } [Fact] public void For_Declarations_Reorder() { var src1 = @"for (var i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (var j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@19 -> @11"); } [Fact] public void For_Declarations_Insert() { var src1 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1]@7 -> [var i = 0, j = 1, k = 2]@7", "Insert [k = 2]@25"); } [Fact] public void For_Declarations_Delete() { var src1 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1, k = 2]@7 -> [var i = 0, j = 1]@7", "Delete [k = 2]@25"); } [Fact] public void For_Initializers_Reorder() { var src1 = @"for (i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@15 -> @7"); } [Fact] public void For_Initializers_Insert() { var src1 = @"for (i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j = 0]@15"); } [Fact] public void For_Initializers_Delete() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [j = 0]@15"); } [Fact] public void For_Initializers_Update() { var src1 = @"for (i = 1; i < 10; i++) { }"; var src2 = @"for (i = 2; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i = 1]@7 -> [i = 2]@7"); } [Fact] public void For_Initializers_Update_Lambda() { var src1 = @"for (int i = 10, j = F(() => 1); i > j; i++) { }"; var src2 = @"for (int i = 10, j = F(() => 2); i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@25 -> [() => 2]@25"); } [Fact] public void For_Condition_Update() { var src1 = @"for (int i = 0; i < 10; i++) { }"; var src2 = @"for (int i = 0; i < 20; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i < 10]@18 -> [i < 20]@18"); } [Fact] public void For_Condition_Lambda() { var src1 = @"for (int i = 0; F(() => 1); i++) { }"; var src2 = @"for (int i = 0; F(() => 2); i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@20 -> [() => 2]@20"); } [Fact] public void For_Incrementors_Reorder() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j++]@38 -> @33"); } [Fact] public void For_Incrementors_Insert() { var src1 = @"for (int i = 10, j = 0; i > j; i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j++]@33"); } [Fact] public void For_Incrementors_Delete() { var src1 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [i--]@38"); } [Fact] public void For_Incrementors_Update() { var src1 = @"for (int i = 10, j = 0; i > j; j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [j++]@33 -> [i++]@33"); } [Fact] public void For_Incrementors_Update_Lambda() { var src1 = @"for (int i = 10, j = 0; i > j; F(() => 1)) { }"; var src2 = @"for (int i = 10, j = 0; i > j; F(() => 2)) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@35 -> [() => 2]@35"); } #endregion #region While Statement [Fact] public void While1() { var src1 = @"while (a) { while (b) { Goo(); } }"; var src2 = @"while (a) { while (c) { while (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (c) { while (b) { Goo(); } }]@14", "Insert [{ while (b) { Goo(); } }]@24", "Move [while (b) { Goo(); }]@14 -> @26"); } [Fact] public void While_DeleteHeader() { var src1 = @"while (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [while (a) { Goo(); }]@2"); } [Fact] public void While_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"while (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Do Statement [Fact] public void Do1() { var src1 = @"do { do { Goo(); } while (b); } while (a);"; var src2 = @"do { do { do { Goo(); } while(b); } while(c); } while(a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { do { Goo(); } while(b); } while(c);]@7", "Insert [{ do { Goo(); } while(b); }]@10", "Move [do { Goo(); } while (b);]@7 -> @12"); } [Fact] public void Do_DeleteHeader() { var src1 = @"do { Goo(); } while (a);"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@5 -> @2", "Delete [do { Goo(); } while (a);]@2"); } [Fact] public void Do_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"do { Goo(); } while (a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { Goo(); } while (a);]@2", "Move [{ Goo(); }]@2 -> @5"); } #endregion #region If Statement [Fact] public void IfStatement_TestExpression_Update() { var src1 = "var x = 1; if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 2) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (x == 1) { x++; }]@13 -> [if (x == 2) { x++; }]@13"); } [Fact] public void ElseClause_Insert() { var src1 = "if (x == 1) x++; "; var src2 = "if (x == 1) x++; else y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else y++;]@19", "Insert [y++;]@24"); } [Fact] public void ElseClause_InsertMove() { var src1 = "if (x == 1) x++; else y++;"; var src2 = "if (x == 1) x++; else if (x == 2) y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (x == 2) y++;]@24", "Move [y++;]@24 -> @36"); } [Fact] public void If1() { var src1 = @"if (a) if (b) Goo();"; var src2 = @"if (a) if (c) if (b) Goo();"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (c) if (b) Goo();]@9", "Move [if (b) Goo();]@9 -> @16"); } [Fact] public void If_DeleteHeader() { var src1 = @"if (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@9 -> @2", "Delete [if (a) { Goo(); }]@2"); } [Fact] public void If_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"if (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @9"); } [Fact] public void Else_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@30 -> @25", "Delete [else { Goo(/*2*/); }]@25"); } [Fact] public void Else_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else { Goo(/*2*/); }]@25", "Move [{ Goo(/*2*/); }]@25 -> @30"); } [Fact] public void ElseIf_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@37 -> @25", "Delete [else if (b) { Goo(/*2*/); }]@25", "Delete [if (b) { Goo(/*2*/); }]@30"); } [Fact] public void ElseIf_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else if (b) { Goo(/*2*/); }]@25", "Insert [if (b) { Goo(/*2*/); }]@30", "Move [{ Goo(/*2*/); }]@25 -> @37"); } [Fact] public void IfElseElseIf_InsertHeader() { var src1 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @9", "Insert [else if (b) { /*2*/ } else { /*3*/ }]@19", "Insert [if (b) { /*2*/ } else { /*3*/ }]@24", "Move [{ /*2*/ }]@12 -> @31", "Insert [else { /*3*/ }]@41", "Move [{ /*3*/ }]@22 -> @46"); } [Fact] public void IfElseElseIf_DeleteHeader() { var src1 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var src2 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@9 -> @2", "Move [{ /*2*/ }]@31 -> @12", "Move [{ /*3*/ }]@46 -> @22", "Delete [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Delete [else if (b) { /*2*/ } else { /*3*/ }]@19", "Delete [if (b) { /*2*/ } else { /*3*/ }]@24", "Delete [else { /*3*/ }]@41"); } #endregion #region Switch Statement [Fact] public void SwitchStatement_Update_Expression() { var src1 = "var x = 1; switch (x + 1) { case 1: break; }"; var src2 = "var x = 1; switch (x + 2) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [switch (x + 1) { case 1: break; }]@13 -> [switch (x + 2) { case 1: break; }]@13"); } [Fact] public void SwitchStatement_Update_SectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_AddSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 1: case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_DeleteSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: case 2: break;]@26 -> [case 1: break;]@26"); } [Fact] public void SwitchStatement_Update_BlockInSection() { var src1 = "var x = 1; switch (x) { case 1: { x++; break; } }"; var src2 = "var x = 1; switch (x) { case 1: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@36 -> [x--;]@36"); } [Fact] public void SwitchStatement_Update_BlockInDefaultSection() { var src1 = "var x = 1; switch (x) { default: { x++; break; } }"; var src2 = "var x = 1; switch (x) { default: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@37 -> [x--;]@37"); } [Fact] public void SwitchStatement_Insert_Section() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [case 2: break;]@41", "Insert [break;]@49"); } [Fact] public void SwitchStatement_Delete_Section() { var src1 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [case 2: break;]@41", "Delete [break;]@49"); } #endregion #region Lambdas [Fact] public void Lambdas_AddAttribute() { var src1 = "Func<int, int> x = (a) => a;"; var src2 = "Func<int, int> x = [A][return:A]([A]a) => a;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a) => a]@21 -> [[A][return:A]([A]a) => a]@21", "Update [a]@22 -> [[A]a]@35"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.parameter)); GetTopEdits(edits).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_InVariableDeclarator() { var src1 = "Action x = a => a, y = b => b;"; var src2 = "Action x = (a) => a, y = b => b + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@13 -> [(a) => a]@13", "Update [b => b]@25 -> [b => b + 1]@27", "Insert [(a)]@13", "Insert [a]@14", "Delete [a]@13"); } [Fact] public void Lambdas_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "F(b => b, a => a+1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => b]@12 -> @4", "Update [a => a]@4 -> [a => a+1]@12"); } [Fact] public void Lambdas_ReorderArguments() { var src1 = "F(G(a => {}), G(b => {}));"; var src2 = "F(G(b => {}), G(a => {}));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => {}]@18 -> @6"); } [Fact] public void Lambdas_InWhile() { var src1 = "while (F(a => a)) { /*1*/ }"; var src2 = "do { /*1*/ } while (F(a => a));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { /*1*/ } while (F(a => a));]@2", "Move [{ /*1*/ }]@20 -> @5", "Move [a => a]@11 -> @24", "Delete [while (F(a => a)) { /*1*/ }]@2"); } [Fact] public void Lambdas_InLambda_ChangeInLambdaSignature() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer lambda signature: edits.VerifyEdits( "Update [() => { G(x => y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void Lambdas_InLambda_ChangeOnlyInLambdaBody() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(() => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer lambda body: edits.VerifyEdits(); } [Fact] public void Lambdas_Update_ParameterRefness_NoBodyChange() { var src1 = @"F((ref int a) => a = 1);"; var src2 = @"F((out int a) => a = 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@5 -> [out int a]@5"); } [Fact] public void Lambdas_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_Static_Nested1() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => G(b => b) + a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => x); } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] public void Lambdas_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f1 = new Func<int, int>(a => y); } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => G(b => x)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); return a; }); } } "; var src2 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); var f3 = new Func<int, int>(c => { return c + x; }); return a; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); G(a => x); // OK G(a => x0 + y0); // OK G(a => x1 + y0); // error - connecting Group #1 and Group #2 G(a => x3 + x1); // error - multi-scope (conservative) G(a => x + y0); // error - connecting Group #0 and Group #1 G(a => x + x3); // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); } [Fact] public void Lambdas_Insert_ForEach1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); G(a => x0 + x1); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_ForEach2() { var src1 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, null); } } "; var src2 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, a => x0 + x1); // error: connecting previously disconnected closures } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_For1() { var src1 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } } "; var src2 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); G(a => x0 + x1); // ok G(a => x0 + x2); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x2", CSharpFeaturesResources.lambda, "x0", "x2")); } [Fact] public void Lambdas_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); goto case 2; case 2: int x1 = 1; G(() => x1); goto default; default: x0 = 1; x1 = 2; G(() => x0 + x1); // ok G(() => x0 + x2); // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x2", "x0")); } [Fact] public void Lambdas_Insert_Using1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); G(() => F(x0, y0)); // ok G(() => F(x0, x1)); // error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_Catch1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); G(() => x0); //ok G(() => F(x0, x1)); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact, WorkItem(1504, "https://github.com/dotnet/roslyn/issues/1504")] public void Lambdas_Insert_CatchFilter1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0)) { } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0) && G(() => x0) && // ok G(() => x0 != x1)) // error { G(() => x0); // ok } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x1", "x0") ); } [Fact] public void Lambdas_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_Second_NotSupported() { var src1 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_FirstInClass_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, // TODO: https://github.com/dotnet/roslyn/issues/52759 // This is incorrect, there should be no rude edit reported Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var src2 = @" using System; class C { int x; void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_Signature1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature2() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature3() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_Nullable() { var src1 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_SyntaxOnly1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2((a) => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G2(a => { }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ReturnType2() { var src1 = "var x = int (int a) => a;"; var src2 = "var x = long (int a) => a;"; var edits = GetMethodEdits(src1, src2); GetTopEdits(edits).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(b => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterRefness1() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1((ref int a) => 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2((int a) => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ParameterRefness2() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((ref int a) => a = 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((out int a) => a = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(out int a)", CSharpFeaturesResources.lambda)); } // Add corresponding test to VB [Fact(Skip = "TODO")] public void Lambdas_Update_Signature_CustomModifiers1() { var delegateSource = @" .class public auto ansi sealed D1 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D2 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D3 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } }"; var src1 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; MetadataReference delegateDefs; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource)) { delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path)); } var edits = GetTopEdits(src1, src2); // TODO edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Signature_MatchingErrorType() { var src1 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 1); } } "; var src2 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("F").Single(), preserveLocalVariables: true) }); } [Fact] public void Lambdas_Signature_NonMatchingErrorType() { var src1 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", "lambda")); } [Fact] public void Lambdas_Update_DelegateType1() { var src1 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType1() { var src1 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType2() { var src1 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_SourceTypeAndMetadataType1() { var src1 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } } "; var src2 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Generic1() { var src1 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G1((a, b) => a + b); } } "; var src2 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Generic2() { var src1 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G1((a, b) => 1); } } "; var src2 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G2((a, b) => 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void Lambdas_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a2", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { new Action(() => { Console.Write(value); }).Invoke(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return y; }); } } "; var src2 = @" using System; class C { void F() { // error var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y").WithFirstLine("{ // error")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact] public void Lambdas_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this").WithFirstLine("partial void F() // impl")); } [Fact] public void Lambdas_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a1", "this", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => { return a1 + x+ // 1 x; // 2 }); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x+ // 1"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x; // 2")); } [Fact] public void Lambdas_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x + y); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // TODO: better diagnostics - identify a1 that causes the capture vs. a1 that doesn't edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1").WithFirstLine("var f1 = new Func<int, int>(a1 =>")); } [Fact] public void Lambdas_Update_Accessing_Closure1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0); } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0 + x0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure2() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure3() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure4() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); // TODO: "a => x + x0" is matched with "a => y1 + x0", hence we report more errors. // Including statement distance when matching would help. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y1", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"), Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures")); } [Fact] public void Lambdas_Update_Accessing_Closure_NestedLambdas() { var src1 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); G(a => b => x0); // ok G(a => b => x1); // ok G(a => b => x0 + x1); // error } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void Lambdas_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_Parameter_To_Discard1() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((a, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard2() { var src1 = "var x = new System.Func<int, int, int>((int a, int b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int a]@42 -> [_]@42", "Update [int b]@49 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard3() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a]@42 -> [_]@42", "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } #endregion #region Local Functions [Fact] public void LocalFunctions_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "int x(int a) => a + 1; F(b => b, x);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@4 -> [int x(int a) => a + 1;]@2", "Move [a => a]@4 -> @2", "Update [F(a => a, b => b);]@2 -> [F(b => b, x);]@25", "Insert [(int a)]@7", "Insert [int a]@8", "Delete [a]@4"); } [Fact] public void LocalFunctions_ReorderAndUpdate() { var src1 = "int x(int a) => a; int y(int b) => b;"; var src2 = "int y(int b) => b; int x(int a) => a + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int y(int b) => b;]@21 -> @2", "Update [int x(int a) => a;]@2 -> [int x(int a) => a + 1;]@21"); } [Fact] public void LocalFunctions_InWhile() { var src1 = "do { /*1*/ } while (F(x));int x(int a) => a + 1;"; var src2 = "while (F(a => a)) { /*1*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (F(a => a)) { /*1*/ }]@2", "Update [int x(int a) => a + 1;]@28 -> [a => a]@11", "Move [int x(int a) => a + 1;]@28 -> @11", "Move [{ /*1*/ }]@5 -> @20", "Insert [a]@11", "Delete [do { /*1*/ } while (F(x));]@2", "Delete [(int a)]@33", "Delete [int a]@34"); } [Fact] public void LocalFunctions_InLocalFunction_NoChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x() { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer local function body: edits.VerifyEdits(); } [Fact] public void LocalFunctions_InLocalFunction_ChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x(int z) { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer local function signature: edits.VerifyEdits("Insert [int z]@8"); } [Fact] public void LocalFunctions_InLambda() { var src1 = "F(() => { int y(int a) => a; G(y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [() => { int y(int a) => a; G(y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void LocalFunctions_Update_ParameterRefness_NoBodyChange() { var src1 = @"void f(ref int a) => a = 1;"; var src2 = @"void f(out int a) => a = 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@9 -> [out int a]@9"); } [Fact] public void LocalFunctions_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_ExpressionBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; int localG(int a) => G(localF) + a; G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_BlockBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } int localG(int a) { return G(localF) + a; } G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_LocalFunction_Replace_Lambda() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var edits = GetTopEdits(src1, src2); // To be removed when we will enable EnC for local functions edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "localF", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Lambda_Replace_LocalFunction() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "a", CSharpFeaturesResources.lambda)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; void F() { int G(int a) => x; } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291"), WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; int f1(int a) => y; } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => a; G(f); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => x; int g(int a) => G(f); G(g); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; return a; }; } } "; var src2 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; int f3(int c) { return c + x; }; return a; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; int f4(int a) => x; // OK int f5(int a) => x0 + y0; // OK int f6(int a) => x1 + y0; // error - connecting Group #1 and Group #2 int f7(int a) => x3 + x1; // error - multi-scope (conservative) int f8(int a) => x + y0; // error - connecting Group #0 and Group #1 int f9(int a) => x + x3; // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ForEach1() { var src1 = @" using System; class C { void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; break; case 2: int x1 = 1; int f1() => x1; break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; goto case 2; case 2: int x1 = 1; int f1() => x1; goto default; default: x0 = 1; x1 = 2; int f01() => x0 + x1; // ok int f02() => x0 + x2; // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.local_function, "x2", "x0")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Catch1() { var src1 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; } } } "; var src2 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; int f00() => x0; //ok int f01() => F(x0, x1); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact] public void LocalFunctions_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { void M() { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "M", FeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var src2 = @" using System; class C { int x; void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void LocalFunctions_Update_Signature1() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(long a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature2() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { int f(int a, int b) => a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature3() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void F() { int f(int a) { return 1; } } } "; var src2 = @" using System; class C { void F() { void f(int a) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { int f(int a) { return a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void F() { int f(int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int b) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness1() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness2() { var src1 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(ref int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness3() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Signature_SemanticErrors() { var src1 = @" using System; class C { void F() { Unknown f(Unknown a) => 1; } } "; var src2 = @" using System; class C { void F() { Unknown f(Unknown a) => 2; } } "; var edits = GetTopEdits(src1, src2); // There are semantics errors in the case. The errors are captured during the emit execution. edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void LocalFunctions_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "f2", "y", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerParameter() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "int f1(int a1, int a2)\r\n {\r\n int f2(int a3) => a2;\r\n return a1;\r\n };\r\n ", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { void f() { Console.Write(value); } f(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return y; }; } } "; var src2 = @" using System; class C { void F() { // error int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a; } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1 + x; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "f1", "this", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { void F() { int x = 1; int f1(int a1) { return a1 + x+ // 1 x; // 2 }; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x; int f2(int a2) => a2 + x + y; } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x + y; int f2(int a2) => a2 + x + y; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void LocalFunctions_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void LocalFunction_In_Parameter_InsertWhole() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_In_Parameter_InsertParameter() { var src1 = @"class Test { void M() { void local() { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local() { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_In_Parameter_Update() { var src1 = @"class Test { void M() { void local(int b) { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local(int b) { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Insert() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Update() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "local", CSharpFeaturesResources.local_function)); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void LocalFunction_AddToInterfaceMethod() { var src1 = @" using System; interface I { static int X = M(() => 1); static int M() => 1; static void F() { void g() { } } } "; var src2 = @" using System; interface I { static int X = M(() => { void f3() {} return 2; }); static int M() => 1; static void F() { int f1() => 1; f1(); void g() { void f2() {} f2(); } var l = new Func<int>(() => 1); l(); } } "; var edits = GetTopEdits(src1, src2); // lambdas are ok as they are emitted to a nested type edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.NetCoreApp }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f1"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f2"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f3") }); } [Fact] public void LocalFunction_AddStatic() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { static int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { static int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveStatic() { var src1 = @"class Test { void M() { static int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { static int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_AddUnsafe() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { unsafe int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveUnsafe() { var src1 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { unsafe int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_AddAsync() { var src1 = @"class Test { void M() { Task<int> local() => throw null; } }"; var src2 = @"class Test { void M() { async Task<int> local() => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_RemoveAsync() { var src1 = @"class Test { void M() { async int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "local", FeaturesResources.local_function)); } [Fact] public void LocalFunction_AddAttribute() { var src1 = "void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [void L() { }]@2 -> [[A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_RemoveAttribute() { var src1 = "[A]void L() { }"; var src2 = "void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]void L() { }]@2 -> [void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReorderAttribute() { var src1 = "[A, B]void L() { }"; var src2 = "[B, A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]void L() { }]@2 -> [[B, A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_CombineAttributeLists() { var src1 = "[A][B]void L() { }"; var src2 = "[A, B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A][B]void L() { }]@2 -> [[A, B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_SplitAttributeLists() { var src1 = "[A, B]void L() { }"; var src2 = "[A][B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]void L() { }]@2 -> [[A][B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ChangeAttributeListTarget1() { var src1 = "[return: A]void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A]void L() { }]@2 -> [[A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ChangeAttributeListTarget2() { var src1 = "[A]void L() { }"; var src2 = "[return: A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A]void L() { }]@2 -> [[return: A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_AddAttribute() { var src1 = "int L() { return 1; }"; var src2 = "[return: A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int L() { return 1; }]@2 -> [[return: A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_RemoveAttribute() { var src1 = "[return: A]int L() { return 1; }"; var src2 = "int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[return: A]int L() { return 1; }]@2 -> [int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_ReorderAttribute() { var src1 = "[return: A, B]int L() { return 1; }"; var src2 = "[return: B, A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A, B]int L() { return 1; }]@2 -> [[return: B, A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_Parameter_AddAttribute() { var src1 = "void L(int i) { }"; var src2 = "void L([A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int i]@9 -> [[A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_RemoveAttribute() { var src1 = "void L([A]int i) { }"; var src2 = "void L(int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]int i]@9 -> [int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_ReorderAttribute() { var src1 = "void L([A, B]int i) { }"; var src2 = "void L([B, A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]int i]@9 -> [[B, A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_TypeParameter_AddAttribute() { var src1 = "void L<T>(T i) { }"; var src2 = "void L<[A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [T]@9 -> [[A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_RemoveAttribute() { var src1 = "void L<[A] T>(T i) { }"; var src2 = "void L<T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A] T]@9 -> [T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_ReorderAttribute() { var src1 = "void L<[A, B] T>(T i) { }"; var src2 = "void L<[B, A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B] T]@9 -> [[B, A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunctions_TypeParameter_Insert1() { var src1 = @"void L() {}"; var src2 = @"void L<A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@8", "Insert [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Insert2() { var src1 = @"void L<A>() {}"; var src2 = @"void L<A,B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@8 -> [<A,B>]@8", "Insert [B]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete1() { var src1 = @"void L<A>() {}"; var src2 = @"void L() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete2() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@8 -> [<B>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Update() { var src1 = @"void L<A>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [A]@9 -> [B]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("Enum", "Delegate")] [InlineData("IDisposable", "IDisposable, new()")] public void LocalFunctions_TypeParameter_Constraint_Clause_Update(string oldConstraint, string newConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() where A : " + newConstraint + " {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [where A : " + oldConstraint + "]@14 -> [where A : " + newConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void LocalFunctions_TypeParameter_Constraint_Clause_Delete(string oldConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [where A : " + oldConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Constraint_Clause_Add() { var src1 = "void L<A,B>() where A : new() {}"; var src2 = "void L<A,B>() where A : new() where B : System.IDisposable {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [where B : System.IDisposable]@32"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Reorder() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_ReorderAndUpdate() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,C>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9", "Update [A]@9 -> [C]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } #endregion #region Queries [Fact] public void Queries_Update_Signature_Select1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1.0} select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_Select2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a.ToString(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_From1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "from", CSharpFeaturesResources.from_clause)); } [Fact] public void Queries_Update_Signature_From2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from System.Int64 a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_From3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new List<int>() from b in new List<int>() select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_Let1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1.0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "let", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_Update_Signature_OrderBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 1.0 descending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_OrderBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 2.0 ascending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_Join1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join4() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_GroupBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1 by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a + 1.0 into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy_MatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_FromSelect_Update1() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in c from x in z select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from a in b]@4 -> [from a in c]@4", "Update [from x in y]@16 -> [from x in z]@16", "Update [select c]@28 -> [select c + 1]@28"); } [Fact] public void Queries_FromSelect_Update2() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in b from x in z select c);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from x in y]@16 -> [from x in z]@16"); } [Fact] public void Queries_FromSelect_Update3() { var src1 = "F(from a in await b from x in y select c);"; var src2 = "F(from a in await c from x in y select c);"; var edits = GetMethodEdits(src1, src2, MethodKind.Async); edits.VerifyEdits( "Update [await b]@34 -> [await c]@34"); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_FromSelect_Delete() { var src1 = "F(from a in b from c in d select a + c);"; var src2 = "F(from a in b select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select a + c]@28 -> [select c + 1]@16", "Delete [from c in d]@16"); } [Fact] public void Queries_JoinInto_Update() { var src1 = "F(from a in b join b in c on a equals b into g1 select g1);"; var src2 = "F(from a in b join b in c on a equals b into g2 select g2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select g1]@50 -> [select g2]@50", "Update [into g1]@42 -> [into g2]@42"); } [Fact] public void Queries_JoinIn_Update() { var src1 = "F(from a in b join b in await A(1) on a equals b select g);"; var src2 = "F(from a in b join b in await A(2) on a equals b select g);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [await A(1)]@26 -> [await A(2)]@26"); } [Fact] public void Queries_GroupBy_Update() { var src1 = "F(from a in b group a by a.x into g select g);"; var src2 = "F(from a in b group z by z.y into h select h);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [group a by a.x]@17 -> [group z by z.y]@17", "Update [into g select g]@32 -> [into h select h]@32", "Update [select g]@40 -> [select h]@40"); } [Fact] public void Queries_OrderBy_Reorder() { var src1 = "F(from a in b orderby a.x, a.b descending, a.c ascending select a.d);"; var src2 = "F(from a in b orderby a.x, a.c ascending, a.b descending select a.d);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [a.c ascending]@46 -> @30"); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_GroupBy_Reduced3() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced4() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_OrderBy_Continuation_Update() { var src1 = "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);"; var src2 = "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);"; var edits = GetMethodEdits(src1, src2); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);", "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);" }, { "from a in b", "from a in b" }, { "orderby a.x, a.b descending select a.d into z orderby a.c ascending select z", "orderby a.x, a.c ascending select a.d into z orderby a.b descending select z" }, { "orderby a.x, a.b descending", "orderby a.x, a.c ascending" }, { "a.x", "a.x" }, { "a.b descending", "a.c ascending" }, { "select a.d", "select a.d" }, { "into z orderby a.c ascending select z", "into z orderby a.b descending select z" }, { "orderby a.c ascending select z", "orderby a.b descending select z" }, { "orderby a.c ascending", "orderby a.b descending" }, { "a.c ascending", "a.b descending" }, { "select z", "select z" } }; expected.AssertEqual(actual); edits.VerifyEdits( "Update [a.b descending]@30 -> [a.c ascending]@30", "Update [a.c ascending]@74 -> [a.b descending]@73"); } [Fact] public void Queries_CapturedTransparentIdentifiers_FromClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 0 where Z(() => b) > 0 where Z(() => a) > 0 where Z(() => b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 1 // update where Z(() => b) > 2 // update where Z(() => a) > 3 // update where Z(() => b) > 4 // update select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_LetClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a) select a + b; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a + 1) select a - b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_JoinClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.First()); } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.Last()); } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CeaseCapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); // TODO: better location (the variable, not the from clause) edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "from b in new[] { 2 }", "b")); } [Fact] public void Queries_CapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "b", "b")); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select 1; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier3() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "select", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_Insert1() { var src1 = @" using System; using System.Linq; class C { void F() { } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] { 1 } select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Yield [Fact] public void Yield_Update1() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield break; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 3; yield break; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield break;", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.yield_break_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 4;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Delete1() { var src1 = @" yield return 1; yield return 2; yield return 3; "; var src2 = @" yield return 1; yield return 3; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Delete [yield return 2;]@42"); } [Fact] public void Yield_Delete2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Insert1() { var src1 = @" yield return 1; yield return 3; "; var src2 = @" yield return 1; yield return 2; yield return 3; yield return 4; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Insert [yield return 2;]@42", "Insert [yield return 4;]@76"); } [Fact] public void Yield_Insert2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "yield return 4;", CSharpFeaturesResources.yield_return_statement), Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingIteratorStateMachineAttribute() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 1; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }, Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable<int> F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute")); } [Fact] public void MissingIteratorStateMachineAttribute2() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return null; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }); } #endregion #region Await /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_OK() { var src1 = @" class C { static async Task<int> F() { await F(1); if (await F(1)) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(1); } while (await F(1)); for (var x = await F(1); await G(1); await H(1)) { Console.WriteLine(1); } foreach (var x in await F(1)) { Console.WriteLine(1); } using (var x = await F(1)) { Console.WriteLine(1); } lock (await F(1)) { Console.WriteLine(1); } lock (a = await F(1)) { Console.WriteLine(1); } var a = await F(1), b = await G(1); a = await F(1); switch (await F(2)) { case 1: return b = await F(1); } return await F(1); } static async Task<int> G() => await F(1); } "; var src2 = @" class C { static async Task<int> F() { await F(2); if (await F(1)) { Console.WriteLine(2); } if (await F(2)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(2); } while (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(2); } while (await F(2)); for (var x = await F(2); await G(2); await H(2)) { Console.WriteLine(2); } foreach (var x in await F(2)) { Console.WriteLine(2); } using (var x = await F(2)) { Console.WriteLine(1); } lock (await F(2)) { Console.WriteLine(2); } lock (a = await F(2)) { Console.WriteLine(2); } var a = await F(2), b = await G(2); b = await F(2); switch (await F(2)) { case 1: return b = await F(2); } return await F(2); } static async Task<int> G() => await F(2); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_Errors() { var src1 = @" class C { static async Task<int> F() { F(1, await F(1)); F(1, await F(1)); F(await F(1)); await F(await F(1)); if (F(1, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(1)), b = F(1, await G(1)); b = F(1, await F(1)); b += await F(1); } } "; var src2 = @" class C { static async Task<int> F() { F(2, await F(1)); F(1, await F(2)); F(await F(2)); await F(await F(2)); if (F(2, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(2)), b = F(1, await G(2)); b = F(1, await F(2)); b += await F(2); } } "; var edits = GetTopEdits(src1, src2); // consider: these edits can be allowed if we get more sophisticated edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "await F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1))"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b = F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b += await F(2);")); } [Fact] public void Await_Delete1() { var src1 = @" await F(1); await F(2); await F(3); "; var src2 = @" await F(1); await F(3); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Delete [await F(2);]@37", "Delete [await F(2)]@37"); } [Fact] public void Await_Delete2() { var src1 = @" class C { static async Task<int> F() { await F(1); { await F(2); } await F(3); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); { F(2); } await F(3); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "F(2);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete3() { var src1 = @" class C { static async Task<int> F() { await F(await F(1)); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await F(1);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete4() { var src1 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete5() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void AwaitForEach_Delete1() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var x in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete2() { var src1 = @" class C { static async Task<int> F() { await foreach (var (x, y) in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var (x, y) in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var (x, y) in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete3() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void AwaitUsing_Delete1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete2() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete3() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete4() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration), Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration)); } [Fact] public void Await_Insert1() { var src1 = @" await F(1); await F(3); "; var src2 = @" await F(1); await F(2); await F(3); await F(4); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Insert [await F(2);]@37", "Insert [await F(4);]@63", "Insert [await F(2)]@37", "Insert [await F(4)]@63"); } [Fact] public void Await_Insert2() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(1); await F(2); await F(3); await F(4); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert3() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(await F(1)); await F(await F(2)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert4() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert5() { var src1 = @" class C { static Task<int> F() => F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert_Ok() { var src1 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); // ok to add awaits if there were none before and no active statements edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert() { var src1 = @" class C { static async Task<int> F() { await Task.FromResult(1); foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await Task.FromResult(1); await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void AwaitUsing_Insert1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "y = new D()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Insert2() { var src1 = @" class C { static async Task<int> F() { await G(); using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await G(); await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void Await_Update() { var src1 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var x in G()) { } await Task.FromResult(1); await Task.FromResult(1); await Task.FromResult(1); yield return 1; yield break; yield break; } } "; var src2 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var (x,y) in G()) { } await foreach (var x in G()) { } await using D x = new D(), y = new D(); await Task.FromResult(1); await Task.FromResult(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "await foreach (var x in G()) { }", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_foreach_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "x = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "y = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 1;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingAsyncStateMachineAttribute1() { var src1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 1; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task<int> F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute") }); } [Fact] public void MissingAsyncStateMachineAttribute2() { var src1 = @" using System.Threading.Tasks; class C { static Task<int> F() { return null; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }); } [Fact] public void SemanticError_AwaitInPropertyAccessor() { var src1 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(1); return 1; } } } "; var src2 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(2); return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Out Var [Fact] public void OutVarType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int y);]@4"); } [Fact] public void OutVarNameAndType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int z); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int z);]@4", "Update [y]@14 -> [z]@14"); } [Fact] public void OutVar_Insert() { var src1 = @" M(); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M();]@4 -> [M(out int y);]@4", "Insert [y]@14"); } [Fact] public void OutVar_Delete() { var src1 = @" M(out int y); "; var src2 = @" M(); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out int y);]@4 -> [M();]@4", "Delete [y]@14"); } #endregion #region Pattern [Fact] public void ConstantPattern_Update() { var src1 = @" if ((o is null) && (y == 7)) return 3; if (a is 7) return 5; "; var src2 = @" if ((o1 is null) && (y == 7)) return 3; if (a is 77) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((o is null) && (y == 7)) return 3;]@4 -> [if ((o1 is null) && (y == 7)) return 3;]@4", "Update [if (a is 7) return 5;]@44 -> [if (a is 77) return 5;]@45"); } [Fact] public void DeclarationPattern_Update() { var src1 = @" if (!(o is int i) && (y == 7)) return; if (!(a is string s)) return; if (!(b is string t)) return; if (!(c is int j)) return; "; var src2 = @" if (!(o1 is int i) && (y == 7)) return; if (!(a is int s)) return; if (!(b is string t1)) return; if (!(c is int)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (!(o is int i) && (y == 7)) return;]@4 -> [if (!(o1 is int i) && (y == 7)) return;]@4", "Update [if (!(a is string s)) return;]@44 -> [if (!(a is int s)) return;]@45", "Update [if (!(c is int j)) return;]@106 -> [if (!(c is int)) return;]@105", "Update [t]@93 -> [t1]@91", "Delete [j]@121"); } [Fact] public void DeclarationPattern_Reorder() { var src1 = @"if ((a is int i) && (b is int j)) { A(); }"; var src2 = @"if ((b is int j) && (a is int i)) { A(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((a is int i) && (b is int j)) { A(); }]@2 -> [if ((b is int j) && (a is int i)) { A(); }]@2", "Reorder [j]@32 -> @16"); } [Fact] public void VarPattern_Update() { var src1 = @" if (o is (var x, var y)) return; if (o4 is (string a, var (b, c))) return; if (o2 is var (e, f, g)) return; if (o3 is var (k, l, m)) return; "; var src2 = @" if (o is (int x, int y1)) return; if (o1 is (var a, (var b, string c1))) return; if (o7 is var (g, e, f)) return; if (o3 is (string k, int l2, int m)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (o is (var x, var y)) return;]@4 -> [if (o is (int x, int y1)) return;]@4", "Update [if (o4 is (string a, var (b, c))) return;]@38 -> [if (o1 is (var a, (var b, string c1))) return;]@39", "Update [if (o2 is var (e, f, g)) return;]@81 -> [if (o7 is var (g, e, f)) return;]@87", "Reorder [g]@102 -> @102", "Update [if (o3 is var (k, l, m)) return;]@115 -> [if (o3 is (string k, int l2, int m)) return;]@121", "Update [y]@25 -> [y1]@25", "Update [c]@67 -> [c1]@72", "Update [l]@133 -> [l2]@146"); } [Fact] public void PositionalPattern_Update1() { var src1 = @"var r = (x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 }]@10 -> [((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 }]@10", "Update [(0, var b, int c) when c > 1 => 2]@29 -> [(_, int b1, double c1) when c1 > 2 => c1]@31", "Reorder [c]@44 -> @39", "Update [c]@44 -> [b1]@39", "Update [b]@37 -> [c1]@50", "Update [when c > 1]@47 -> [when c1 > 2]@54"); } [Fact] public void PositionalPattern_Update2() { var src1 = @"var r = (x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 }]@10", "Update [(var a, 3, 4) => a]@29 -> [(var a1, 3, 4) => a1 * 2]@31", "Update [(1, 1, Point { X: 0 } p) => 3]@49 -> [(1, 1, Point { Y: 0 } p1) => 3]@57", "Update [a]@34 -> [a1]@36", "Update [p]@71 -> [p1]@79"); } [Fact] public void PositionalPattern_Reorder() { var src1 = @"var r = (x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }; "; var src2 = @"var r = ((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @"Update [(x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }]@10", "Reorder [(var a, 3, 4) => a]@47 -> @100", "Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64", "Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32"); } [Fact] public void PropertyPattern_Update() { var src1 = @" if (address is { State: ""WA"" }) return 1; if (obj is { Color: Color.Purple }) return 2; if (o is string { Length: 5 } s) return 3; "; var src2 = @" if (address is { ZipCode: 98052 }) return 4; if (obj is { Size: Size.M }) return 2; if (o is string { Length: 7 } s7) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (address is { State: \"WA\" }) return 1;]@4 -> [if (address is { ZipCode: 98052 }) return 4;]@4", "Update [if (obj is { Color: Color.Purple }) return 2;]@47 -> [if (obj is { Size: Size.M }) return 2;]@50", "Update [if (o is string { Length: 5 } s) return 3;]@94 -> [if (o is string { Length: 7 } s7) return 5;]@90", "Update [return 1;]@36 -> [return 4;]@39", "Update [s]@124 -> [s7]@120", "Update [return 3;]@127 -> [return 5;]@124"); } [Fact] public void RecursivePatterns_Reorder() { var src1 = @"var r = obj switch { string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, int i => i * i, _ => -1 }; "; var src2 = @"var r = obj switch { int i => i * i, string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, _ => -1 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int i => i * i]@140 -> @29", "Move [i]@102 -> @33", "Move [i]@144 -> @123"); } [Fact] public void CasePattern_UpdateInsert() { var src1 = @" switch(shape) { case Circle c: return 1; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: return 1; case Point p: return 0; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@26 -> [case Circle c1: return 1;]@26", "Insert [case Point p: return 0;]@57", "Insert [case Point p:]@57", "Insert [return 0;]@71", "Update [c]@38 -> [c1]@38", "Insert [p]@68"); } [Fact] public void CasePattern_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: A(c); break; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: A(c1); break; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: A(c); break;]@55 -> [case Circle c1: A(c1); break;]@26", "Update [A(c);]@70 -> [A(c1);]@42", "Update [c]@67 -> [c1]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } [Fact] public void WhenCondition_Update() { var src1 = @" switch(shape) { case Circle c when (c < 10): return 1; case Circle c when (c > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c < 5): return 1; case Circle c2 when (c2 > 100): return 2; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c when (c < 10): return 1;]@26 -> [case Circle c when (c < 5): return 1;]@26", "Update [case Circle c when (c > 100): return 2;]@70 -> [case Circle c2 when (c2 > 100): return 2;]@69", "Update [when (c < 10)]@40 -> [when (c < 5)]@40", "Update [c]@82 -> [c2]@81", "Update [when (c > 100)]@84 -> [when (c2 > 100)]@84"); } [Fact] public void CasePatternWithWhenCondition_UpdateReorder() { var src1 = @" switch(shape) { case Rectangle r: return 0; case Circle c when (c.Radius < 10): return 1; case Circle c when (c.Radius > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c.Radius > 99): return 2; case Circle c when (c.Radius < 10): return 1; case Rectangle r: return 0; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case Circle c when (c.Radius < 10): return 1;]@59 -> @77", "Reorder [case Circle c when (c.Radius > 100): return 2;]@110 -> @26", "Update [case Circle c when (c.Radius > 100): return 2;]@110 -> [case Circle c when (c.Radius > 99): return 2;]@26", "Move [c]@71 -> @38", "Update [when (c.Radius > 100)]@124 -> [when (c.Radius > 99)]@40", "Move [c]@122 -> @89"); } #endregion #region Ref [Fact] public void Ref_Update() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Insert() { var src1 = @" int a = G(new int[] { 1, 2 }); int G(int[] p) { return p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int G(int[] p) { return p[1]; }]@36 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [int a = G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = G(new int[] { 1, 2 })]@8 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Delete() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" int32 a = G1(new int[] { 1, 2 }); int G1(int[] p) { return p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [int G1(int[] p) { return p[2]; }]@39", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [int32 a = G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = G1(new int[] { 1, 2 })]@10"); } #endregion #region Tuples [Fact] public void TupleType_LocalVariables() { var src1 = @" (int a, string c) x = (a, string2); (int a, int b) y = (3, 4); (int a, int b, int c) z = (5, 6, 7); "; var src2 = @" (int a, int b) x = (a, string2); (int a, int b, string c) z1 = (5, 6, 7); (int a, int b) y2 = (3, 4); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int a, int b, int c) z = (5, 6, 7);]@69 -> @39", "Update [(int a, string c) x = (a, string2)]@4 -> [(int a, int b) x = (a, string2)]@4", "Update [(int a, int b, int c) z = (5, 6, 7)]@69 -> [(int a, int b, string c) z1 = (5, 6, 7)]@39", "Update [z = (5, 6, 7)]@91 -> [z1 = (5, 6, 7)]@64", "Update [y = (3, 4)]@56 -> [y2 = (3, 4)]@96"); } [Fact] public void TupleElementName() { var src1 = @"class C { (int a, int b) F(); }"; var src2 = @"class C { (int x, int b) F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b) F();]@10 -> [(int x, int b) F();]@10"); } [Fact] public void TupleInField() { var src1 = @"class C { private (int, int) _x = (1, 2); }"; var src2 = @"class C { private (int, string) _y = (1, 2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) _x = (1, 2)]@18 -> [(int, string) _y = (1, 2)]@18", "Update [_x = (1, 2)]@29 -> [_y = (1, 2)]@32"); } [Fact] public void TupleInProperty() { var src1 = @"class C { public (int, int) Property1 { get { return (1, 2); } } }"; var src2 = @"class C { public (int, string) Property2 { get { return (1, string.Empty); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public (int, int) Property1 { get { return (1, 2); } }]@10 -> [public (int, string) Property2 { get { return (1, string.Empty); } }]@10", "Update [get { return (1, 2); }]@40 -> [get { return (1, string.Empty); }]@43"); } [Fact] public void TupleInDelegate() { var src1 = @"public delegate void EventHandler1((int, int) x);"; var src2 = @"public delegate void EventHandler2((int, int) y);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void EventHandler1((int, int) x);]@0 -> [public delegate void EventHandler2((int, int) y);]@0", "Update [(int, int) x]@35 -> [(int, int) y]@35"); } #endregion #region With Expressions [Fact] public void WithExpression_PropertyAdd() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyDelete() { var src1 = @"var x = y with { X = 1, Y = 2 };"; var src2 = @"var x = y with { X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 2 }]@6 -> [x = y with { X = 1 }]@6"); } [Fact] public void WithExpression_PropertyChange() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { Y = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { Y = 1 }]@6"); } [Fact] public void WithExpression_PropertyValueChange() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyValueReorder() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { Y = 1, X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { Y = 1, X = 1 }]@6"); } #endregion #region Top Level Statements [Fact] public void TopLevelStatement_CaptureArgs() { var src1 = @" using System; var x = new Func<string>(() => ""Hello""); Console.WriteLine(x()); "; var src2 = @" using System; var x = new Func<string>(() => ""Hello"" + args[0]); Console.WriteLine(x()); "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "using System;\r\n\r\nvar x = new Func<string>(() => \"Hello\" + args[0]);\r\n\r\nConsole.WriteLine(x());\r\n", "args")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void TopLevelStatement_InsertMultiScopeCapture() { var src1 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } "; var src2 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class StatementEditingTests : EditingTestBase { #region Strings [Fact] public void StringLiteral_update() { var src1 = @" var x = ""Hello1""; "; var src2 = @" var x = ""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = \"Hello1\"]@8 -> [x = \"Hello2\"]@8"); } [Fact] public void InterpolatedStringText_update() { var src1 = @" var x = $""Hello1""; "; var src2 = @" var x = $""Hello2""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello1\"]@8 -> [x = $\"Hello2\"]@8"); } [Fact] public void Interpolation_update() { var src1 = @" var x = $""Hello{123}""; "; var src2 = @" var x = $""Hello{124}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123}\"]@8 -> [x = $\"Hello{124}\"]@8"); } [Fact] public void InterpolationFormatClause_update() { var src1 = @" var x = $""Hello{123:N1}""; "; var src2 = @" var x = $""Hello{123:N2}""; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [x = $\"Hello{123:N1}\"]@8 -> [x = $\"Hello{123:N2}\"]@8"); } #endregion #region Variable Declaration [Fact] public void VariableDeclaration_Insert() { var src1 = "if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 1) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var x = 1;]@2", "Insert [var x = 1]@2", "Insert [x = 1]@6"); } [Fact] public void VariableDeclaration_Update() { var src1 = "int x = F(1), y = G(2);"; var src2 = "int x = F(3), y = G(4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x = F(1)]@6 -> [x = F(3)]@6", "Update [y = G(2)]@16 -> [y = G(4)]@16"); } [Fact] public void ParenthesizedVariableDeclaration_Update() { var src1 = @" var (x1, (x2, x3)) = (1, (2, true)); var (a1, a2) = (1, () => { return 7; }); "; var src2 = @" var (x1, (x2, x4)) = (1, (2, true)); var (a1, a3) = (1, () => { return 8; }); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x3]@18 -> [x4]@18", "Update [a2]@51 -> [a3]@51"); } [Fact] public void ParenthesizedVariableDeclaration_Insert() { var src1 = @"var (z1, z2) = (1, 2);"; var src2 = @"var (z1, z2, z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (z1, z2) = (1, 2);]@2 -> [var (z1, z2, z3) = (1, 2, 5);]@2", "Insert [z3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Delete() { var src1 = @"var (y1, y2, y3) = (1, 2, 7);"; var src2 = @"var (y1, y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (y1, y2, y3) = (1, 2, 7);]@2 -> [var (y1, y2) = (1, 4);]@2", "Delete [y3]@15"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed1() { var src1 = @"int a; (var z1, a) = (1, 2);"; var src2 = @"int a; (var z1, a, var z3) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, a) = (1, 2);]@9 -> [(var z1, a, var z3) = (1, 2, 5);]@9", "Insert [z3]@25"); } [Fact] public void ParenthesizedVariableDeclaration_Insert_Mixed2() { var src1 = @"int a; (var z1, var z2) = (1, 2);"; var src2 = @"int a; (var z1, var z2, a) = (1, 2, 5);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var z1, var z2) = (1, 2);]@9 -> [(var z1, var z2, a) = (1, 2, 5);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed1() { var src1 = @"int a; (var y1, var y2, a) = (1, 2, 7);"; var src2 = @"int a; (var y1, var y2) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, var y2, a) = (1, 2, 7);]@9 -> [(var y1, var y2) = (1, 4);]@9"); } [Fact] public void ParenthesizedVariableDeclaration_Delete_Mixed2() { var src1 = @"int a; (var y1, a, var y3) = (1, 2, 7);"; var src2 = @"int a; (var y1, a) = (1, 4);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(var y1, a, var y3) = (1, 2, 7);]@9 -> [(var y1, a) = (1, 4);]@9", "Delete [y3]@25"); } [Fact] public void VariableDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (c, d) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2"); } [Fact] public void VariableDeclaraions_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2); (int c, int d) = (3, 4);"; var src2 = @"int a; (int c, int d) = (3, 4); (a, int b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int c, int d) = (3, 4);]@30 -> @9"); } [Fact] public void VariableNames_Reorder() { var src1 = @"var (a, b) = (1, 2);"; var src2 = @"var (b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, b) = (1, 2);]@2 -> [var (b, a) = (2, 1);]@2", "Reorder [b]@10 -> @7"); } [Fact] public void VariableNames_Reorder_Mixed() { var src1 = @"int a; (a, int b) = (1, 2);"; var src2 = @"int a; (int b, a) = (2, 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a, int b) = (1, 2);]@9 -> [(int b, a) = (2, 1);]@9"); } [Fact] public void VariableNamesAndDeclaraions_Reorder() { var src1 = @"var (a, b) = (1, 2); var (c, d) = (3, 4);"; var src2 = @"var (d, c) = (3, 4); var (a, b) = (1, 2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (c, d) = (3, 4);]@23 -> @2", "Reorder [d]@31 -> @7"); } [Fact] public void ParenthesizedVariableDeclaration_Reorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((b, c), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((b, c), a) = ((2, 3), 1);]@2", "Reorder [a]@7 -> @15"); } [Fact] public void ParenthesizedVariableDeclaration_DoubleReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3));"; var src2 = @"var ((c, b), a) = ((2, 3), 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = ((2, 3), 1);]@2", "Reorder [b]@11 -> @11", "Reorder [c]@14 -> @8"); } [Fact] public void ParenthesizedVariableDeclaration_ComplexReorder() { var src1 = @"var (a, (b, c)) = (1, (2, 3)); var (x, (y, z)) = (4, (5, 6));"; var src2 = @"var (x, (y, z)) = (4, (5, 6)); var ((c, b), a) = (1, (2, 3)); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [var (x, (y, z)) = (4, (5, 6));]@33 -> @2", "Update [var (a, (b, c)) = (1, (2, 3));]@2 -> [var ((c, b), a) = (1, (2, 3));]@33", "Reorder [b]@11 -> @42", "Reorder [c]@14 -> @39"); } #endregion #region Switch Statement [Fact] public void Switch1() { var src1 = "switch (a) { case 1: f(); break; } switch (b) { case 2: g(); break; }"; var src2 = "switch (b) { case 2: f(); break; } switch (a) { case 1: g(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [switch (b) { case 2: g(); break; }]@37 -> @2", "Update [case 1: f(); break;]@15 -> [case 2: f(); break;]@15", "Move [case 1: f(); break;]@15 -> @15", "Update [case 2: g(); break;]@50 -> [case 1: g(); break;]@50", "Move [case 2: g(); break;]@50 -> @50"); } [Fact] public void Switch_Case_Reorder() { var src1 = "switch (expr) { case 1: f(); break; case 2: case 3: case 4: g(); break; }"; var src2 = "switch (expr) { case 2: case 3: case 4: g(); break; case 1: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case 2: case 3: case 4: g(); break;]@40 -> @18"); } [Fact] public void Switch_Case_Update() { var src1 = "switch (expr) { case 1: f(); break; }"; var src2 = "switch (expr) { case 2: f(); break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: f(); break;]@18 -> [case 2: f(); break;]@18"); } [Fact] public void CasePatternLabel_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: return 1; } "; var src2 = @" switch(shape) { case Circle circle: return 1; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@55 -> [case Circle circle: return 1;]@26", "Update [c]@67 -> [circle]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } #endregion #region Switch Expression [Fact] public void MethodUpdate_UpdateSwitchExpression1() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression2() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 1 => 0, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 1 => 0, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateSwitchExpression3() { var src1 = @" class C { static int F(int a) => a switch { 0 => 0, _ => 1 }; }"; var src2 = @" class C { static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => a switch { 0 => 0, _ => 1 };]@18 -> [static int F(int a) => a switch { 0 => 0, 1 => 1, _ => 2 };]@18"); edits.VerifyRudeDiagnostics(); } #endregion #region Try Catch Finally [Fact] public void TryInsert1() { var src1 = "x++;"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Insert [{ x++; }]@6", "Insert [catch { }]@15", "Move [x++;]@2 -> @8", "Insert [{ }]@21"); } [Fact] public void TryInsert2() { var src1 = "{ x++; }"; var src2 = "try { x++; } catch { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { x++; } catch { }]@2", "Move [{ x++; }]@2 -> @6", "Insert [catch { }]@15", "Insert [{ }]@21"); } [Fact] public void TryDelete1() { var src1 = "try { x++; } catch { }"; var src2 = "x++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [x++;]@8 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [{ x++; }]@6", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryDelete2() { var src1 = "try { x++; } catch { }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@6 -> @2", "Delete [try { x++; } catch { }]@2", "Delete [catch { }]@15", "Delete [{ }]@21"); } [Fact] public void TryReorder() { var src1 = "try { x++; } catch { /*1*/ } try { y++; } catch { /*2*/ }"; var src2 = "try { y++; } catch { /*2*/ } try { x++; } catch { /*1*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [try { y++; } catch { /*2*/ }]@31 -> @2"); } [Fact] public void Finally_DeleteHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@47 -> @39", "Delete [finally { /*3*/ }]@39"); } [Fact] public void Finally_InsertHeader() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [finally { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @47"); } [Fact] public void CatchUpdate() { var src1 = "try { } catch (Exception e) { }"; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(Exception e)]@16 -> [(IOException e)]@16"); } [Fact] public void CatchInsert() { var src1 = "try { /*1*/ } catch (Exception e) { /*2*/ } "; var src2 = "try { /*1*/ } catch (IOException e) { /*3*/ } catch (Exception e) { /*2*/ } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (IOException e) { /*3*/ }]@16", "Insert [(IOException e)]@22", "Insert [{ /*3*/ }]@38"); } [Fact] public void CatchBodyUpdate() { var src1 = "try { } catch (E e) { x++; }"; var src2 = "try { } catch (E e) { y++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@24 -> [y++;]@24"); } [Fact] public void CatchDelete() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [catch (Exception e) { }]@36", "Delete [(Exception e)]@42", "Delete [{ }]@56"); } [Fact] public void CatchReorder1() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } "; var src2 = "try { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @10"); } [Fact] public void CatchReorder2() { var src1 = "try { } catch (IOException e) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch (A e) { } catch (Exception e) { } catch (IOException e) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@36 -> @26", "Reorder [catch { }]@60 -> @10", "Insert [(A e)]@16"); } [Fact] public void CatchFilterReorder2() { var src1 = "try { } catch (Exception e) when (e != null) { } catch (Exception e) { } catch { }"; var src2 = "try { } catch when (s == 1) { } catch (Exception e) { } catch (Exception e) when (e != null) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [catch (Exception e) { }]@51 -> @34", "Reorder [catch { }]@75 -> @10", "Insert [when (s == 1)]@16"); } [Fact] public void CatchInsertDelete() { var src1 = @" try { x++; } catch (E e) { /*1*/ } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } finally { /*3*/ }"; var src2 = @" try { x++; } catch (Exception e) { /*2*/ } try { Console.WriteLine(); } catch (E e) { /*1*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E e) { /*1*/ }]@79", "Insert [(E e)]@85", "Move [{ /*1*/ }]@29 -> @91", "Delete [catch (E e) { /*1*/ }]@17", "Delete [(E e)]@23"); } [Fact] public void Catch_DeleteHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@52 -> @39", "Delete [catch (E2 e) { /*3*/ }]@39", "Delete [(E2 e)]@45"); } [Fact] public void Catch_InsertHeader1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch (E2 e) { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch (E2 e) { /*3*/ }]@39", "Insert [(E2 e)]@45", "Move [{ /*3*/ }]@39 -> @52"); } [Fact] public void Catch_DeleteHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*3*/ }]@45 -> @39", "Delete [catch { /*3*/ }]@39"); } [Fact] public void Catch_InsertHeader2() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ } catch { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [catch { /*3*/ }]@39", "Move [{ /*3*/ }]@39 -> @45"); } [Fact] public void Catch_InsertFilter1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [when (e == null)]@29"); } [Fact] public void Catch_InsertFilter2() { var src1 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22"); } [Fact] public void Catch_InsertFilter3() { var src1 = "try { /*1*/ } catch { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [(E1 e)]@22", "Insert [when (e == null)]@29"); } [Fact] public void Catch_DeleteDeclaration1() { var src1 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter1() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch (E1 e) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [when (e == null)]@29"); } [Fact] public void Catch_DeleteFilter2() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch when (e == null) { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22"); } [Fact] public void Catch_DeleteFilter3() { var src1 = "try { /*1*/ } catch (E1 e) when (e == null) { /*2*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [(E1 e)]@22", "Delete [when (e == null)]@29"); } [Fact] public void TryCatchFinally_DeleteHeader() { var src1 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var src2 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@6 -> @2", "Move [{ /*2*/ }]@22 -> @12", "Move [{ /*3*/ }]@40 -> @22", "Delete [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Delete [catch { /*2*/ }]@16", "Delete [finally { /*3*/ }]@32"); } [Fact] public void TryCatchFinally_InsertHeader() { var src1 = "{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch { /*2*/ }]@16", "Insert [finally { /*3*/ }]@32", "Move [{ /*2*/ }]@12 -> @22", "Move [{ /*3*/ }]@22 -> @40"); } [Fact] public void TryFilterFinally_InsertHeader() { var src1 = "{ /*1*/ } if (a == 1) { /*2*/ } { /*3*/ }"; var src2 = "try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [try { /*1*/ } catch when (a == 1) { /*2*/ } finally { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @6", "Insert [catch when (a == 1) { /*2*/ }]@16", "Insert [finally { /*3*/ }]@46", "Insert [when (a == 1)]@22", "Move [{ /*2*/ }]@24 -> @36", "Move [{ /*3*/ }]@34 -> @54", "Delete [if (a == 1) { /*2*/ }]@12"); } #endregion #region Blocks [Fact] public void Block_Insert() { var src1 = ""; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [{ x++; }]@2", "Insert [x++;]@4"); } [Fact] public void Block_Delete() { var src1 = "{ x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [{ x++; }]@2", "Delete [x++;]@4"); } [Fact] public void Block_Reorder() { var src1 = "{ x++; } { y++; }"; var src2 = "{ y++; } { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [{ y++; }]@11 -> @2"); } [Fact] public void Block_AddLine() { var src1 = "{ x++; }"; var src2 = @"{ // x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(); } #endregion #region Checked/Unchecked [Fact] public void Checked_Insert() { var src1 = ""; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Insert [{ x++; }]@10", "Insert [x++;]@12"); } [Fact] public void Checked_Delete() { var src1 = "checked { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [checked { x++; }]@2", "Delete [{ x++; }]@10", "Delete [x++;]@12"); } [Fact] public void Checked_Update() { var src1 = "checked { x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [checked { x++; }]@2 -> [unchecked { x++; }]@2"); } [Fact] public void Checked_DeleteHeader() { var src1 = "checked { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@10 -> @2", "Delete [checked { x++; }]@2"); } [Fact] public void Checked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "checked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [checked { x++; }]@2", "Move [{ x++; }]@2 -> @10"); } [Fact] public void Unchecked_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unchecked { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unchecked { x++; }]@2", "Move [{ x++; }]@2 -> @12"); } #endregion #region Unsafe [Fact] public void Unsafe_Insert() { var src1 = ""; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Insert [{ x++; }]@9", "Insert [x++;]@11"); } [Fact] public void Unsafe_Delete() { var src1 = "unsafe { x++; }"; var src2 = ""; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [unsafe { x++; }]@2", "Delete [{ x++; }]@9", "Delete [x++;]@11"); } [Fact] public void Unsafe_DeleteHeader() { var src1 = "unsafe { x++; }"; var src2 = "{ x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ x++; }]@9 -> @2", "Delete [unsafe { x++; }]@2"); } [Fact] public void Unsafe_InsertHeader() { var src1 = "{ x++; }"; var src2 = "unsafe { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [unsafe { x++; }]@2", "Move [{ x++; }]@2 -> @9"); } #endregion #region Using Statement [Fact] public void Using1() { var src1 = @"using (a) { using (b) { Goo(); } }"; var src2 = @"using (a) { using (c) { using (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (c) { using (b) { Goo(); } }]@14", "Insert [{ using (b) { Goo(); } }]@24", "Move [using (b) { Goo(); }]@14 -> @26"); } [Fact] public void Using_DeleteHeader() { var src1 = @"using (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [using (a) { Goo(); }]@2"); } [Fact] public void Using_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"using (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [using (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Lock Statement [Fact] public void Lock1() { var src1 = @"lock (a) { lock (b) { Goo(); } }"; var src2 = @"lock (a) { lock (c) { lock (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (c) { lock (b) { Goo(); } }]@13", "Insert [{ lock (b) { Goo(); } }]@22", "Move [lock (b) { Goo(); }]@13 -> @24"); } [Fact] public void Lock_DeleteHeader() { var src1 = @"lock (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@11 -> @2", "Delete [lock (a) { Goo(); }]@2"); } [Fact] public void Lock_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"lock (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [lock (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @11"); } #endregion #region ForEach Statement [Fact] public void ForEach1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var c in g) { foreach (var b in f) { Goo(); } }]@25", "Insert [{ foreach (var b in f) { Goo(); } }]@46", "Move [foreach (var b in f) { Goo(); }]@25 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "{ foreach (var b in f) { Goo(); } }", "{ foreach (var c in g) { foreach (var b in f) { Goo(); } } }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { Goo(); }" }, { "{ Goo(); }", "{ Goo(); }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void ForEach_Swap1() { var src1 = @"foreach (var a in e) { foreach (var b in f) { Goo(); } }"; var src2 = @"foreach (var b in f) { foreach (var a in e) { Goo(); } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach (var b in f) { Goo(); }]@25 -> @2", "Move [foreach (var a in e) { foreach (var b in f) { Goo(); } }]@2 -> @25", "Move [Goo();]@48 -> @48"); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "foreach (var a in e) { foreach (var b in f) { Goo(); } }", "foreach (var a in e) { Goo(); }" }, { "{ foreach (var b in f) { Goo(); } }", "{ Goo(); }" }, { "foreach (var b in f) { Goo(); }", "foreach (var b in f) { foreach (var a in e) { Goo(); } }" }, { "{ Goo(); }", "{ foreach (var a in e) { Goo(); } }" }, { "Goo();", "Goo();" } }; expected.AssertEqual(actual); } [Fact] public void Foreach_DeleteHeader() { var src1 = @"foreach (var a in b) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@23 -> @2", "Delete [foreach (var a in b) { Goo(); }]@2"); } [Fact] public void Foreach_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"foreach (var a in b) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [foreach (var a in b) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @23"); } [Fact] public void ForeachVariable_Update1() { var src1 = @" foreach (var (a1, a2) in e) { } foreach ((var b1, var b2) in e) { } foreach (var a in e1) { } "; var src2 = @" foreach (var (a1, a3) in e) { } foreach ((var b3, int b2) in e) { } foreach (_ in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach ((var b1, var b2) in e) { }]@37 -> [foreach ((var b3, int b2) in e) { }]@37", "Update [foreach (var a in e1) { }]@74 -> [foreach (_ in e1) { }]@74", "Update [a2]@22 -> [a3]@22", "Update [b1]@51 -> [b3]@51"); } [Fact] public void ForeachVariable_Update2() { var src1 = @" foreach (_ in e2) { } foreach (_ in e3) { A(); } "; var src2 = @" foreach (var b in e2) { } foreach (_ in e4) { A(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (_ in e2) { }]@4 -> [foreach (var b in e2) { }]@4", "Update [foreach (_ in e3) { A(); }]@27 -> [foreach (_ in e4) { A(); }]@31"); } [Fact] public void ForeachVariable_Insert() { var src1 = @" foreach (var (a3, a4) in e) { } foreach ((var b4, var b5) in e) { } "; var src2 = @" foreach (var (a3, a5, a4) in e) { } foreach ((var b6, var b4, var b5) in e) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a3, a4) in e) { }]@4 -> [foreach (var (a3, a5, a4) in e) { }]@4", "Update [foreach ((var b4, var b5) in e) { }]@37 -> [foreach ((var b6, var b4, var b5) in e) { }]@41", "Insert [a5]@22", "Insert [b6]@55"); } [Fact] public void ForeachVariable_Delete() { var src1 = @" foreach (var (a11, a12, a13) in e) { F(); } foreach ((var b7, var b8, var b9) in e) { G(); } "; var src2 = @" foreach (var (a12, a13) in e1) { F(); } foreach ((var b7, var b9) in e) { G(); } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [foreach (var (a11, a12, a13) in e) { F(); }]@4 -> [foreach (var (a12, a13) in e1) { F(); }]@4", "Update [foreach ((var b7, var b8, var b9) in e) { G(); }]@49 -> [foreach ((var b7, var b9) in e) { G(); }]@45", "Delete [a11]@18", "Delete [b8]@71"); } [Fact] public void ForeachVariable_Reorder() { var src1 = @" foreach (var (a, b) in e1) { } foreach ((var x, var y) in e2) { } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [foreach ((var x, var y) in e2) { }]@36 -> @4"); } [Fact] public void ForeachVariableEmbedded_Reorder() { var src1 = @" foreach (var (a, b) in e1) { foreach ((var x, var y) in e2) { } } "; var src2 = @" foreach ((var x, var y) in e2) { } foreach (var (a, b) in e1) { } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [foreach ((var x, var y) in e2) { }]@39 -> @4"); } #endregion #region For Statement [Fact] public void For1() { var src1 = @"for (int a = 0; a < 10; a++) { for (int a = 0; a < 20; a++) { Goo(); } }"; var src2 = @"for (int a = 0; a < 10; a++) { for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int b = 0; b < 10; b++) { for (int a = 0; a < 20; a++) { Goo(); } }]@33", "Insert [int b = 0]@38", "Insert [b < 10]@49", "Insert [b++]@57", "Insert [{ for (int a = 0; a < 20; a++) { Goo(); } }]@62", "Insert [b = 0]@42", "Move [for (int a = 0; a < 20; a++) { Goo(); }]@33 -> @64"); } [Fact] public void For_DeleteHeader() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@43 -> @2", "Delete [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Delete [int i = 10, j = 0]@7", "Delete [i = 10]@11", "Delete [j = 0]@19", "Delete [i > j]@26", "Delete [i--]@33", "Delete [j++]@38"); } [Fact] public void For_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [for (int i = 10, j = 0; i > j; i--, j++) { Goo(); }]@2", "Insert [int i = 10, j = 0]@7", "Insert [i > j]@26", "Insert [i--]@33", "Insert [j++]@38", "Move [{ Goo(); }]@2 -> @43", "Insert [i = 10]@11", "Insert [j = 0]@19"); } [Fact] public void For_DeclaratorsToInitializers() { var src1 = @"for (var i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [i = 10]@7", "Delete [var i = 10]@7", "Delete [i = 10]@11"); } [Fact] public void For_InitializersToDeclarators() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (var i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [var i = 10, j = 0]@7", "Insert [i = 10]@11", "Insert [j = 0]@19", "Delete [i = 10]@7", "Delete [j = 0]@15"); } [Fact] public void For_Declarations_Reorder() { var src1 = @"for (var i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (var j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@19 -> @11"); } [Fact] public void For_Declarations_Insert() { var src1 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1]@7 -> [var i = 0, j = 1, k = 2]@7", "Insert [k = 2]@25"); } [Fact] public void For_Declarations_Delete() { var src1 = @"for (var i = 0, j = 1, k = 2; i > j; i++, j++) { }"; var src2 = @"for (var i = 0, j = 1; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [var i = 0, j = 1, k = 2]@7 -> [var i = 0, j = 1]@7", "Delete [k = 2]@25"); } [Fact] public void For_Initializers_Reorder() { var src1 = @"for (i = 10, j = 0; i > j; i++, j++) { }"; var src2 = @"for (j = 0, i = 10; i > j; i++, j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j = 0]@15 -> @7"); } [Fact] public void For_Initializers_Insert() { var src1 = @"for (i = 10; i < 10; i++) { }"; var src2 = @"for (i = 10, j = 0; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j = 0]@15"); } [Fact] public void For_Initializers_Delete() { var src1 = @"for (i = 10, j = 0; i < 10; i++) { }"; var src2 = @"for (i = 10; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [j = 0]@15"); } [Fact] public void For_Initializers_Update() { var src1 = @"for (i = 1; i < 10; i++) { }"; var src2 = @"for (i = 2; i < 10; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i = 1]@7 -> [i = 2]@7"); } [Fact] public void For_Initializers_Update_Lambda() { var src1 = @"for (int i = 10, j = F(() => 1); i > j; i++) { }"; var src2 = @"for (int i = 10, j = F(() => 2); i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@25 -> [() => 2]@25"); } [Fact] public void For_Condition_Update() { var src1 = @"for (int i = 0; i < 10; i++) { }"; var src2 = @"for (int i = 0; i < 20; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [i < 10]@18 -> [i < 20]@18"); } [Fact] public void For_Condition_Lambda() { var src1 = @"for (int i = 0; F(() => 1); i++) { }"; var src2 = @"for (int i = 0; F(() => 2); i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@20 -> [() => 2]@20"); } [Fact] public void For_Incrementors_Reorder() { var src1 = @"for (int i = 10, j = 0; i > j; i--, j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Reorder [j++]@38 -> @33"); } [Fact] public void For_Incrementors_Insert() { var src1 = @"for (int i = 10, j = 0; i > j; i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Insert [j++]@33"); } [Fact] public void For_Incrementors_Delete() { var src1 = @"for (int i = 10, j = 0; i > j; j++, i--) { }"; var src2 = @"for (int i = 10, j = 0; i > j; j++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Delete [i--]@38"); } [Fact] public void For_Incrementors_Update() { var src1 = @"for (int i = 10, j = 0; i > j; j++) { }"; var src2 = @"for (int i = 10, j = 0; i > j; i++) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [j++]@33 -> [i++]@33"); } [Fact] public void For_Incrementors_Update_Lambda() { var src1 = @"for (int i = 10, j = 0; i > j; F(() => 1)) { }"; var src2 = @"for (int i = 10, j = 0; i > j; F(() => 2)) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [() => 1]@35 -> [() => 2]@35"); } #endregion #region While Statement [Fact] public void While1() { var src1 = @"while (a) { while (b) { Goo(); } }"; var src2 = @"while (a) { while (c) { while (b) { Goo(); } } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (c) { while (b) { Goo(); } }]@14", "Insert [{ while (b) { Goo(); } }]@24", "Move [while (b) { Goo(); }]@14 -> @26"); } [Fact] public void While_DeleteHeader() { var src1 = @"while (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@12 -> @2", "Delete [while (a) { Goo(); }]@2"); } [Fact] public void While_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"while (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @12"); } #endregion #region Do Statement [Fact] public void Do1() { var src1 = @"do { do { Goo(); } while (b); } while (a);"; var src2 = @"do { do { do { Goo(); } while(b); } while(c); } while(a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { do { Goo(); } while(b); } while(c);]@7", "Insert [{ do { Goo(); } while(b); }]@10", "Move [do { Goo(); } while (b);]@7 -> @12"); } [Fact] public void Do_DeleteHeader() { var src1 = @"do { Goo(); } while (a);"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@5 -> @2", "Delete [do { Goo(); } while (a);]@2"); } [Fact] public void Do_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"do { Goo(); } while (a);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { Goo(); } while (a);]@2", "Move [{ Goo(); }]@2 -> @5"); } #endregion #region If Statement [Fact] public void IfStatement_TestExpression_Update() { var src1 = "var x = 1; if (x == 1) { x++; }"; var src2 = "var x = 1; if (x == 2) { x++; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (x == 1) { x++; }]@13 -> [if (x == 2) { x++; }]@13"); } [Fact] public void ElseClause_Insert() { var src1 = "if (x == 1) x++; "; var src2 = "if (x == 1) x++; else y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else y++;]@19", "Insert [y++;]@24"); } [Fact] public void ElseClause_InsertMove() { var src1 = "if (x == 1) x++; else y++;"; var src2 = "if (x == 1) x++; else if (x == 2) y++;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (x == 2) y++;]@24", "Move [y++;]@24 -> @36"); } [Fact] public void If1() { var src1 = @"if (a) if (b) Goo();"; var src2 = @"if (a) if (c) if (b) Goo();"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (c) if (b) Goo();]@9", "Move [if (b) Goo();]@9 -> @16"); } [Fact] public void If_DeleteHeader() { var src1 = @"if (a) { Goo(); }"; var src2 = @"{ Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(); }]@9 -> @2", "Delete [if (a) { Goo(); }]@2"); } [Fact] public void If_InsertHeader() { var src1 = @"{ Goo(); }"; var src2 = @"if (a) { Goo(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { Goo(); }]@2", "Move [{ Goo(); }]@2 -> @9"); } [Fact] public void Else_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@30 -> @25", "Delete [else { Goo(/*2*/); }]@25"); } [Fact] public void Else_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else { Goo(/*2*/); }]@25", "Move [{ Goo(/*2*/); }]@25 -> @30"); } [Fact] public void ElseIf_DeleteHeader() { var src1 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ Goo(/*2*/); }]@37 -> @25", "Delete [else if (b) { Goo(/*2*/); }]@25", "Delete [if (b) { Goo(/*2*/); }]@30"); } [Fact] public void ElseIf_InsertHeader() { var src1 = @"if (a) { Goo(/*1*/); } { Goo(/*2*/); }"; var src2 = @"if (a) { Goo(/*1*/); } else if (b) { Goo(/*2*/); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [else if (b) { Goo(/*2*/); }]@25", "Insert [if (b) { Goo(/*2*/); }]@30", "Move [{ Goo(/*2*/); }]@25 -> @37"); } [Fact] public void IfElseElseIf_InsertHeader() { var src1 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var src2 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Move [{ /*1*/ }]@2 -> @9", "Insert [else if (b) { /*2*/ } else { /*3*/ }]@19", "Insert [if (b) { /*2*/ } else { /*3*/ }]@24", "Move [{ /*2*/ }]@12 -> @31", "Insert [else { /*3*/ }]@41", "Move [{ /*3*/ }]@22 -> @46"); } [Fact] public void IfElseElseIf_DeleteHeader() { var src1 = @"if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }"; var src2 = @"{ /*1*/ } { /*2*/ } { /*3*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Move [{ /*1*/ }]@9 -> @2", "Move [{ /*2*/ }]@31 -> @12", "Move [{ /*3*/ }]@46 -> @22", "Delete [if (a) { /*1*/ } else if (b) { /*2*/ } else { /*3*/ }]@2", "Delete [else if (b) { /*2*/ } else { /*3*/ }]@19", "Delete [if (b) { /*2*/ } else { /*3*/ }]@24", "Delete [else { /*3*/ }]@41"); } #endregion #region Switch Statement [Fact] public void SwitchStatement_Update_Expression() { var src1 = "var x = 1; switch (x + 1) { case 1: break; }"; var src2 = "var x = 1; switch (x + 2) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [switch (x + 1) { case 1: break; }]@13 -> [switch (x + 2) { case 1: break; }]@13"); } [Fact] public void SwitchStatement_Update_SectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_AddSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: break;]@26 -> [case 1: case 2: break;]@26"); } [Fact] public void SwitchStatement_Update_DeleteSectionLabel() { var src1 = "var x = 1; switch (x) { case 1: case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case 1: case 2: break;]@26 -> [case 1: break;]@26"); } [Fact] public void SwitchStatement_Update_BlockInSection() { var src1 = "var x = 1; switch (x) { case 1: { x++; break; } }"; var src2 = "var x = 1; switch (x) { case 1: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@36 -> [x--;]@36"); } [Fact] public void SwitchStatement_Update_BlockInDefaultSection() { var src1 = "var x = 1; switch (x) { default: { x++; break; } }"; var src2 = "var x = 1; switch (x) { default: { x--; break; } }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [x++;]@37 -> [x--;]@37"); } [Fact] public void SwitchStatement_Insert_Section() { var src1 = "var x = 1; switch (x) { case 1: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [case 2: break;]@41", "Insert [break;]@49"); } [Fact] public void SwitchStatement_Delete_Section() { var src1 = "var x = 1; switch (x) { case 1: break; case 2: break; }"; var src2 = "var x = 1; switch (x) { case 1: break; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [case 2: break;]@41", "Delete [break;]@49"); } #endregion #region Lambdas [Fact] public void Lambdas_AddAttribute() { var src1 = "Func<int, int> x = (a) => a;"; var src2 = "Func<int, int> x = [A][return:A]([A]a) => a;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(a) => a]@21 -> [[A][return:A]([A]a) => a]@21", "Update [a]@22 -> [[A]a]@35"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.method), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "([A]a)", FeaturesResources.parameter)); GetTopEdits(edits).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_InVariableDeclarator() { var src1 = "Action x = a => a, y = b => b;"; var src2 = "Action x = (a) => a, y = b => b + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@13 -> [(a) => a]@13", "Update [b => b]@25 -> [b => b + 1]@27", "Insert [(a)]@13", "Insert [a]@14", "Delete [a]@13"); } [Fact] public void Lambdas_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "F(b => b, a => a+1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => b]@12 -> @4", "Update [a => a]@4 -> [a => a+1]@12"); } [Fact] public void Lambdas_ReorderArguments() { var src1 = "F(G(a => {}), G(b => {}));"; var src2 = "F(G(b => {}), G(a => {}));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [b => {}]@18 -> @6"); } [Fact] public void Lambdas_InWhile() { var src1 = "while (F(a => a)) { /*1*/ }"; var src2 = "do { /*1*/ } while (F(a => a));"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [do { /*1*/ } while (F(a => a));]@2", "Move [{ /*1*/ }]@20 -> @5", "Move [a => a]@11 -> @24", "Delete [while (F(a => a)) { /*1*/ }]@2"); } [Fact] public void Lambdas_InLambda_ChangeInLambdaSignature() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer lambda signature: edits.VerifyEdits( "Update [() => { G(x => y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void Lambdas_InLambda_ChangeOnlyInLambdaBody() { var src1 = "F(() => { G(x => y); });"; var src2 = "F(() => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer lambda body: edits.VerifyEdits(); } [Fact] public void Lambdas_Update_ParameterRefness_NoBodyChange() { var src1 = @"F((ref int a) => a = 1);"; var src2 = @"F((out int a) => a = 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@5 -> [out int a]@5"); } [Fact] public void Lambdas_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_Static_Nested1() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => G(b => b) + a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => x); } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] public void Lambdas_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f1 = new Func<int, int>(a => y); } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { G(a => G(b => x)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); return a; }); } } "; var src2 = @" using System; class C { int x = 0; void F() { var f1 = new Func<int, int>(a => { var f2 = new Func<int, int>(b => { return b; }); var f3 = new Func<int, int>(c => { return c + x; }); return a; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 G(a => x3 + x1); G(a => x0 + y0 + x2); G(a => x); G(a => x); // OK G(a => x0 + y0); // OK G(a => x1 + y0); // error - connecting Group #1 and Group #2 G(a => x3 + x1); // error - multi-scope (conservative) G(a => x + y0); // error - connecting Group #0 and Group #1 G(a => x + x3); // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.lambda, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.lambda, "this", "x3")); } [Fact] public void Lambdas_Insert_ForEach1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; G(a => x0); G(a => x1); G(a => x0 + x1); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_ForEach2() { var src1 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, null); } } "; var src2 = @" using System; class C { void G(Func<int, int> f1, Func<int, int> f2, Func<int, int> f3) {} void F() { int x0 = 0; // Group #0 foreach (int x1 in new[] { 1 }) // Group #1 G(a => x0, a => x1, a => x0 + x1); // error: connecting previously disconnected closures } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_For1() { var src1 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); } } } "; var src2 = @" using System; class C { bool G(Func<int, int> f) => true; void F() { for (int x0 = 0, x1 = 0; G(a => x0) && G(a => x1);) { int x2 = 0; G(a => x2); G(a => x0 + x1); // ok G(a => x0 + x2); // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x2", CSharpFeaturesResources.lambda, "x0", "x2")); } [Fact] public void Lambdas_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); break; case 2: int x1 = 1; G(() => x1); break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; G(() => x2); switch (a) { case 1: int x0 = 1; G(() => x0); goto case 2; case 2: int x1 = 1; G(() => x1); goto default; default: x0 = 1; x1 = 2; G(() => x0 + x1); // ok G(() => x0 + x2); // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x2", "x0")); } [Fact] public void Lambdas_Insert_Using1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static IDisposable D() => null; static void F() { using (IDisposable x0 = D(), y0 = D()) { int x1 = 1; G(() => x0); G(() => y0); G(() => x1); G(() => F(x0, y0)); // ok G(() => F(x0, x1)); // error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_Insert_Catch1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static int F(object a, object b) => 1; static void F() { try { } catch (Exception x0) { int x1 = 1; G(() => x0); G(() => x1); G(() => x0); //ok G(() => F(x0, x1)); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact, WorkItem(1504, "https://github.com/dotnet/roslyn/issues/1504")] public void Lambdas_Insert_CatchFilter1() { var src1 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0)) { } } } "; var src2 = @" using System; class C { static bool G<T>(Func<T> f) => true; static void F() { Exception x1 = null; try { G(() => x1); } catch (Exception x0) when (G(() => x0) && G(() => x0) && // ok G(() => x0 != x1)) // error { G(() => x0); // ok } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.lambda, "x1", "x0") ); } [Fact] public void Lambdas_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_Second_NotSupported() { var src1 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { void F() { var f = new Func<int, int>(a => a); var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Insert_FirstInClass_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { var g = new Func<int, int>(b => b); } } "; var capabilities = EditAndContinueCapabilities.Baseline | EditAndContinueCapabilities.NewTypeDefinition; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities, // TODO: https://github.com/dotnet/roslyn/issues/52759 // This is incorrect, there should be no rude edit reported Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "b", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var src2 = @" using System; class C { int x; void F() { var f = new Func<int, int>(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_Signature1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<long, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature2() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature3() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, long> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_Nullable() { var src1 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<string, string> f) {} void G2(Func<string?, string?> f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_SyntaxOnly1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2((a) => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Action<int> f) {} void F() { G2(a => { }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ReturnType2() { var src1 = "var x = int (int a) => a;"; var src2 = "var x = long (int a) => a;"; var edits = GetMethodEdits(src1, src2); GetTopEdits(edits).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => { return 1; }); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { G2(b => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Signature_ParameterRefness1() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1((ref int a) => 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2((int a) => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(int a)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Signature_ParameterRefness2() { var src1 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((ref int a) => a = 1); } } "; var src2 = @" using System; delegate int D1(ref int a); delegate int D2(out int a); class C { void G(D1 f) {} void G(D2 f) {} void F() { G((out int a) => a = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(out int a)", CSharpFeaturesResources.lambda)); } // Add corresponding test to VB [Fact(Skip = "TODO")] public void Lambdas_Update_Signature_CustomModifiers1() { var delegateSource = @" .class public auto ansi sealed D1 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Int64) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D2 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } } .class public auto ansi sealed D3 extends [mscorlib]System.MulticastDelegate { .method public specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public newslot virtual instance int32 [] modopt([mscorlib]System.Boolean) Invoke( int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) a, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsConst) b) runtime managed { } }"; var src1 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; MetadataReference delegateDefs; using (var tempAssembly = IlasmUtilities.CreateTempAssembly(delegateSource)) { delegateDefs = MetadataReference.CreateFromImage(File.ReadAllBytes(tempAssembly.Path)); } var edits = GetTopEdits(src1, src2); // TODO edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Signature_MatchingErrorType() { var src1 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 1); } } "; var src2 = @" using System; class C { void G(Func<Unknown, Unknown> f) {} void F() { G(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("F").Single(), preserveLocalVariables: true) }); } [Fact] public void Lambdas_Signature_NonMatchingErrorType() { var src1 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G1(a => 1); } } "; var src2 = @" using System; class C { void G1(Func<Unknown1, Unknown1> f) {} void G2(Func<Unknown2, Unknown2> f) {} void F() { G2(a => 2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", "lambda")); } [Fact] public void Lambdas_Update_DelegateType1() { var src1 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate int D1(int a); delegate int D2(int a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType1() { var src1 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate C D2(C a); class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_SourceType2() { var src1 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } "; var src2 = @" using System; delegate C D1(C a); delegate B D2(B a); class B { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_SourceTypeAndMetadataType1() { var src1 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G1(a => a); } } } "; var src2 = @" namespace System { delegate string D1(string a); delegate String D2(String a); class String { } class C { void G1(D1 f) {} void G2(D2 f) {} void F() { G2(a => a); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "a", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Generic1() { var src1 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G1((a, b) => a + b); } } "; var src2 = @" delegate T D1<S, T>(S a, T b); delegate T D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, int> f) {} void F() { G2((a, b) => a + b); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Generic2() { var src1 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G1((a, b) => 1); } } "; var src2 = @" delegate int D1<S, T>(S a, T b); delegate int D2<S, T>(T a, S b); class C { void G1(D1<int, int> f) {} void G2(D2<int, string> f) {} void F() { G2((a, b) => 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "(a, b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void Lambdas_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F(int x1) { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); var f3 = new Func<int, int, int>((a1, a2) => { var f4 = new Func<int, int>(a3 => x1 + a2 + 1); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a2", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_IndexerParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { new Action(() => { Console.Write(value); }).Invoke(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(234448, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=234448")] public void Lambdas_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => y + a2); return y; }); } } "; var src2 = @" using System; class C { void F() { // error var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y").WithFirstLine("{ // error")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a2); } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a2); } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { var f = new Func<int, int>(a3 => a1 + a2); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact] public void Lambdas_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { new Action(() => { Console.Write(value); }).Invoke(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1); } } "; var src2 = @" using System; class C { void F(int a1, int a2) { var f2 = new Func<int, int>(a3 => a1 + a2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_MethodParameter2() { var src1 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1); } "; var src2 = @" using System; class C { Func<int, int> F(int a1, int a2) => new Func<int, int>(a3 => a1 + a2); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact] public void Lambdas_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { var f1 = new Func<int, int, int>((a1, a2) => { var f2 = new Func<int, int>(a3 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact] public void Lambdas_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact] public void Lambdas_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a); } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { var f = new Func<int, int>(a => a + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this").WithFirstLine("partial void F() // impl")); } [Fact] public void Lambdas_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { int x = 1; void F() { var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a1", "this", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => a1); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var src2 = @" using System; class C { void F() { int x = 1; var f1 = new Func<int, int>(a1 => { return a1 + x+ // 1 x; // 2 }); var f2 = new Func<int, int>(a2 => a2 + x); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x+ // 1"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.lambda).WithFirstLine("x; // 2")); } [Fact] public void Lambdas_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; var f1 = new Func<int, int>(a1 => a1 + x + y); var f2 = new Func<int, int>(a2 => a2 + x + y); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2 + y); return a1 + y; }); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Lambdas_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a2); return a1; }); } } "; var src2 = @" using System; class C { void F() { int y = 1; var f1 = new Func<int, int>(a1 => { var f2 = new Func<int, int>(a2 => a1 + a2); return a1; }); } } "; var edits = GetTopEdits(src1, src2); // TODO: better diagnostics - identify a1 that causes the capture vs. a1 that doesn't edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1").WithFirstLine("var f1 = new Func<int, int>(a1 =>")); } [Fact] public void Lambdas_Update_Accessing_Closure1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0); } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { int x0 = 0, y0 = 0; G(a => x0); G(a => y0 + x0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure2() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure3() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x0", "x0", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_Update_Accessing_Closure4() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x + x0); G(a => x0); G(a => y0); G(a => x1); G(a => y1); } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0; // Group #0 void F() { { int x0 = 0, y0 = 0; // Group #0 { int x1 = 0, y1 = 0; // Group #1 G(a => x); // error: disconnecting previously connected closures G(a => x0); G(a => y0); G(a => x1); G(a => y1 + x0); // error: connecting previously disconnected closures } } } } "; var edits = GetTopEdits(src1, src2); // TODO: "a => x + x0" is matched with "a => y1 + x0", hence we report more errors. // Including statement distance when matching would help. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y1", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => y1 + x0); // error: connecting previously disconnected closures"), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "this", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures"), Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "a", "y1", CSharpFeaturesResources.lambda).WithFirstLine("G(a => x); // error: disconnecting previously connected closures")); } [Fact] public void Lambdas_Update_Accessing_Closure_NestedLambdas() { var src1 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); } } } } "; var src2 = @" using System; class C { void G(Func<int, Func<int, int>> f) {} void F() { { int x0 = 0; // Group #0 { int x1 = 0; // Group #1 G(a => b => x0); G(a => b => x1); G(a => b => x0); // ok G(a => b => x1); // ok G(a => b => x0 + x1); // error } } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.lambda, "x0", "x1")); } [Fact] public void Lambdas_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void Lambdas_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { Func<int> f = () => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { Func<int> f = () => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_Parameter_To_Discard1() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((a, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard2() { var src1 = "var x = new System.Func<int, int, int>((int a, int b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int a]@42 -> [_]@42", "Update [int b]@49 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } [Fact] public void Lambdas_Parameter_To_Discard3() { var src1 = "var x = new System.Func<int, int, int>((a, b) => 1);"; var src2 = "var x = new System.Func<int, int, int>((_, _) => 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a]@42 -> [_]@42", "Update [b]@45 -> [_]@45"); GetTopEdits(edits).VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: true)); } #endregion #region Local Functions [Fact] public void LocalFunctions_InExpressionStatement() { var src1 = "F(a => a, b => b);"; var src2 = "int x(int a) => a + 1; F(b => b, x);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [a => a]@4 -> [int x(int a) => a + 1;]@2", "Move [a => a]@4 -> @2", "Update [F(a => a, b => b);]@2 -> [F(b => b, x);]@25", "Insert [(int a)]@7", "Insert [int a]@8", "Delete [a]@4"); } [Fact] public void LocalFunctions_ReorderAndUpdate() { var src1 = "int x(int a) => a; int y(int b) => b;"; var src2 = "int y(int b) => b; int x(int a) => a + 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int y(int b) => b;]@21 -> @2", "Update [int x(int a) => a;]@2 -> [int x(int a) => a + 1;]@21"); } [Fact] public void LocalFunctions_InWhile() { var src1 = "do { /*1*/ } while (F(x));int x(int a) => a + 1;"; var src2 = "while (F(a => a)) { /*1*/ }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [while (F(a => a)) { /*1*/ }]@2", "Update [int x(int a) => a + 1;]@28 -> [a => a]@11", "Move [int x(int a) => a + 1;]@28 -> @11", "Move [{ /*1*/ }]@5 -> @20", "Insert [a]@11", "Delete [do { /*1*/ } while (F(x));]@2", "Delete [(int a)]@33", "Delete [int a]@34"); } [Fact] public void LocalFunctions_InLocalFunction_NoChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x() { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // no changes to the method were made, only within the outer local function body: edits.VerifyEdits(); } [Fact] public void LocalFunctions_InLocalFunction_ChangeInSignature() { var src1 = "int x() { int y(int a) => a; return y(b); }"; var src2 = "int x(int z) { int y() => c; return y(); }"; var edits = GetMethodEdits(src1, src2); // changes were made to the outer local function signature: edits.VerifyEdits("Insert [int z]@8"); } [Fact] public void LocalFunctions_InLambda() { var src1 = "F(() => { int y(int a) => a; G(y); });"; var src2 = "F(q => { G(() => y); });"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [() => { int y(int a) => a; G(y); }]@4 -> [q => { G(() => y); }]@4", "Insert [q]@4", "Delete [()]@4"); } [Fact] public void LocalFunctions_Update_ParameterRefness_NoBodyChange() { var src1 = @"void f(ref int a) => a = 1;"; var src2 = @"void f(out int a) => a = 1;"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int a]@9 -> [out int a]@9"); } [Fact] public void LocalFunctions_Insert_Static_Top() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_ExpressionBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) => a; int localG(int a) => G(localF) + a; G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Insert_Static_Nested_BlockBodies() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } int localG(int a) { return G(localF) + a; } G(localG); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_LocalFunction_Replace_Lambda() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var edits = GetTopEdits(src1, src2); // To be removed when we will enable EnC for local functions edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "localF", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Lambda_Replace_LocalFunction() { var src1 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { int localF(int a) { return a; } G(localF); } } "; var src2 = @" using System; class C { static int G(Func<int, int> f) => 0; void F() { G(a => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.SwitchBetweenLambdaAndLocalFunction, "a", CSharpFeaturesResources.lambda)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top1() { var src1 = @" using System; class C { int x = 0; void F() { } } "; var src2 = @" using System; class C { int x = 0; void F() { int G(int a) => x; } } "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291"), WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Top2() { var src1 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; int f1(int a) => y; } } } "; var src2 = @" using System; using System.Linq; class C { void F() { int y = 1; { int x = 2; var f2 = from a in new[] { 1 } select a + y; var f3 = from a in new[] { 1 } where x > 0 select a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "x", "x")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested1() { var src1 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => a; G(f); } } "; var src2 = @" using System; class C { int x = 0; int G(Func<int, int> f) => 0; void F() { int f(int a) => x; int g(int a) => G(f); G(g); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ThisOnly_Nested2() { var src1 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; return a; }; } } "; var src2 = @" using System; class C { int x = 0; void F() { int f1(int a) { int f2(int b) { return b; }; int f3(int c) { return c + x; }; return a; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_InsertAndDelete_Scopes1() { var src1 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; } } } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} int x = 0, y = 0; // Group #0 void F() { int x0 = 0, y0 = 0; // Group #1 { int x1 = 0, y1 = 0; // Group #2 { int x2 = 0, y2 = 0; // Group #1 { int x3 = 0, y3 = 0; // Group #2 int f1(int a) => x3 + x1; int f2(int a) => x0 + y0 + x2; int f3(int a) => x; int f4(int a) => x; // OK int f5(int a) => x0 + y0; // OK int f6(int a) => x1 + y0; // error - connecting Group #1 and Group #2 int f7(int a) => x3 + x1; // error - multi-scope (conservative) int f8(int a) => x + y0; // error - connecting Group #0 and Group #1 int f9(int a) => x + x3; // error - connecting Group #0 and Group #2 } } } } } "; var insert = GetTopEdits(src1, src2); insert.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); var delete = GetTopEdits(src2, src1); delete.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "y0", "x1"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "x1", "x3"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "y0", CSharpFeaturesResources.local_function, "this", "y0"), Diagnostic(RudeEditKind.DeleteLambdaWithMultiScopeCapture, "x3", CSharpFeaturesResources.local_function, "this", "x3")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_ForEach1() { var src1 = @" using System; class C { void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } } } "; var src2 = @" using System; class C { void G(Func<int, int> f) {} void F() { foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Switch1() { var src1 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; break; case 2: int x1 = 1; int f1() => x1; break; } } } "; var src2 = @" using System; class C { bool G(Func<int> f) => true; int a = 1; void F() { int x2 = 1; int f2() => x2; switch (a) { case 1: int x0 = 1; int f0() => x0; goto case 2; case 2: int x1 = 1; int f1() => x1; goto default; default: x0 = 1; x1 = 2; int f01() => x0 + x1; // ok int f02() => x0 + x2; // error break; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x0", CSharpFeaturesResources.local_function, "x2", "x0")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Insert_Catch1() { var src1 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; } } } "; var src2 = @" using System; class C { static void F() { try { } catch (Exception x0) { int x1 = 1; int f0() => x0; int f1() => x1; int f00() => x0; //ok int f01() => F(x0, x1); //error } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } [Fact] public void LocalFunctions_Insert_NotSupported() { var src1 = @" using System; class C { void F() { } } "; var src2 = @" using System; class C { void F() { void M() { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( activeStatements: ActiveStatementsDescription.Empty, capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "M", FeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_This() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var src2 = @" using System; class C { int x; void F() { int f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "F", "this")); } [Fact] public void LocalFunctions_Update_Signature1() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(long a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature2() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { int f(int a, int b) => a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature3() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void F() { long f(int a) => a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ReturnType1() { var src1 = @" using System; class C { void F() { int f(int a) { return 1; } } } "; var src2 = @" using System; class C { void F() { void f(int a) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_BodySyntaxOnly() { var src1 = @" using System; class C { void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { void G1(Func<int, int> f) {} void G2(Func<int, int> f) {} void F() { int f(int a) { return a; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterName1() { var src1 = @" using System; class C { void F() { int f(int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int b) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness1() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness2() { var src1 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(ref int a) => 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Signature_ParameterRefness3() { var src1 = @" using System; class C { void F() { int f(ref int a) => 1; } } "; var src2 = @" using System; class C { void F() { int f(out int a) => 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "f", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Signature_SemanticErrors() { var src1 = @" using System; class C { void F() { Unknown f(Unknown a) => 1; } } "; var src2 = @" using System; class C { void F() { Unknown f(Unknown a) => 2; } } "; var edits = GetTopEdits(src1, src2); // There are semantics errors in the case. The errors are captured during the emit execution. edits.VerifySemanticDiagnostics(); } [Fact] public void LocalFunctions_Update_CapturedParameters1() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(2223, "https://github.com/dotnet/roslyn/issues/2223")] public void LocalFunctions_Update_CapturedParameters2() { var src1 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F(int x1) { int f1(int a1, int a2) { int f2(int a3) => x1 + a2 + 1; return a1; }; int f3(int a1, int a2) { int f4(int a3) => x1 + a2 + 1; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_Closure1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); // y is no longer captured in f2 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "f2", "y", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerParameter() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "int f1(int a1, int a2)\r\n {\r\n int f2(int a3) => a2;\r\n return a1;\r\n };\r\n ", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_SetterValueParameter1() { var src1 = @" using System; class C { int D { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int D { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { void f() { Console.Write(value); } f(); } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "add", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_CeaseCapture_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var src2 = @" using System; class C { event Action D { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_DeleteCapture1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => y + a2; return y; }; } } "; var src2 = @" using System; class C { void F() { // error int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.DeletingCapturedVariable, "{", "y")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerGetterParameter2() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a2; return f; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { int f(int a3) => a1 + a2; return f; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterParameter1() { var src1 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a2; } } } "; var src2 = @" using System; class C { Func<int, int> this[int a1, int a2] { get { return null; } set { int f(int a3) => a1 + a2; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_IndexerSetterValueParameter1() { var src1 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { } } } "; var src2 = @" using System; class C { int this[int a1, int a2] { get { return 0; } set { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "set", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventAdderValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_EventRemoverValueParameter1() { var src1 = @" using System; class C { event Action D { add { } remove { } } } "; var src2 = @" using System; class C { event Action D { add { } remove { void f() { Console.Write(value); } f(); } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "remove", "value")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_MethodParameter1() { var src1 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1; } } "; var src2 = @" using System; class C { void F(int a1, int a2) { int f2(int a3) => a1 + a2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a2", "a2")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Capturing_LambdaParameter1() { var src1 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int f1(int a1, int a2) { int f2(int a3) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly1() { var src1 = @" using System; class C { int x = 1; void F() { int f(int a) => a; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly_Partial() { var src1 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a; } } "; var src2 = @" using System; partial class C { int x = 1; partial void F(); // def } partial class C { partial void F() // impl { int f(int a) => a + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "F", "this")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToThisOnly3() { var src1 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { int x = 1; void F() { int f1(int a1) => a1 + x; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "f1", "this", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_StaticToClosure1() { var src1 = @" using System; class C { void F() { int x = 1; int f1(int a1) => a1; int f2(int a2) => a2 + x; } } "; var src2 = @" using System; class C { void F() { int x = 1; int f1(int a1) { return a1 + x+ // 1 x; // 2 }; int f2(int a2) => a2 + x; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "x", "x", CSharpFeaturesResources.local_function)); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_ThisOnlyToClosure1() { var src1 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x; int f2(int a2) => a2 + x + y; } } "; var src2 = @" using System; class C { int x = 1; void F() { int y = 1; int f1(int a1) => a1 + x + y; int f2(int a2) => a2 + x + y; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "y", "y", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunctions_Update_Nested1() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2 + y; return a1 + y; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_Update_Nested2() { var src1 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a2; return a1; }; } } "; var src2 = @" using System; class C { void F() { int y = 1; int f1(int a1) { int f2(int a2) => a1 + a2; return a1; }; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "a1", "a1")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void LocalFunctions_RenameCapturedLocal() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main() { int x = 1; int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main() { int X = 1; int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.RenamingCapturedVariable, "X", "x", "X")); } [Fact] public void LocalFunctions_RenameCapturedParameter() { var src1 = @" using System; using System.Diagnostics; class Program { static void Main(int x) { int f() => x; } }"; var src2 = @" using System; using System.Diagnostics; class Program { static void Main(int X) { int f() => X; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.Main"), preserveLocalVariables: true) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void LocalFunction_In_Parameter_InsertWhole() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_In_Parameter_InsertParameter() { var src1 = @"class Test { void M() { void local() { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local() { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_In_Parameter_Update() { var src1 = @"class Test { void M() { void local(int b) { throw null; } } }"; var src2 = @"class Test { void M() { void local(in int b) { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { void local(int b) { throw null; } }]@13 -> [void M() { void local(in int b) { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaParameters, "local", CSharpFeaturesResources.local_function)); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Insert() { var src1 = @"class Test { void M() { } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ReadOnlyRef_ReturnType_Update() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { ref readonly int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { ref readonly int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingLambdaReturnType, "local", CSharpFeaturesResources.local_function)); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void LocalFunction_AddToInterfaceMethod() { var src1 = @" using System; interface I { static int X = M(() => 1); static int M() => 1; static void F() { void g() { } } } "; var src2 = @" using System; interface I { static int X = M(() => { void f3() {} return 2; }); static int M() => 1; static void F() { int f1() => 1; f1(); void g() { void f2() {} f2(); } var l = new Func<int>(() => 1); l(); } } "; var edits = GetTopEdits(src1, src2); // lambdas are ok as they are emitted to a nested type edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.NetCoreApp }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f1"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f2"), Diagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, "f3") }); } [Fact] public void LocalFunction_AddStatic() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { static int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { static int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveStatic() { var src1 = @"class Test { void M() { static int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { static int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_AddUnsafe() { var src1 = @"class Test { void M() { int local() { throw null; } } }"; var src2 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { int local() { throw null; } }]@13 -> [void M() { unsafe int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_RemoveUnsafe() { var src1 = @"class Test { void M() { unsafe int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void M() { unsafe int local() { throw null; } }]@13 -> [void M() { int local() { throw null; } }]@13"); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_AddAsync() { var src1 = @"class Test { void M() { Task<int> local() => throw null; } }"; var src2 = @"class Test { void M() { async Task<int> local() => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunction_RemoveAsync() { var src1 = @"class Test { void M() { async int local() { throw null; } } }"; var src2 = @"class Test { void M() { int local() { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "local", FeaturesResources.local_function)); } [Fact] public void LocalFunction_AddAttribute() { var src1 = "void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [void L() { }]@2 -> [[A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_RemoveAttribute() { var src1 = "[A]void L() { }"; var src2 = "void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]void L() { }]@2 -> [void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReorderAttribute() { var src1 = "[A, B]void L() { }"; var src2 = "[B, A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]void L() { }]@2 -> [[B, A]void L() { }]@2"); // Get top edits so we can validate rude edits GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_CombineAttributeLists() { var src1 = "[A][B]void L() { }"; var src2 = "[A, B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A][B]void L() { }]@2 -> [[A, B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_SplitAttributeLists() { var src1 = "[A, B]void L() { }"; var src2 = "[A][B]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]void L() { }]@2 -> [[A][B]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_ChangeAttributeListTarget1() { var src1 = "[return: A]void L() { }"; var src2 = "[A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A]void L() { }]@2 -> [[A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ChangeAttributeListTarget2() { var src1 = "[A]void L() { }"; var src2 = "[return: A]void L() { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A]void L() { }]@2 -> [[return: A]void L() { }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_AddAttribute() { var src1 = "int L() { return 1; }"; var src2 = "[return: A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int L() { return 1; }]@2 -> [[return: A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_RemoveAttribute() { var src1 = "[return: A]int L() { return 1; }"; var src2 = "int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[return: A]int L() { return 1; }]@2 -> [int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunction_ReturnType_ReorderAttribute() { var src1 = "[return: A, B]int L() { return 1; }"; var src2 = "[return: B, A]int L() { return 1; }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[return: A, B]int L() { return 1; }]@2 -> [[return: B, A]int L() { return 1; }]@2"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_Parameter_AddAttribute() { var src1 = "void L(int i) { }"; var src2 = "void L([A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int i]@9 -> [[A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_RemoveAttribute() { var src1 = "void L([A]int i) { }"; var src2 = "void L(int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A]int i]@9 -> [int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.parameter)); } [Fact] public void LocalFunction_Parameter_ReorderAttribute() { var src1 = "void L([A, B]int i) { }"; var src2 = "void L([B, A]int i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B]int i]@9 -> [[B, A]int i]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunction_TypeParameter_AddAttribute() { var src1 = "void L<T>(T i) { }"; var src2 = "void L<[A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [T]@9 -> [[A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_RemoveAttribute() { var src1 = "void L<[A] T>(T i) { }"; var src2 = "void L<T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [[A] T]@9 -> [T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "L", FeaturesResources.type_parameter)); } [Fact] public void LocalFunction_TypeParameter_ReorderAttribute() { var src1 = "void L<[A, B] T>(T i) { }"; var src2 = "void L<[B, A] T>(T i) { }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits("Update [[A, B] T]@9 -> [[B, A] T]@9"); GetTopEdits(edits).VerifyRudeDiagnostics(); } [Fact] public void LocalFunctions_TypeParameter_Insert1() { var src1 = @"void L() {}"; var src2 = @"void L<A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@8", "Insert [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Insert2() { var src1 = @"void L<A>() {}"; var src2 = @"void L<A,B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@8 -> [<A,B>]@8", "Insert [B]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete1() { var src1 = @"void L<A>() {}"; var src2 = @"void L() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Delete2() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@8 -> [<B>]@8", "Delete [A]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Update() { var src1 = @"void L<A>() {}"; var src2 = @"void L<B>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [A]@9 -> [B]@9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("Enum", "Delegate")] [InlineData("IDisposable", "IDisposable, new()")] public void LocalFunctions_TypeParameter_Constraint_Clause_Update(string oldConstraint, string newConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() where A : " + newConstraint + " {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [where A : " + oldConstraint + "]@14 -> [where A : " + newConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void LocalFunctions_TypeParameter_Constraint_Clause_Delete(string oldConstraint) { var src1 = "void L<A>() where A : " + oldConstraint + " {}"; var src2 = "void L<A>() {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Delete [where A : " + oldConstraint + "]@14"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Constraint_Clause_Add() { var src1 = "void L<A,B>() where A : new() {}"; var src2 = "void L<A,B>() where A : new() where B : System.IDisposable {}"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Insert [where B : System.IDisposable]@32"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_Reorder() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,A>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } [Fact] public void LocalFunctions_TypeParameter_ReorderAndUpdate() { var src1 = @"void L<A,B>() {}"; var src2 = @"void L<B,C>() {} "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@11 -> @9", "Update [A]@9 -> [C]@11"); GetTopEdits(edits).VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingTypeParameters, "L", FeaturesResources.local_function)); } #endregion #region Queries [Fact] public void Queries_Update_Signature_Select1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1.0} select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_Select2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} select a.ToString(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Update_Signature_From1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "from", CSharpFeaturesResources.from_clause)); } [Fact] public void Queries_Update_Signature_From2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from System.Int64 a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from long a in new[] {1} from b in new[] {2} select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_From3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} from b in new[] {2} select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new List<int>() from b in new List<int>() select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_Let1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} let b = 1.0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "let", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_Update_Signature_OrderBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1.0 descending, a + 2 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 1.0 descending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_OrderBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2 ascending select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} orderby a + 1 descending, a + 2.0 ascending select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "a + 2.0 ascending", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Update_Signature_Join1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1.0} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join byte b in new[] {1} on a equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join3() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1 equals b select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a + 1.0 equals b select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_Join4() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1 select b; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} join b in new[] {1} on a equals b + 1.0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "join", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_Update_Signature_GroupBy1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1 by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} group a by a + 1.0 into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_Update_Signature_GroupBy_MatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown G1(int a) => null; Unknown G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Update_Signature_GroupBy_NonMatchingErrorTypes() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G1(a) by a into z select z; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { Unknown1 G1(int a) => null; Unknown2 G2(int a) => null; void F() { var result = from a in new[] {1} group G2(a) by a into z select z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_FromSelect_Update1() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in c from x in z select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from a in b]@4 -> [from a in c]@4", "Update [from x in y]@16 -> [from x in z]@16", "Update [select c]@28 -> [select c + 1]@28"); } [Fact] public void Queries_FromSelect_Update2() { var src1 = "F(from a in b from x in y select c);"; var src2 = "F(from a in b from x in z select c);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [from x in y]@16 -> [from x in z]@16"); } [Fact] public void Queries_FromSelect_Update3() { var src1 = "F(from a in await b from x in y select c);"; var src2 = "F(from a in await c from x in y select c);"; var edits = GetMethodEdits(src1, src2, MethodKind.Async); edits.VerifyEdits( "Update [await b]@34 -> [await c]@34"); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a + 1; } } "; var src2 = @" using System; using System.Linq; using System.Collections.Generic; class C { void F() { var result = from a in new[] {1} where a > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_FromSelect_Delete() { var src1 = "F(from a in b from c in d select a + c);"; var src2 = "F(from a in b select c + 1);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select a + c]@28 -> [select c + 1]@16", "Delete [from c in d]@16"); } [Fact] public void Queries_JoinInto_Update() { var src1 = "F(from a in b join b in c on a equals b into g1 select g1);"; var src2 = "F(from a in b join b in c on a equals b into g2 select g2);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [select g1]@50 -> [select g2]@50", "Update [into g1]@42 -> [into g2]@42"); } [Fact] public void Queries_JoinIn_Update() { var src1 = "F(from a in b join b in await A(1) on a equals b select g);"; var src2 = "F(from a in b join b in await A(2) on a equals b select g);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [await A(1)]@26 -> [await A(2)]@26"); } [Fact] public void Queries_GroupBy_Update() { var src1 = "F(from a in b group a by a.x into g select g);"; var src2 = "F(from a in b group z by z.y into h select h);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [group a by a.x]@17 -> [group z by z.y]@17", "Update [into g select g]@32 -> [into h select h]@32", "Update [select g]@40 -> [select h]@40"); } [Fact] public void Queries_OrderBy_Reorder() { var src1 = "F(from a in b orderby a.x, a.b descending, a.c ascending select a.d);"; var src2 = "F(from a in b orderby a.x, a.c ascending, a.b descending select a.d);"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [a.c ascending]@46 -> @30"); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_GroupBy_Reduced3() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1.0 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingQueryLambdaType, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced4() { var src1 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a + 1 by a; } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] {1} group a by a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_OrderBy_Continuation_Update() { var src1 = "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);"; var src2 = "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);"; var edits = GetMethodEdits(src1, src2); var actual = ToMatchingPairs(edits.Match); var expected = new MatchingPairs { { "F(from a in b orderby a.x, a.b descending select a.d into z orderby a.c ascending select z);", "F(from a in b orderby a.x, a.c ascending select a.d into z orderby a.b descending select z);" }, { "from a in b", "from a in b" }, { "orderby a.x, a.b descending select a.d into z orderby a.c ascending select z", "orderby a.x, a.c ascending select a.d into z orderby a.b descending select z" }, { "orderby a.x, a.b descending", "orderby a.x, a.c ascending" }, { "a.x", "a.x" }, { "a.b descending", "a.c ascending" }, { "select a.d", "select a.d" }, { "into z orderby a.c ascending select z", "into z orderby a.b descending select z" }, { "orderby a.c ascending select z", "orderby a.b descending select z" }, { "orderby a.c ascending", "orderby a.b descending" }, { "a.c ascending", "a.b descending" }, { "select z", "select z" } }; expected.AssertEqual(actual); edits.VerifyEdits( "Update [a.b descending]@30 -> [a.c ascending]@30", "Update [a.c ascending]@74 -> [a.b descending]@73"); } [Fact] public void Queries_CapturedTransparentIdentifiers_FromClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 0 where Z(() => b) > 0 where Z(() => a) > 0 where Z(() => b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a) > 1 // update where Z(() => b) > 2 // update where Z(() => a) > 3 // update where Z(() => b) > 4 // update select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_LetClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a) select a + b; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } let b = Z(() => a + 1) select a - b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CapturedTransparentIdentifiers_JoinClause1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.First()); } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } join b in new[] { 3 } on Z(() => a + 1) equals Z(() => b - 1) into g select Z(() => g.Last()); } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_CeaseCapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); // TODO: better location (the variable, not the from clause) edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "from b in new[] { 2 }", "b")); } [Fact] public void Queries_CapturingTransparentIdentifiers1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + 1) > 0 select a; } }"; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) { return 1; } void F() { var result = from a in new[] { 1 } from b in new[] { 2 } where Z(() => a + b) > 0 select a; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "b", "b")); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select 1; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_AccessingCapturedTransparentIdentifier3() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier1() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select a + b; } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } from b in new[] { 1 } where Z(() => a) > 0 select b; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.NotAccessingCapturedVariableInLambda, "select", "a", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_NotAccessingCapturedTransparentIdentifier2() { var src1 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => 1); } } "; var src2 = @" using System; using System.Linq; class C { int Z(Func<int> f) => 1; void F() { var result = from a in new[] { 1 } where Z(() => a) > 0 select Z(() => a); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.select_clause), Diagnostic(RudeEditKind.AccessingCapturedVariableInLambda, "a", "a", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_Insert1() { var src1 = @" using System; using System.Linq; class C { void F() { } } "; var src2 = @" using System; using System.Linq; class C { void F() { var result = from a in new[] { 1 } select a; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Yield [Fact] public void Yield_Update1() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield break; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 3; yield break; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield break;", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.yield_break_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 4;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Delete1() { var src1 = @" yield return 1; yield return 2; yield return 3; "; var src2 = @" yield return 1; yield return 3; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Delete [yield return 2;]@42"); } [Fact] public void Yield_Delete2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void Yield_Insert1() { var src1 = @" yield return 1; yield return 3; "; var src2 = @" yield return 1; yield return 2; yield return 3; yield return 4; "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Iterator); bodyEdits.VerifyEdits( "Insert [yield return 2;]@42", "Insert [yield return 4;]@76"); } [Fact] public void Yield_Insert2() { var src1 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 3; } } "; var src2 = @" class C { static IEnumerable<int> F() { yield return 1; yield return 2; yield return 3; yield return 4; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "yield return 4;", CSharpFeaturesResources.yield_return_statement), Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingIteratorStateMachineAttribute() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 1; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }, Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static IEnumerable<int> F()", "System.Runtime.CompilerServices.IteratorStateMachineAttribute")); } [Fact] public void MissingIteratorStateMachineAttribute2() { var src1 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { return null; } } "; var src2 = @" using System.Collections.Generic; class C { static IEnumerable<int> F() { yield return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.Mscorlib40AndSystemCore }); } #endregion #region Await /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_OK() { var src1 = @" class C { static async Task<int> F() { await F(1); if (await F(1)) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(1); } if (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(1); } while (await F(1)); for (var x = await F(1); await G(1); await H(1)) { Console.WriteLine(1); } foreach (var x in await F(1)) { Console.WriteLine(1); } using (var x = await F(1)) { Console.WriteLine(1); } lock (await F(1)) { Console.WriteLine(1); } lock (a = await F(1)) { Console.WriteLine(1); } var a = await F(1), b = await G(1); a = await F(1); switch (await F(2)) { case 1: return b = await F(1); } return await F(1); } static async Task<int> G() => await F(1); } "; var src2 = @" class C { static async Task<int> F() { await F(2); if (await F(1)) { Console.WriteLine(2); } if (await F(2)) { Console.WriteLine(1); } if (F(1, await F(1))) { Console.WriteLine(2); } while (await F(1)) { Console.WriteLine(1); } do { Console.WriteLine(2); } while (await F(2)); for (var x = await F(2); await G(2); await H(2)) { Console.WriteLine(2); } foreach (var x in await F(2)) { Console.WriteLine(2); } using (var x = await F(2)) { Console.WriteLine(1); } lock (await F(2)) { Console.WriteLine(2); } lock (a = await F(2)) { Console.WriteLine(2); } var a = await F(2), b = await G(2); b = await F(2); switch (await F(2)) { case 1: return b = await F(2); } return await F(2); } static async Task<int> G() => await F(2); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } /// <summary> /// Tests spilling detection logic of <see cref="CSharpEditAndContinueAnalyzer.ReportStateMachineSuspensionPointRudeEdits"/>. /// </summary> [Fact] public void AwaitSpilling_Errors() { var src1 = @" class C { static async Task<int> F() { F(1, await F(1)); F(1, await F(1)); F(await F(1)); await F(await F(1)); if (F(1, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(1)), b = F(1, await G(1)); b = F(1, await F(1)); b += await F(1); } } "; var src2 = @" class C { static async Task<int> F() { F(2, await F(1)); F(1, await F(2)); F(await F(2)); await F(await F(2)); if (F(2, await F(1))) { Console.WriteLine(1); } var a = F(1, await F(2)), b = F(1, await G(2)); b = F(1, await F(2)); b += await F(2); } } "; var edits = GetTopEdits(src1, src2); // consider: these edits can be allowed if we get more sophisticated edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "await F(await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "F(2, await F(1))"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "var a = F(1, await F(2)), b = F(1, await G(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b = F(1, await F(2));"), Diagnostic(RudeEditKind.AwaitStatementUpdate, "b += await F(2);")); } [Fact] public void Await_Delete1() { var src1 = @" await F(1); await F(2); await F(3); "; var src2 = @" await F(1); await F(3); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Delete [await F(2);]@37", "Delete [await F(2)]@37"); } [Fact] public void Await_Delete2() { var src1 = @" class C { static async Task<int> F() { await F(1); { await F(2); } await F(3); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); { F(2); } await F(3); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "F(2);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete3() { var src1 = @" class C { static async Task<int> F() { await F(await F(1)); } } "; var src2 = @" class C { static async Task<int> F() { await F(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await F(1);", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete4() { var src1 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Delete5() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "static async Task<int> F()", CSharpFeaturesResources.await_expression)); } [Fact] public void AwaitForEach_Delete1() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var x in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete2() { var src1 = @" class C { static async Task<int> F() { await foreach (var (x, y) in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { foreach (var (x, y) in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "foreach (var (x, y) in G())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void AwaitForEach_Delete3() { var src1 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void AwaitUsing_Delete1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete2() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "await using", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete3() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.Delete, "{", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Delete4() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var src2 = @" class C { static async Task<int> F() { using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(ActiveStatementsDescription.Empty, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration), Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "using", CSharpFeaturesResources.using_declaration)); } [Fact] public void Await_Insert1() { var src1 = @" await F(1); await F(3); "; var src2 = @" await F(1); await F(2); await F(3); await F(4); "; var bodyEdits = GetMethodEdits(src1, src2, kind: MethodKind.Async); bodyEdits.VerifyEdits( "Insert [await F(2);]@37", "Insert [await F(4);]@63", "Insert [await F(2)]@37", "Insert [await F(4)]@63"); } [Fact] public void Await_Insert2() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(1); await F(2); await F(3); await F(4); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert3() { var src1 = @" class C { static async IEnumerable<int> F() { await F(1); await F(3); } } "; var src2 = @" class C { static async IEnumerable<int> F() { await F(await F(1)); await F(await F(2)); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert4() { var src1 = @" class C { static async Task<int> F() => await F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(await F(1)); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void Await_Insert5() { var src1 = @" class C { static Task<int> F() => F(1); } "; var src2 = @" class C { static async Task<int> F() => await F(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert_Ok() { var src1 = @" class C { static async Task<int> F() { foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); // ok to add awaits if there were none before and no active statements edits.VerifyRudeDiagnostics(); } [Fact] public void AwaitForEach_Insert() { var src1 = @" class C { static async Task<int> F() { await Task.FromResult(1); foreach (var x in G()) { } } } "; var src2 = @" class C { static async Task<int> F() { await Task.FromResult(1); await foreach (var x in G()) { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void AwaitUsing_Insert1() { var src1 = @" class C { static async Task<int> F() { await using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await using D x = new D(), y = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "y = new D()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void AwaitUsing_Insert2() { var src1 = @" class C { static async Task<int> F() { await G(); using D x = new D(); } } "; var src2 = @" class C { static async Task<int> F() { await G(); await using D x = new D(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", "await")); } [Fact] public void Await_Update() { var src1 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var x in G()) { } await Task.FromResult(1); await Task.FromResult(1); await Task.FromResult(1); yield return 1; yield break; yield break; } } "; var src2 = @" class C { static async IAsyncEnumerable<int> F() { await foreach (var (x,y) in G()) { } await foreach (var x in G()) { } await using D x = new D(), y = new D(); await Task.FromResult(1); await Task.FromResult(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingStateMachineShape, "await foreach (var x in G()) { }", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_foreach_statement), Diagnostic(RudeEditKind.ChangingStateMachineShape, "x = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "y = new D()", CSharpFeaturesResources.await_expression, CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_return_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "await Task.FromResult(1)", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.await_expression), Diagnostic(RudeEditKind.ChangingStateMachineShape, "yield return 1;", CSharpFeaturesResources.yield_break_statement, CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MissingAsyncStateMachineAttribute1() { var src1 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 1; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }, expectedDiagnostics: new[] { Diagnostic(RudeEditKind.UpdatingStateMachineMethodMissingAttribute, "static async Task<int> F()", "System.Runtime.CompilerServices.AsyncStateMachineAttribute") }); } [Fact] public void MissingAsyncStateMachineAttribute2() { var src1 = @" using System.Threading.Tasks; class C { static Task<int> F() { return null; } } "; var src2 = @" using System.Threading.Tasks; class C { static async Task<int> F() { await new Task(); return 2; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( targetFrameworks: new[] { TargetFramework.MinimalAsync }); } [Fact] public void SemanticError_AwaitInPropertyAccessor() { var src1 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(1); return 1; } } } "; var src2 = @" using System.Threading.Tasks; class C { public Task<int> P { get { await Task.Delay(2); return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } #endregion #region Out Var [Fact] public void OutVarType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int y);]@4"); } [Fact] public void OutVarNameAndType_Update() { var src1 = @" M(out var y); "; var src2 = @" M(out int z); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out var y);]@4 -> [M(out int z);]@4", "Update [y]@14 -> [z]@14"); } [Fact] public void OutVar_Insert() { var src1 = @" M(); "; var src2 = @" M(out int y); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M();]@4 -> [M(out int y);]@4", "Insert [y]@14"); } [Fact] public void OutVar_Delete() { var src1 = @" M(out int y); "; var src2 = @" M(); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [M(out int y);]@4 -> [M();]@4", "Delete [y]@14"); } #endregion #region Pattern [Fact] public void ConstantPattern_Update() { var src1 = @" if ((o is null) && (y == 7)) return 3; if (a is 7) return 5; "; var src2 = @" if ((o1 is null) && (y == 7)) return 3; if (a is 77) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((o is null) && (y == 7)) return 3;]@4 -> [if ((o1 is null) && (y == 7)) return 3;]@4", "Update [if (a is 7) return 5;]@44 -> [if (a is 77) return 5;]@45"); } [Fact] public void DeclarationPattern_Update() { var src1 = @" if (!(o is int i) && (y == 7)) return; if (!(a is string s)) return; if (!(b is string t)) return; if (!(c is int j)) return; "; var src2 = @" if (!(o1 is int i) && (y == 7)) return; if (!(a is int s)) return; if (!(b is string t1)) return; if (!(c is int)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (!(o is int i) && (y == 7)) return;]@4 -> [if (!(o1 is int i) && (y == 7)) return;]@4", "Update [if (!(a is string s)) return;]@44 -> [if (!(a is int s)) return;]@45", "Update [if (!(c is int j)) return;]@106 -> [if (!(c is int)) return;]@105", "Update [t]@93 -> [t1]@91", "Delete [j]@121"); } [Fact] public void DeclarationPattern_Reorder() { var src1 = @"if ((a is int i) && (b is int j)) { A(); }"; var src2 = @"if ((b is int j) && (a is int i)) { A(); }"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if ((a is int i) && (b is int j)) { A(); }]@2 -> [if ((b is int j) && (a is int i)) { A(); }]@2", "Reorder [j]@32 -> @16"); } [Fact] public void VarPattern_Update() { var src1 = @" if (o is (var x, var y)) return; if (o4 is (string a, var (b, c))) return; if (o2 is var (e, f, g)) return; if (o3 is var (k, l, m)) return; "; var src2 = @" if (o is (int x, int y1)) return; if (o1 is (var a, (var b, string c1))) return; if (o7 is var (g, e, f)) return; if (o3 is (string k, int l2, int m)) return; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (o is (var x, var y)) return;]@4 -> [if (o is (int x, int y1)) return;]@4", "Update [if (o4 is (string a, var (b, c))) return;]@38 -> [if (o1 is (var a, (var b, string c1))) return;]@39", "Update [if (o2 is var (e, f, g)) return;]@81 -> [if (o7 is var (g, e, f)) return;]@87", "Reorder [g]@102 -> @102", "Update [if (o3 is var (k, l, m)) return;]@115 -> [if (o3 is (string k, int l2, int m)) return;]@121", "Update [y]@25 -> [y1]@25", "Update [c]@67 -> [c1]@72", "Update [l]@133 -> [l2]@146"); } [Fact] public void PositionalPattern_Update1() { var src1 = @"var r = (x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (0, var b, int c) when c > 1 => 2, _ => 4 }]@10 -> [((x, y, z)) switch { (_, int b1, double c1) when c1 > 2 => c1, _ => 4 }]@10", "Update [(0, var b, int c) when c > 1 => 2]@29 -> [(_, int b1, double c1) when c1 > 2 => c1]@31", "Reorder [c]@44 -> @39", "Update [c]@44 -> [b1]@39", "Update [b]@37 -> [c1]@50", "Update [when c > 1]@47 -> [when c1 > 2]@54"); } [Fact] public void PositionalPattern_Update2() { var src1 = @"var r = (x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 };"; var src2 = @"var r = ((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [(x, y, z) switch { (var a, 3, 4) => a, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (var a1, 3, 4) => a1 * 2, (1, 1, Point { Y: 0 } p1) => 3, _ => 4 }]@10", "Update [(var a, 3, 4) => a]@29 -> [(var a1, 3, 4) => a1 * 2]@31", "Update [(1, 1, Point { X: 0 } p) => 3]@49 -> [(1, 1, Point { Y: 0 } p1) => 3]@57", "Update [a]@34 -> [a1]@36", "Update [p]@71 -> [p1]@79"); } [Fact] public void PositionalPattern_Reorder() { var src1 = @"var r = (x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }; "; var src2 = @"var r = ((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( @"Update [(x, y, z) switch { (1, 2, 3) => 0, (var a, 3, 4) => a, (0, var b, int c) when c > 1 => 2, (1, 1, Point { X: 0 } p) => 3, _ => 4 }]@10 -> [((x, y, z)) switch { (1, 1, Point { X: 0 } p) => 3, (0, var b, int c) when c > 1 => 2, (var a, 3, 4) => a, (1, 2, 3) => 0, _ => 4 }]@10", "Reorder [(var a, 3, 4) => a]@47 -> @100", "Reorder [(0, var b, int c) when c > 1 => 2]@68 -> @64", "Reorder [(1, 1, Point { X: 0 } p) => 3]@104 -> @32"); } [Fact] public void PropertyPattern_Update() { var src1 = @" if (address is { State: ""WA"" }) return 1; if (obj is { Color: Color.Purple }) return 2; if (o is string { Length: 5 } s) return 3; "; var src2 = @" if (address is { ZipCode: 98052 }) return 4; if (obj is { Size: Size.M }) return 2; if (o is string { Length: 7 } s7) return 5; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [if (address is { State: \"WA\" }) return 1;]@4 -> [if (address is { ZipCode: 98052 }) return 4;]@4", "Update [if (obj is { Color: Color.Purple }) return 2;]@47 -> [if (obj is { Size: Size.M }) return 2;]@50", "Update [if (o is string { Length: 5 } s) return 3;]@94 -> [if (o is string { Length: 7 } s7) return 5;]@90", "Update [return 1;]@36 -> [return 4;]@39", "Update [s]@124 -> [s7]@120", "Update [return 3;]@127 -> [return 5;]@124"); } [Fact] public void RecursivePatterns_Reorder() { var src1 = @"var r = obj switch { string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, int i => i * i, _ => -1 }; "; var src2 = @"var r = obj switch { int i => i * i, string s when s.Length > 0 => (s, obj1) switch { (""a"", int i) => i, _ => 0 }, _ => -1 }; "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [int i => i * i]@140 -> @29", "Move [i]@102 -> @33", "Move [i]@144 -> @123"); } [Fact] public void CasePattern_UpdateInsert() { var src1 = @" switch(shape) { case Circle c: return 1; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: return 1; case Point p: return 0; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: return 1;]@26 -> [case Circle c1: return 1;]@26", "Insert [case Point p: return 0;]@57", "Insert [case Point p:]@57", "Insert [return 0;]@71", "Update [c]@38 -> [c1]@38", "Insert [p]@68"); } [Fact] public void CasePattern_UpdateDelete() { var src1 = @" switch(shape) { case Point p: return 0; case Circle c: A(c); break; default: return 4; } "; var src2 = @" switch(shape) { case Circle c1: A(c1); break; default: return 4; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c: A(c); break;]@55 -> [case Circle c1: A(c1); break;]@26", "Update [A(c);]@70 -> [A(c1);]@42", "Update [c]@67 -> [c1]@38", "Delete [case Point p: return 0;]@26", "Delete [case Point p:]@26", "Delete [p]@37", "Delete [return 0;]@40"); } [Fact] public void WhenCondition_Update() { var src1 = @" switch(shape) { case Circle c when (c < 10): return 1; case Circle c when (c > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c < 5): return 1; case Circle c2 when (c2 > 100): return 2; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [case Circle c when (c < 10): return 1;]@26 -> [case Circle c when (c < 5): return 1;]@26", "Update [case Circle c when (c > 100): return 2;]@70 -> [case Circle c2 when (c2 > 100): return 2;]@69", "Update [when (c < 10)]@40 -> [when (c < 5)]@40", "Update [c]@82 -> [c2]@81", "Update [when (c > 100)]@84 -> [when (c2 > 100)]@84"); } [Fact] public void CasePatternWithWhenCondition_UpdateReorder() { var src1 = @" switch(shape) { case Rectangle r: return 0; case Circle c when (c.Radius < 10): return 1; case Circle c when (c.Radius > 100): return 2; } "; var src2 = @" switch(shape) { case Circle c when (c.Radius > 99): return 2; case Circle c when (c.Radius < 10): return 1; case Rectangle r: return 0; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [case Circle c when (c.Radius < 10): return 1;]@59 -> @77", "Reorder [case Circle c when (c.Radius > 100): return 2;]@110 -> @26", "Update [case Circle c when (c.Radius > 100): return 2;]@110 -> [case Circle c when (c.Radius > 99): return 2;]@26", "Move [c]@71 -> @38", "Update [when (c.Radius > 100)]@124 -> [when (c.Radius > 99)]@40", "Move [c]@122 -> @89"); } #endregion #region Ref [Fact] public void Ref_Update() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Insert() { var src1 = @" int a = G(new int[] { 1, 2 }); int G(int[] p) { return p[1]; } "; var src2 = @" ref int32 a = ref G1(new int[] { 1, 2 }); ref int G1(int[] p) { return ref p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [int G(int[] p) { return p[1]; }]@36 -> [ref int G1(int[] p) { return ref p[2]; }]@47", "Update [int a = G(new int[] { 1, 2 })]@4 -> [ref int32 a = ref G1(new int[] { 1, 2 })]@4", "Update [a = G(new int[] { 1, 2 })]@8 -> [a = ref G1(new int[] { 1, 2 })]@14"); } [Fact] public void Ref_Delete() { var src1 = @" ref int a = ref G(new int[] { 1, 2 }); ref int G(int[] p) { return ref p[1]; } "; var src2 = @" int32 a = G1(new int[] { 1, 2 }); int G1(int[] p) { return p[2]; } "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Update [ref int G(int[] p) { return ref p[1]; }]@44 -> [int G1(int[] p) { return p[2]; }]@39", "Update [ref int a = ref G(new int[] { 1, 2 })]@4 -> [int32 a = G1(new int[] { 1, 2 })]@4", "Update [a = ref G(new int[] { 1, 2 })]@12 -> [a = G1(new int[] { 1, 2 })]@10"); } #endregion #region Tuples [Fact] public void TupleType_LocalVariables() { var src1 = @" (int a, string c) x = (a, string2); (int a, int b) y = (3, 4); (int a, int b, int c) z = (5, 6, 7); "; var src2 = @" (int a, int b) x = (a, string2); (int a, int b, string c) z1 = (5, 6, 7); (int a, int b) y2 = (3, 4); "; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits( "Reorder [(int a, int b, int c) z = (5, 6, 7);]@69 -> @39", "Update [(int a, string c) x = (a, string2)]@4 -> [(int a, int b) x = (a, string2)]@4", "Update [(int a, int b, int c) z = (5, 6, 7)]@69 -> [(int a, int b, string c) z1 = (5, 6, 7)]@39", "Update [z = (5, 6, 7)]@91 -> [z1 = (5, 6, 7)]@64", "Update [y = (3, 4)]@56 -> [y2 = (3, 4)]@96"); } [Fact] public void TupleElementName() { var src1 = @"class C { (int a, int b) F(); }"; var src2 = @"class C { (int x, int b) F(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b) F();]@10 -> [(int x, int b) F();]@10"); } [Fact] public void TupleInField() { var src1 = @"class C { private (int, int) _x = (1, 2); }"; var src2 = @"class C { private (int, string) _y = (1, 2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) _x = (1, 2)]@18 -> [(int, string) _y = (1, 2)]@18", "Update [_x = (1, 2)]@29 -> [_y = (1, 2)]@32"); } [Fact] public void TupleInProperty() { var src1 = @"class C { public (int, int) Property1 { get { return (1, 2); } } }"; var src2 = @"class C { public (int, string) Property2 { get { return (1, string.Empty); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public (int, int) Property1 { get { return (1, 2); } }]@10 -> [public (int, string) Property2 { get { return (1, string.Empty); } }]@10", "Update [get { return (1, 2); }]@40 -> [get { return (1, string.Empty); }]@43"); } [Fact] public void TupleInDelegate() { var src1 = @"public delegate void EventHandler1((int, int) x);"; var src2 = @"public delegate void EventHandler2((int, int) y);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void EventHandler1((int, int) x);]@0 -> [public delegate void EventHandler2((int, int) y);]@0", "Update [(int, int) x]@35 -> [(int, int) y]@35"); } #endregion #region With Expressions [Fact] public void WithExpression_PropertyAdd() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyDelete() { var src1 = @"var x = y with { X = 1, Y = 2 };"; var src2 = @"var x = y with { X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 2 }]@6 -> [x = y with { X = 1 }]@6"); } [Fact] public void WithExpression_PropertyChange() { var src1 = @"var x = y with { X = 1 };"; var src2 = @"var x = y with { Y = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1 }]@6 -> [x = y with { Y = 1 }]@6"); } [Fact] public void WithExpression_PropertyValueChange() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { X = 1, Y = 2 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { X = 1, Y = 2 }]@6"); } [Fact] public void WithExpression_PropertyValueReorder() { var src1 = @"var x = y with { X = 1, Y = 1 };"; var src2 = @"var x = y with { Y = 1, X = 1 };"; var edits = GetMethodEdits(src1, src2); edits.VerifyEdits(@"Update [x = y with { X = 1, Y = 1 }]@6 -> [x = y with { Y = 1, X = 1 }]@6"); } #endregion #region Top Level Statements [Fact] public void TopLevelStatement_CaptureArgs() { var src1 = @" using System; var x = new Func<string>(() => ""Hello""); Console.WriteLine(x()); "; var src2 = @" using System; var x = new Func<string>(() => ""Hello"" + args[0]); Console.WriteLine(x()); "; var edits = GetTopEdits(src1, src2); // TODO: allow creating a new leaf closure: https://github.com/dotnet/roslyn/issues/54672 edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.CapturingVariable, "using System;\r\n\r\nvar x = new Func<string>(() => \"Hello\" + args[0]);\r\n\r\nConsole.WriteLine(x());\r\n", "args")); } [Fact, WorkItem(21499, "https://github.com/dotnet/roslyn/issues/21499")] public void TopLevelStatement_InsertMultiScopeCapture() { var src1 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; } "; var src2 = @" using System; foreach (int x0 in new[] { 1 }) // Group #0 { // Group #1 int x1 = 0; int f0(int a) => x0; int f1(int a) => x1; int f2(int a) => x0 + x1; // error: connecting previously disconnected closures } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertLambdaWithMultiScopeCapture, "x1", CSharpFeaturesResources.local_function, "x0", "x1")); } #endregion } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/EditorFeatures/CSharpTest2/Recommendations/ElseKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ElseKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAtRoot_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalStatement_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalVariableDeclaration_Interactive() { await VerifyAbsenceAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInPreprocessor1() { await VerifyAbsenceAsync( @"class C { #if $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInPreprocessorFollowedBySkippedTokens() { await VerifyKeywordAsync( @"#if GOO #$$ dasd "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHash() { await VerifyKeywordAsync( @"#$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterHashAndSpace() { await VerifyKeywordAsync( @"# $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterIf() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$ else")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [WorkItem(25336, "https://github.com/dotnet/roslyn/issues/25336")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfStatementElse(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} else $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfElseNestedIfStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterIfElseNestedIfElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) Console.WriteLine(); else if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterWhileIfWhileNestedIfElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else {statement} $$ else")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestNotAfterWhileIfWhileNestedIfElseElseStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"while (true) if (true) while (true) if (true) Console.WriteLine(); else Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console")] [InlineData("Console.")] [InlineData("Console.WriteLine(")] [InlineData("Console.WriteLine()")] [InlineData("{")] [InlineData("{ Console.WriteLine();")] [InlineData("while")] [InlineData("while (true)")] [InlineData("while (true) {")] [InlineData("while (true) { { }")] [InlineData("for (int i = 0;")] public async Task TestNotAfterIfNestedIfElseIncompleteStatement(string statement) { await VerifyAbsenceAsync(AddInsideMethod( $@"if (true) if (true) Console.WriteLine(); else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$")); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [InlineData("Console.WriteLine();")] [InlineData("{ }")] [InlineData("while (true) { }")] public async Task TestAfterIfNestedIfIncompleteStatementElseStatement_BeforeElse(string statement) { await VerifyKeywordAsync(AddInsideMethod( $@"if (true) if (true) Console // Incomplete, but that's fine. This is not the if statement we care about. else {statement} $$ else")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine()$$; // Complete statement, but we're not at the end of it. ")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSkippedToken() { await VerifyAbsenceAsync(AddInsideMethod( @"if (true) Console.WriteLine();, $$")); } } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Scripting/Core/Hosting/AssemblyLoader/AssemblyLoaderImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal abstract class AssemblyLoaderImpl : IDisposable { internal readonly InteractiveAssemblyLoader Loader; protected AssemblyLoaderImpl(InteractiveAssemblyLoader loader) { Loader = loader; } public static AssemblyLoaderImpl Create(InteractiveAssemblyLoader loader) { if (CoreClrShim.AssemblyLoadContext.Type != null) { return CreateCoreImpl(loader); } else { return new DesktopAssemblyLoaderImpl(loader); } } // NoInlining to avoid loading AssemblyLoadContext if not available. [MethodImpl(MethodImplOptions.NoInlining)] private static AssemblyLoaderImpl CreateCoreImpl(InteractiveAssemblyLoader loader) { return new CoreAssemblyLoaderImpl(loader); } public abstract Assembly LoadFromStream(Stream peStream, Stream pdbStream); public abstract AssemblyAndLocation LoadFromPath(string path); public abstract void Dispose(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal abstract class AssemblyLoaderImpl : IDisposable { internal readonly InteractiveAssemblyLoader Loader; protected AssemblyLoaderImpl(InteractiveAssemblyLoader loader) { Loader = loader; } public static AssemblyLoaderImpl Create(InteractiveAssemblyLoader loader) { if (CoreClrShim.AssemblyLoadContext.Type != null) { return CreateCoreImpl(loader); } else { return new DesktopAssemblyLoaderImpl(loader); } } // NoInlining to avoid loading AssemblyLoadContext if not available. [MethodImpl(MethodImplOptions.NoInlining)] private static AssemblyLoaderImpl CreateCoreImpl(InteractiveAssemblyLoader loader) { return new CoreAssemblyLoaderImpl(loader); } public abstract Assembly LoadFromStream(Stream peStream, Stream pdbStream); public abstract AssemblyAndLocation LoadFromPath(string path); public abstract void Dispose(); } }
-1
dotnet/roslyn
56,173
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.
Closes #53800. Related to #56171.
AlekseyTs
"2021-09-03T17:22:56Z"
"2021-09-07T18:21:02Z"
ec20540d1ac3d0b048ddfb3b7831728511f3e3bb
5851730e82f7805df3559444fd0f605243bd1adf
Provide real implementation for RuntimeSupportsStaticAbstractMembersInInterfaces property.. Closes #53800. Related to #56171.
./src/Tools/ExternalAccess/FSharp/Internal/Diagnostics/FSharpUnusedDeclarationsAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics { [Shared] [ExportLanguageService(typeof(FSharpUnusedDeclarationsDiagnosticAnalyzerService), LanguageNames.FSharp)] internal class FSharpUnusedDeclarationsDiagnosticAnalyzerService : ILanguageService { private readonly IFSharpUnusedDeclarationsDiagnosticAnalyzer _analyzer; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpUnusedDeclarationsDiagnosticAnalyzerService(IFSharpUnusedDeclarationsDiagnosticAnalyzer analyzer) { _analyzer = analyzer; } public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken) { return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken); } } [DiagnosticAnalyzer(LanguageNames.FSharp)] internal class FSharpUnusedDeclarationsDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private const string DescriptorId = "FS1182"; private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor( DescriptorId, ExternalAccessFSharpResources.TheValueIsUnused, ExternalAccessFSharpResources.TheValueIsUnused, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor); public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public override int Priority => 80; // Default = 50 public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var analyzer = document.Project.LanguageServices.GetService<FSharpUnusedDeclarationsDiagnosticAnalyzerService>(); if (analyzer == null) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken); } public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } public bool OpenFileOnly(OptionSet options) { return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Diagnostics; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Diagnostics { [Shared] [ExportLanguageService(typeof(FSharpUnusedDeclarationsDiagnosticAnalyzerService), LanguageNames.FSharp)] internal class FSharpUnusedDeclarationsDiagnosticAnalyzerService : ILanguageService { private readonly IFSharpUnusedDeclarationsDiagnosticAnalyzer _analyzer; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpUnusedDeclarationsDiagnosticAnalyzerService(IFSharpUnusedDeclarationsDiagnosticAnalyzer analyzer) { _analyzer = analyzer; } public Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(DiagnosticDescriptor descriptor, Document document, CancellationToken cancellationToken) { return _analyzer.AnalyzeSemanticsAsync(descriptor, document, cancellationToken); } } [DiagnosticAnalyzer(LanguageNames.FSharp)] internal class FSharpUnusedDeclarationsDiagnosticAnalyzer : DocumentDiagnosticAnalyzer, IBuiltInAnalyzer { private const string DescriptorId = "FS1182"; private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor( DescriptorId, ExternalAccessFSharpResources.TheValueIsUnused, ExternalAccessFSharpResources.TheValueIsUnused, DiagnosticCategory.Style, DiagnosticSeverity.Hidden, isEnabledByDefault: true, customTags: FSharpDiagnosticCustomTags.Unnecessary); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_descriptor); public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public override int Priority => 80; // Default = 50 public override Task<ImmutableArray<Diagnostic>> AnalyzeSemanticsAsync(Document document, CancellationToken cancellationToken) { var analyzer = document.Project.LanguageServices.GetService<FSharpUnusedDeclarationsDiagnosticAnalyzerService>(); if (analyzer == null) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } return analyzer.AnalyzeSemanticsAsync(_descriptor, document, cancellationToken); } public override Task<ImmutableArray<Diagnostic>> AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { return Task.FromResult(ImmutableArray<Diagnostic>.Empty); } public DiagnosticAnalyzerCategory GetAnalyzerCategory() { return DiagnosticAnalyzerCategory.SemanticDocumentAnalysis; } public bool OpenFileOnly(OptionSet options) { return true; } } }
-1