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,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Test/Symbol/Compilation/SemanticModelGetSemanticInfoTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; // Note: the easiest way to create new unit tests that use GetSemanticInfo // is to use the SemanticInfo unit test generate in Editor Test App. namespace Microsoft.CodeAnalysis.CSharp.UnitTests { using Utils = CompilationUtils; public class SemanticModelGetSemanticInfoTests : SemanticModelTestBase { [Fact] public void FailedOverloadResolution() { string sourceCode = @" class Program { static void Main(string[] args) { int i = 8; int j = i + q; /*<bind>*/X.f/*</bind>*/(""hello""); } } class X { public static void f() { } public static void f(int i) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void X.f()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("void X.f(System.Int32 i)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void X.f()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void X.f(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SimpleGenericType() { string sourceCode = @" using System; class Program { /*<bind>*/K<int>/*</bind>*/ f; } class K<T> { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("K<System.Int32>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity1() { string sourceCode = @" using System; class Program { /*<bind>*/K<int, string>/*</bind>*/ f; } class K<T> { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity2() { string sourceCode = @" using System; class Program { /*<bind>*/K/*</bind>*/ f; } class K<T> { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity3() { string sourceCode = @" using System; class Program { static void Main() { /*<bind>*/K<int, int>/*</bind>*/.f(); } } class K<T> { void f() { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity4() { string sourceCode = @" using System; class Program { static K Main() { /*<bind>*/K/*</bind>*/.f(); } } class K<T> { void f() { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NotInvocable() { string sourceCode = @" using System; class Program { static void Main() { K./*<bind>*/f/*</bind>*/(); } } class K { public int f; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotInvocable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleField() { string sourceCode = @" class Program { static void Main() { K./*<bind>*/f/*</bind>*/ = 3; } } class K { private int f; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleFieldAssignment() { string sourceCode = @"class A { string F; } class B { static void M(A a) { /*<bind>*/a.F/*</bind>*/ = string.Empty; } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); var symbol = semanticInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("System.String A.F", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, symbol.Kind); } [WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")] [Fact] public void InaccessibleBaseClassConstructor01() { string sourceCode = @" namespace Test { public class Base { protected Base() { } } public class Derived : Base { void M() { Base b = /*<bind>*/new Base()/*</bind>*/; } } }"; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Test.Base..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); } [WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")] [Fact] public void InaccessibleBaseClassConstructor02() { string sourceCode = @" namespace Test { public class Base { protected Base() { } } public class Derived : Base { void M() { Base b = new /*<bind>*/Base/*</bind>*/(); } } }"; var semanticInfo = GetSemanticInfoForTest<NameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal("Test.Base", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MemberGroup.Length); } [Fact] public void InaccessibleFieldMethodArg() { string sourceCode = @"class A { string F; } class B { static void M(A a) { M(/*<bind>*/a.F/*</bind>*/); } static void M(string s) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); var symbol = semanticInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("System.String A.F", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, symbol.Kind); } [Fact] public void TypeNotAVariable() { string sourceCode = @" using System; class Program { static void Main() { /*<bind>*/K/*</bind>*/ = 12; } } class K { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleType1() { string sourceCode = @" using System; class Program { static void Main() { /*<bind>*/K.J/*</bind>*/ = v; } } class K { protected class J { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K.J", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguousTypesBetweenUsings1() { string sourceCode = @" using System; using N1; using N2; class Program { /*<bind>*/A/*</bind>*/ field; } namespace N1 { class A { } } namespace N2 { class A { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguousTypesBetweenUsings2() { string sourceCode = @" using System; using N1; using N2; class Program { void f() { /*<bind>*/A/*</bind>*/.g(); } } namespace N1 { class A { } } namespace N2 { class A { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguousTypesBetweenUsings3() { string sourceCode = @" using System; using N1; using N2; class Program { void f() { /*<bind>*/A<int>/*</bind>*/.g(); } } namespace N1 { class A<T> { } } namespace N2 { class A<U> { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.A<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("N1.A<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.A<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("N2.A<U>", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguityBetweenInterfaceMembers() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; interface I1 { public int P { get; } } interface I2 { public string P { get; } } interface I3 : I1, I2 { } public class Class1 { void f() { I3 x = null; int o = x./*<bind>*/P/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("I1.P", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 I1.P { get; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal("System.String I2.P { get; }", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Alias1() { string sourceCode = @" using O = System.Object; partial class A : /*<bind>*/O/*</bind>*/ {} "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Alias2() { string sourceCode = @" using O = System.Object; partial class A { void f() { /*<bind>*/O/*</bind>*/.ReferenceEquals(null, null); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(539002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539002")] [Fact] public void IncompleteGenericMethodCall() { string sourceCode = @" class Array { public static void Find<T>(T t) { } } class C { static void Main() { /*<bind>*/Array.Find<int>/*</bind>*/( } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void IncompleteExtensionMethodCall() { string sourceCode = @"interface I<T> { } class A { } class B : A { } class C { static void M(A a) { /*<bind>*/a.M/*</bind>*/( } } static class S { internal static void M(this object o, int x) { } internal static void M(this A a, int x, int y) { } internal static void M(this B b) { } internal static void M(this string s) { } internal static void M<T>(this T t, object o) { } internal static void M<T>(this T[] t) { } internal static void M<T, U>(this T x, I<T> y, U z) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup, "void object.M(int x)", "void A.M(int x, int y)", "void A.M<A>(object o)", "void A.M<A, U>(I<A> y, U z)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void object.M(int x)", "void A.M(int x, int y)", "void A.M<A>(object o)", "void A.M<A, U>(I<A> y, U z)"); Utils.CheckReducedExtensionMethod(semanticInfo.MethodGroup[3].GetSymbol(), "void A.M<A, U>(I<A> y, U z)", "void S.M<T, U>(T x, I<T> y, U z)", "void T.M<T, U>(I<T> y, U z)", "void S.M<T, U>(T x, I<T> y, U z)"); } [Fact] public void IncompleteExtensionMethodCallBadThisType() { string sourceCode = @"interface I<T> { } class B { static void M(I<A> a) { /*<bind>*/a.M/*</bind>*/( } } static class S { internal static void M(this object o) { } internal static void M<T>(this T t, object o) { } internal static void M<T>(this T[] t) { } internal static void M<T, U>(this I<T> x, I<T> y, U z) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Utils.CheckISymbols(semanticInfo.MethodGroup, "void object.M()", "void I<A>.M<I<A>>(object o)", "void I<A>.M<A, U>(I<A> y, U z)"); } [WorkItem(541141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541141")] [Fact] public void IncompleteGenericExtensionMethodCall() { string sourceCode = @"using System.Linq; class C { static void M(double[] a) { /*<bind>*/a.Where/*</bind>*/( } }"; var compilation = CreateCompilation(source: sourceCode); var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckISymbols(semanticInfo.MethodGroup, "IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, bool> predicate)", "IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, int, bool> predicate)"); } [WorkItem(541349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541349")] [Fact] public void GenericExtensionMethodCallExplicitTypeArgs() { string sourceCode = @"interface I<T> { } class C { static void M(object o) { /*<bind>*/o.E<int>/*</bind>*/(); } } static class S { internal static void E(this object x, object y) { } internal static void E<T>(this object o) { } internal static void E<T>(this object o, T t) { } internal static void E<T>(this I<T> t) { } internal static void E<T, U>(this I<T> t) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Utils.CheckSymbol(semanticInfo.Symbol, "void object.E<int>()"); Utils.CheckISymbols(semanticInfo.MethodGroup, "void object.E<int>()", "void object.E<int>(int t)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); } [Fact] public void GenericExtensionMethodCallExplicitTypeArgsOfT() { string sourceCode = @"interface I<T> { } class C { static void M<T, U>(T t, U u) { /*<bind>*/t.E<T, U>/*</bind>*/(u); } } static class S { internal static void E(this object x, object y) { } internal static void E<T>(this object o) { } internal static void E<T, U>(this T t, U u) { } internal static void E<T, U>(this I<T> t, U u) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Utils.CheckISymbols(semanticInfo.MethodGroup, "void T.E<T, U>(U u)"); } [WorkItem(541297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541297")] [Fact] public void GenericExtensionMethodCall() { // Single applicable overload with valid argument. var semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { /*<bind>*/s.E(s)/*</bind>*/; } } static class S { internal static void E<T>(this T x, object y) { } internal static void E<T, U>(this T x, U y) { } }"); Utils.CheckSymbol(semanticInfo.Symbol, "void string.E<string, string>(string y)"); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Multiple applicable overloads with valid arguments. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s, object o) { /*<bind>*/s.E(s, o)/*</bind>*/; } } static class S { internal static void E<T>(this object x, T y, object z) { } internal static void E<T, U>(this T x, object y, U z) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void object.E<string>(string y, object z)", "void string.E<string, object>(object y, object z)"); // Multiple applicable overloads with error argument. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { /*<bind>*/s.E(t, s)/*</bind>*/; } } static class S { internal static void E<T>(this T x, T y, object z) { } internal static void E<T, U>(this T x, string y, U z) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void string.E<string>(string y, object z)", "void string.E<string, string>(string y, string z)"); // Multiple overloads but all inaccessible. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { /*<bind>*/s.E()/*</bind>*/; } } static class S { static void E(this string x) { } static void E<T>(this T x) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols /* no candidates */ ); } [Fact] public void GenericExtensionDelegateMethod() { // Single applicable overload. var semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { System.Action<string> a = /*<bind>*/s.E/*</bind>*/; } } static class S { internal static void E<T>(this T x, T y) { } internal static void E<T>(this object x, T y) { } }"); Utils.CheckSymbol(semanticInfo.Symbol, "void string.E<string>(string y)"); Utils.CheckISymbols(semanticInfo.MethodGroup, "void string.E<string>(string y)", "void object.E<T>(T y)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Multiple applicable overloads. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { System.Action<string> a = /*<bind>*/s.E/*</bind>*/; } } static class S { internal static void E<T>(this T x, T y) { } internal static void E<T, U>(this T x, U y) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup, "void string.E<string>(string y)", "void string.E<string, U>(U y)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void string.E<string>(string y)", "void string.E<string, U>(U y)"); } /// <summary> /// Overloads from different scopes should /// be included in method group. /// </summary> [WorkItem(541890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541890")] [Fact] public void IncompleteExtensionOverloadedDifferentScopes() { // Instance methods and extension method (implicit instance). var sourceCode = @"class C { void M() { /*<bind>*/F/*</bind>*/( } void F(int x) { } void F(object x, object y) { } } static class E { internal static void F(this object x, object y) { } }"; var compilation = (Compilation)CreateCompilation(source: sourceCode); var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); var symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)"); symbols = model.LookupSymbols(expr.SpanStart, container: null, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)", "void object.F(object y)"); // Instance methods and extension method (explicit instance). sourceCode = @"class C { void M() { /*<bind>*/this.F/*</bind>*/( } void F(int x) { } void F(object x, object y) { } } static class E { internal static void F(this object x, object y) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)", "void object.F(object y)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)", "void object.F(object y)"); // Applicable instance method and inapplicable extension method. sourceCode = @"class C { void M() { /*<bind>*/this.F<string>/*</bind>*/( } void F<T>(T t) { } } static class E { internal static void F(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F<string>(string t)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F<T>(T t)", "void object.F()"); // Inaccessible instance method and accessible extension method. sourceCode = @"class A { void F() { } } class B : A { static void M(A a) { /*<bind>*/a.F/*</bind>*/( } } static class E { internal static void F(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void object.F()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F()"); // Inapplicable instance method and applicable extension method. sourceCode = @"class C { void M() { /*<bind>*/this.F<string>/*</bind>*/( } void F(object o) { } } static class E { internal static void F<T>(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void object.F<string>()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(object o)", "void object.F<T>()"); // Viable instance and extension methods, binding to extension method. sourceCode = @"class C { void M() { /*<bind>*/this.F/*</bind>*/(); } void F(object o) { } } static class E { internal static void F(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(object o)", "void object.F()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(object o)", "void object.F()"); // Applicable and inaccessible extension methods. sourceCode = @"class C { void M(string s) { /*<bind>*/s.F<string>/*</bind>*/( } } static class E { internal static void F(this object x, object y) { } internal static void F<T>(this T t) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GetSpecialType(SpecialType.System_String); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void string.F<string>()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F(object y)", "void string.F<string>()"); // Inapplicable and inaccessible extension methods. sourceCode = @"class C { void M(string s) { /*<bind>*/s.F<string>/*</bind>*/( } } static class E { internal static void F(this object x, object y) { } private static void F<T>(this T t) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GetSpecialType(SpecialType.System_String); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void string.F<string>()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F(object y)"); // Multiple scopes. sourceCode = @"namespace N1 { static class E { internal static void F(this object o) { } } } namespace N2 { using N1; class C { static void M(C c) { /*<bind>*/c.F/*</bind>*/( } void F(int x) { } } static class E { internal static void F(this object x, object y) { } } } static class E { internal static void F(this object x, object y, object z) { } }"; compilation = CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N2").GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(int x)", "void object.F(object y)", "void object.F()", "void object.F(object y, object z)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void object.F(object y)", "void object.F()", "void object.F(object y, object z)"); // Multiple scopes, no instance methods. sourceCode = @"namespace N { class C { static void M(C c) { /*<bind>*/c.F/*</bind>*/( } } static class E { internal static void F(this object x, object y) { } } } static class E { internal static void F(this object x, object y, object z) { } }"; compilation = CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N").GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void object.F(object y)", "void object.F(object y, object z)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F(object y)", "void object.F(object y, object z)"); } [ClrOnlyFact] public void PropertyGroup() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Property P(Optional x As Integer = 0) As Object Get Return Nothing End Get Set End Set End Property Property P(x As Integer, y As Integer) As Integer Get Return Nothing End Get Set End Set End Property Property P(x As Integer, y As String) As String Get Return Nothing End Get Set End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped); // Assignment (property group). var source2 = @"class B { static void M(A a) { /*<bind>*/a.P/*</bind>*/[1, null] = string.Empty; } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Assignment (property access). source2 = @"class B { static void M(A a) { /*<bind>*/a.P[1, null]/*</bind>*/ = string.Empty; } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.MemberGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Object initializer. source2 = @"class B { static A F = new A() { /*<bind>*/P/*</bind>*/ = 1 }; }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object A.P[int x = 0]"); Utils.CheckISymbols(semanticInfo.MemberGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Incomplete reference, overload resolution failure (property group). source2 = @"class B { static void M(A a) { var o = /*<bind>*/a.P/*</bind>*/[1, a } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); // Incomplete reference, overload resolution failure (property access). source2 = @"class B { static void M(A a) { var o = /*<bind>*/a.P[1, a/*</bind>*/ } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MemberGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); } [ClrOnlyFact] public void PropertyGroupOverloadsOverridesHides() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Overridable ReadOnly Property P1(index As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P2(index As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P2(x As Object, y As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P3(index As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P3(x As Object, y As Object) As Object Get Return Nothing End Get End Property End Class <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E212"")> Public Class B Inherits A Overrides ReadOnly Property P1(index As Object) As Object Get Return Nothing End Get End Property Shadows ReadOnly Property P2(index As String) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped); // Overridden property. var source2 = @"class C { static object F(B b) { return /*<bind>*/b.P1/*</bind>*/[null]; } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object B.P1[object index]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P1[object index]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Hidden property. source2 = @"class C { static object F(B b) { return /*<bind>*/b.P2/*</bind>*/[null]; } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object B.P2[string index]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P2[string index]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Overloaded property. source2 = @"class C { static object F(B b) { return /*<bind>*/b.P3/*</bind>*/[null]; } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object A.P3[object index]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P3[object index]", "object A.P3[object x, object y]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); } [WorkItem(538859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538859")] [Fact] public void ThisExpression() { string sourceCode = @" class C { void M() { /*<bind>*/this/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C this", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538143")] [Fact] public void GetSemanticInfoOfNull() { var compilation = CreateCompilation(""); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetConstantValue((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ConstructorInitializerSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ConstructorInitializerSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ConstructorInitializerSyntax)null)); } [WorkItem(537860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537860")] [Fact] public void UsingNamespaceName() { string sourceCode = @" using /*<bind>*/System/*</bind>*/; class Test { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3017, "DevDiv_Projects/Roslyn")] [Fact] public void VariableUsedInForInit() { string sourceCode = @" class Test { void Fill() { for (int i = 0; /*<bind>*/i/*</bind>*/ < 10 ; i++ ) { } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527269")] [Fact] public void NullLiteral() { string sourceCode = @" class Test { public static void Main() { string s = /*<bind>*/null/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [WorkItem(3019, "DevDiv_Projects/Roslyn")] [Fact] public void PostfixIncrement() { string sourceCode = @" class Test { public static void Main() { int i = 10; /*<bind>*/i++/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 System.Int32.op_Increment(System.Int32 value)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3199, "DevDiv_Projects/Roslyn")] [Fact] public void ConditionalOrExpr() { string sourceCode = @" class Program { static void T1() { bool result = /*<bind>*/true || true/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [WorkItem(3222, "DevDiv_Projects/Roslyn")] [Fact] public void ConditionalOperExpr() { string sourceCode = @" class Program { static void Main() { int i = /*<bind>*/(true ? 0 : 1)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(0, semanticInfo.ConstantValue); } [WorkItem(3223, "DevDiv_Projects/Roslyn")] [Fact] public void DefaultValueExpr() { string sourceCode = @" class Test { static void Main(string[] args) { int s = /*<bind>*/default(int)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(0, semanticInfo.ConstantValue); } [WorkItem(537979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537979")] [Fact] public void StringConcatWithInt() { string sourceCode = @" public class Test { public static void Main(string[] args) { string str = /*<bind>*/""Count value is: "" + 5/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3226, "DevDiv_Projects/Roslyn")] [Fact] public void StringConcatWithIntAndNullableInt() { string sourceCode = @" public class Test { public static void Main(string[] args) { string str = /*<bind>*/""Count value is: "" + (int?) 10 + 5/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3234, "DevDiv_Projects/Roslyn")] [Fact] public void AsOper() { string sourceCode = @" public class Test { public static void Main(string[] args) { object o = null; string str = /*<bind>*/o as string/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537983")] [Fact] public void AddWithUIntAndInt() { string sourceCode = @" public class Test { public static void Main(string[] args) { uint ui = 0; ulong ui2 = /*<bind>*/ui + 5/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.UInt32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.UInt64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.UInt32 System.UInt32.op_Addition(System.UInt32 left, System.UInt32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527314")] [Fact()] public void AddExprWithNullableUInt64AndInt32() { string sourceCode = @" public class Test { public static void Main(string[] args) { ulong? ui = 0; ulong? ui2 = /*<bind>*/ui + 5/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.UInt64?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.UInt64?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("ulong.operator +(ulong, ulong)", semanticInfo.Symbol.ToString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3248, "DevDiv_Projects/Roslyn")] [Fact] public void NegatedIsExpr() { string sourceCode = @" using System; public class Test { public static void Main() { Exception e = new Exception(); bool bl = /*<bind>*/!(e is DivideByZeroException)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Boolean.op_LogicalNot(System.Boolean value)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3249, "DevDiv_Projects/Roslyn")] [Fact] public void IsExpr() { string sourceCode = @" using System; public class Test { public static void Main() { Exception e = new Exception(); bool bl = /*<bind>*/ (e is DivideByZeroException) /*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527324")] [Fact] public void ExceptionCatchVariable() { string sourceCode = @" using System; public class Test { public static void Main() { try { } catch (Exception e) { bool bl = (/*<bind>*/e/*</bind>*/ is DivideByZeroException) ; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Exception", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Exception", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Exception e", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3478, "DevDiv_Projects/Roslyn")] [Fact] public void GenericInvocation() { string sourceCode = @" class Program { public static void Ref<T>(T array) { } static void Main() { /*<bind>*/Ref<object>(null)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void Program.Ref<System.Object>(System.Object array)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538039")] [Fact] public void GlobalAliasQualifiedName() { string sourceCode = @" namespace N1 { interface I1 { void Method(); } } namespace N2 { class Test : N1.I1 { void /*<bind>*/global::N1.I1/*</bind>*/.Method() { } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.I1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("N1.I1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.I1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527363")] [Fact] public void ArrayInitializer() { string sourceCode = @" class Test { static void Main() { int[] arr = new int[] /*<bind>*/{5}/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538041")] [Fact] public void AliasQualifiedName() { string sourceCode = @" using NSA = A; namespace A { class Goo {} } namespace B { class Test { class NSA { } static void Main() { /*<bind>*/NSA::Goo/*</bind>*/ goo = new NSA::Goo(); } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A.Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A.Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A.Goo", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538021")] [Fact] public void EnumToStringInvocationExpr() { string sourceCode = @" using System; enum E { Red, Blue, Green} public class MainClass { public static int Main () { E e = E.Red; string s = /*<bind>*/e.ToString()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String System.Enum.ToString()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538026")] [Fact] public void ExplIfaceMethInvocationExpr() { string sourceCode = @" namespace N1 { interface I1 { int Method(); } } namespace N2 { class Test : N1.I1 { int N1.I1.Method() { return 5; } static int Main() { Test t = new Test(); if (/*<bind>*/((N1.I1)t).Method()/*</bind>*/ != 5) return 1; return 0; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 N1.I1.Method()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538027")] [Fact] public void InvocExprWithAliasIdentifierNameSameAsType() { string sourceCode = @" using N1 = NGoo; namespace NGoo { class Goo { public static void method() { } } } namespace N2 { class N1 { } class Test { static void Main() { /*<bind>*/N1::Goo.method()/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void NGoo.Goo.method()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3498, "DevDiv_Projects/Roslyn")] [Fact] public void BaseAccessMethodInvocExpr() { string sourceCode = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { /*<bind>*/base.MyMeth()/*</bind>*/; } public static void Main() { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void BaseClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")] [Fact] public void OverloadResolutionForVirtualMethods() { string sourceCode = @" using System; class Program { static void Main() { D d = new D(); string s = ""hello""; long l = 1; /*<bind>*/d.goo(ref s, l, l)/*</bind>*/; } } public class B { // Should bind to this method. public virtual int goo(ref string x, long y, long z) { Console.WriteLine(""Base: goo(ref string x, long y, long z)""); return 0; } public virtual void goo(ref string x, params long[] y) { Console.WriteLine(""Base: goo(ref string x, params long[] y)""); } } public class D: B { // Roslyn erroneously binds to this override. // Roslyn binds to the correct method above if you comment out this override. public override void goo(ref string x, params long[] y) { Console.WriteLine(""Derived: goo(ref string x, params long[] y)""); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 B.goo(ref System.String x, System.Int64 y, System.Int64 z)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")] [Fact] public void OverloadResolutionForVirtualMethods2() { string sourceCode = @" using System; class Program { static void Main() { D d = new D(); int i = 1; /*<bind>*/d.goo(i, i)/*</bind>*/; } } public class B { public virtual int goo(params int[] x) { Console.WriteLine(""""Base: goo(params int[] x)""""); return 0; } public virtual void goo(params object[] x) { Console.WriteLine(""""Base: goo(params object[] x)""""); } } public class D: B { public override void goo(params object[] x) { Console.WriteLine(""""Derived: goo(params object[] x)""""); } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 B.goo(params System.Int32[] x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ThisInStaticMethod() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/this/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("Program", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("Program this", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Constructor1() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/A/*</bind>*/(4); } } class A { public A() { } public A(int x) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Constructor2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new A(4)/*</bind>*/; } } class A { public A() { } public A(int x) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("A..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void FailedOverloadResolution1() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; /*<bind>*/A.f(o)/*</bind>*/; } } class A { public void f(int x, int y) { } public void f(string z) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void FailedOverloadResolution2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; A./*<bind>*/f/*</bind>*/(o); } } class A { public void f(int x, int y) { } public void f(string z) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void A.f(System.String z)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541745")] [Fact] public void FailedOverloadResolution3() { string sourceCode = @" class C { public int M { get; set; } } static class Extensions1 { public static int M(this C c) { return 0; } } static class Extensions2 { public static int M(this C c) { return 0; } } class Goo { void M() { C c = new C(); /*<bind>*/c.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("System.Int32 C.M()", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.Int32 C.M()", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542833")] [Fact] public void FailedOverloadResolution4() { string sourceCode = @" class C { public int M; } static class Extensions { public static int M(this C c, int i) { return 0; } } class Goo { void M() { C c = new C(); /*<bind>*/c.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SucceededOverloadResolution1() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; /*<bind>*/A.f(""hi"")/*</bind>*/; } } class A { public static void f(int x, int y) { } public static int f(string z) { return 3; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SucceededOverloadResolution2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; A./*<bind>*/f/*</bind>*/(""hi""); } } class A { public static void f(int x, int y) { } public static int f(string z) { return 3; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 A.f(System.String z)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541878")] [Fact] public void TestCandidateReasonForInaccessibleMethod() { string sourceCode = @" class Test { class NestedTest { static void Method1() { } } static void Main() { /*<bind>*/NestedTest.Method1()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void Test.NestedTest.Method1()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); } [WorkItem(541879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541879")] [Fact] public void InaccessibleTypeInObjectCreationExpression() { string sourceCode = @" class Test { class NestedTest { class NestedNestedTest { } } static void Main() { var nnt = /*<bind>*/new NestedTest.NestedNestedTest()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Test.NestedTest.NestedNestedTest..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); } [WorkItem(541883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541883")] [Fact] public void InheritedMemberHiding() { string sourceCode = @" public class A { public static int m() { return 1; } } public class B : A { public static int m() { return 5; } public static void Main1() { /*<bind>*/m/*</bind>*/(10); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 B.m()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 B.m()", sortedMethodGroup[0].ToTestDisplayString()); } [WorkItem(538106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538106")] [Fact] public void UsingAliasNameSystemInvocExpr() { string sourceCode = @" using System = MySystem.IO.StreamReader; namespace N1 { using NullStreamReader = System::NullStreamReader; class Test { static int Main() { NullStreamReader nr = new NullStreamReader(); /*<bind>*/nr.ReadLine()/*</bind>*/; return 0; } } } namespace MySystem { namespace IO { namespace StreamReader { public class NullStreamReader { public string ReadLine() { return null; } } } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String MySystem.IO.StreamReader.NullStreamReader.ReadLine()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538109")] [Fact] public void InterfaceMethodImplInvocExpr() { string sourceCode = @" interface ISomething { string ToString(); } class A : ISomething { string ISomething.ToString() { return null; } } class Test { static void Main() { ISomething isome = new A(); /*<bind>*/isome.ToString()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String ISomething.ToString()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538112")] [Fact] public void MemberAccessMethodWithNew() { string sourceCode = @" public class MyBase { public void MyMeth() { } } public class MyClass : MyBase { new public void MyMeth() { } public static void Main() { MyClass test = new MyClass(); /*<bind>*/test.MyMeth/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void MyClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void MyClass.MyMeth()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527386")] [Fact] public void MethodGroupWithStaticInstanceSameName() { string sourceCode = @" class D { public static void M2(int x, int y) { } public void M2(int x) { } } class C { public static void Main() { D d = new D(); /*<bind>*/d.M2/*</bind>*/(5); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void D.M2(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void D.M2(System.Int32 x)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void D.M2(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538123")] [Fact] public void VirtualOverriddenMember() { string sourceCode = @" public class C1 { public virtual void M1() { } } public class C2:C1 { public override void M1() { } } public class Test { static void Main() { C2 c2 = new C2(); /*<bind>*/c2.M1/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void C2.M1()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C2.M1()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538125")] [Fact] public void AbstractOverriddenMember() { string sourceCode = @" public abstract class AbsClass { public abstract void Test(); } public class TestClass : AbsClass { public override void Test() { } public static void Main() { TestClass tc = new TestClass(); /*<bind>*/tc.Test/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void TestClass.Test()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void TestClass.Test()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DiamondInheritanceMember() { string sourceCode = @" public interface IB { void M(); } public interface IM1 : IB {} public interface IM2 : IB {} public interface ID : IM1, IM2 {} public class Program { public static void Main() { ID id = null; /*<bind>*/id.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); // We must ensure that the method is only found once, even though there are two paths to it. Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void IB.M()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void IB.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InconsistentlyHiddenMember() { string sourceCode = @" public interface IB { void M(); } public interface IL : IB {} public interface IR : IB { new void M(); } public interface ID : IR, IL {} public class Program { public static void Main() { ID id = null; /*<bind>*/id.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); // Even though there is a "path" from ID to IB.M via IL on which IB.M is not hidden, // it is still hidden because *any possible hiding* hides the method. Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void IR.M()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void IR.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538138")] [Fact] public void ParenExprWithMethodInvocExpr() { string sourceCode = @" class Test { public static int Meth1() { return 9; } public static void Main() { int var1 = /*<bind>*/(Meth1())/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Test.Meth1()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527397")] [Fact()] public void ExplicitIdentityCastExpr() { string sourceCode = @" class Test { public static void Main() { int i = 10; object j = /*<bind>*/(int)i/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3652, "DevDiv_Projects/Roslyn")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(543619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543619")] [Fact()] public void OutOfBoundsConstCastToByte() { string sourceCode = @" class Test { public static void Main() { byte j = unchecked(/*<bind>*/(byte)-123/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal((byte)133, semanticInfo.ConstantValue); } [WorkItem(538160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538160")] [Fact] public void InsideCollectionsNamespace() { string sourceCode = @" using System; namespace Collections { public class Test { public static /*<bind>*/void/*</bind>*/ Main() { } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Void", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538161")] [Fact] public void ErrorTypeNameSameAsVariable() { string sourceCode = @" public class A { public static void RunTest() { /*<bind>*/B/*</bind>*/ B = new B(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("B B", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Local, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537117")] [WorkItem(537127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537127")] [Fact] public void SystemNamespace() { string sourceCode = @" namespace System { class A { /*<bind>*/System/*</bind>*/.Exception c; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537118")] [Fact] public void SystemNamespace2() { string sourceCode = @" namespace N1 { namespace N2 { public class A1 { } } public class A2 { /*<bind>*/N1.N2.A1/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.N2.A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.N2.A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.N2.A1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537119")] [Fact] public void SystemNamespace3() { string sourceCode = @" class H<T> { } class A { } namespace N1 { public class A1 { /*<bind>*/H<A>/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("H<A>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("H<A>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("H<A>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537124")] [Fact] public void SystemNamespace4() { string sourceCode = @" using System; class H<T> { } class H<T1, T2> { } class A { } namespace N1 { public class A1 { /*<bind>*/H<H<A>, H<A>>/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("H<H<A>, H<A>>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("H<H<A>, H<A>>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("H<H<A>, H<A>>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537160")] [Fact] public void SystemNamespace5() { string sourceCode = @" namespace N1 { namespace N2 { public class A2 { public class A1 { } /*<bind>*/N1.N2.A2.A1/*</bind>*/ a; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.N2.A2.A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.N2.A2.A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.N2.A2.A1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537161")] [Fact] public void SystemNamespace6() { string sourceCode = @" namespace N1 { class NC1 { public class A1 { } } public class A2 { /*<bind>*/N1.NC1.A1/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.NC1.A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.NC1.A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.NC1.A1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537340")] [Fact] public void LeftOfDottedTypeName() { string sourceCode = @" class Main { A./*<bind>*/B/*</bind>*/ x; // this refers to the B within A. } class A { public class B {} } class B {} "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A.B", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537592")] [Fact] public void Parameters() { string sourceCode = @" class C { void M(DateTime dt) { /*<bind>*/dt/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("DateTime", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("DateTime", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("DateTime dt", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } // TODO: This should probably have a candidate symbol! [WorkItem(527212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527212")] [Fact] public void FieldMemberOfConstructedType() { string sourceCode = @" class C<T> { public T Field; } class D { void M() { new C<int>./*<bind>*/Field/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C<System.Int32>.Field", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("C<System.Int32>.Field", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); // Should bind to "field" with a candidateReason (not a typeornamespace>) Assert.NotEqual(CandidateReason.None, semanticInfo.CandidateReason); Assert.NotEqual(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537593")] [Fact] public void Constructor() { string sourceCode = @" class C { public C() { /*<bind>*/new C()/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538046")] [Fact] public void TypeNameInTypeThatMatchesNamespace() { string sourceCode = @" namespace T { class T { void M() { /*<bind>*/T/*</bind>*/.T T = new T.T(); } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("T.T", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("T.T", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("T.T", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538267")] [Fact] public void RHSExpressionInTryParent() { string sourceCode = @" using System; public class Test { static int Main() { try { object obj = /*<bind>*/null/*</bind>*/; } catch {} return 0; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")] [Fact] public void GenericArgumentInBase1() { string sourceCode = @" public class X { public interface Z { } } class A<T> { public class X { } } class B : A<B.Y./*<bind>*/Z/*</bind>*/> { public class Y : X { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("B.Y.Z", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("B.Y.Z", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")] [Fact] public void GenericArgumentInBase2() { string sourceCode = @" public class X { public interface Z { } } class A<T> { public class X { } } class B : /*<bind>*/A<B.Y.Z>/*</bind>*/ { public class Y : X { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A<B.Y.Z>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A<B.Y.Z>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A<B.Y.Z>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538097")] [Fact] public void InvokedLocal1() { string sourceCode = @" class C { static void Goo() { int x = 10; /*<bind>*/x/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538318")] [Fact] public void TooManyConstructorArgs() { string sourceCode = @" class C { C() {} void M() { /*<bind>*/new C(null /*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538185")] [Fact] public void NamespaceAndFieldSameName1() { string sourceCode = @" class C { void M() { /*<bind>*/System/*</bind>*/.String x = F(); } string F() { return null; } public int System; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void PEProperty() { string sourceCode = @" class C { void M(string s) { /*<bind>*/s.Length/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 System.String.Length { get; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NotPresentGenericType1() { string sourceCode = @" class Class { void Test() { /*<bind>*/List<int>/*</bind>*/ l; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NotPresentGenericType2() { string sourceCode = @" class Class { /*<bind>*/List<int>/*</bind>*/ Test() { return null;} } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BadArityConstructorCall() { string sourceCode = @" class C<T1> { public void Test() { C c = new /*<bind>*/C/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C<T1>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BadArityConstructorCall2() { string sourceCode = @" class C<T1> { public void Test() { C c = /*<bind>*/new C()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C<T1>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C<T1>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C<T1>..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C<T1>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void UnresolvedBaseConstructor() { string sourceCode = @" class C : B { public C(int i) /*<bind>*/: base(i)/*</bind>*/ { } public C(string j, string k) : base() { } } class B { public B(string a, string b) { } public B() { } int i; } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("B..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("B..ctor(System.String a, System.String b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BoundBaseConstructor() { string sourceCode = @" class C : B { public C(int i) /*<bind>*/: base(""hi"", ""hello"")/*</bind>*/ { } public C(string j, string k) : base() { } } class B { public B(string a, string b) { } public B() { } int i; } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("B..ctor(System.String a, System.String b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540998")] [Fact] public void DeclarationWithinSwitchStatement() { string sourceCode = @"class C { static void M(int i) { switch (i) { case 0: string name = /*<bind>*/null/*</bind>*/; if (name != null) { } break; } } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.NotNull(semanticInfo); } [WorkItem(537573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537573")] [Fact] public void UndeclaredTypeAndCheckContainingSymbol() { string sourceCode = @" class C1 { void M() { /*<bind>*/F/*</bind>*/ f; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("F", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("F", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.Equal(SymbolKind.Namespace, semanticInfo.Type.ContainingSymbol.Kind); Assert.True(((INamespaceSymbol)semanticInfo.Type.ContainingSymbol).IsGlobalNamespace); } [WorkItem(538538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538538")] [Fact] public void AliasQualifier() { string sourceCode = @" using X = A; namespace A.B { } namespace N { using /*<bind>*/X/*</bind>*/::B; class X { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("X=A", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AliasQualifier2() { string sourceCode = @" using S = System.String; { class X { void Goo() { string x; x = /*<bind>*/S/*</bind>*/.Empty; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Equal("S=System.String", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal("String", aliasInfo.Target.Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void PropertyAccessor() { string sourceCode = @" class C { private object p = null; internal object P { set { p = /*<bind>*/value/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Object value", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void IndexerAccessorValue() { string sourceCode = @"class C { string[] values = new string[10]; internal string this[int i] { get { return values[i]; } set { values[i] = /*<bind>*/value/*</bind>*/; } } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("System.String value", semanticInfo.Symbol.ToTestDisplayString()); } [Fact] public void IndexerAccessorParameter() { string sourceCode = @"class C { string[] values = new string[10]; internal string this[short i] { get { return values[/*<bind>*/i/*</bind>*/]; } } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("System.Int16 i", semanticInfo.Symbol.ToTestDisplayString()); } [Fact] public void IndexerAccessNamedParameter() { string sourceCode = @"class C { string[] values = new string[10]; internal string this[short i] { get { return values[i]; } } void Method() { string s = this[/*<bind>*/i/*</bind>*/: 0]; } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); var symbol = semanticInfo.Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.True(symbol.ContainingSymbol.Kind == SymbolKind.Property && ((IPropertySymbol)symbol.ContainingSymbol).IsIndexer); Assert.Equal("System.Int16 i", symbol.ToTestDisplayString()); } [Fact] public void LocalConstant() { string sourceCode = @" class C { static void M() { const int i = 1; const int j = i + 1; const int k = /*<bind>*/j/*</bind>*/ - 2; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 j", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2, semanticInfo.ConstantValue); var symbol = (ILocalSymbol)semanticInfo.Symbol; Assert.True(symbol.HasConstantValue); Assert.Equal(2, symbol.ConstantValue); } [Fact] public void FieldConstant() { string sourceCode = @" class C { const int i = 1; const int j = i + 1; static void M() { const int k = /*<bind>*/j/*</bind>*/ - 2; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.j", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2, semanticInfo.ConstantValue); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.Equal("j", symbol.Name); Assert.True(symbol.HasConstantValue); Assert.Equal(2, symbol.ConstantValue); } [Fact] public void FieldInitializer() { string sourceCode = @" class C { int F = /*<bind>*/G() + 1/*</bind>*/; static int G() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void EnumConstant() { string sourceCode = @" enum E { A, B, C, D = B } class C { static void M(E e) { M(/*<bind>*/E.C/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2, semanticInfo.ConstantValue); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("C", symbol.Name); Assert.True(symbol.HasConstantValue); Assert.Equal(2, symbol.ConstantValue); } [Fact] public void BadEnumConstant() { string sourceCode = @" enum E { W = Z, X, Y } class C { static void M(E e) { M(/*<bind>*/E.Y/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.Y", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("Y", symbol.Name); Assert.False(symbol.HasConstantValue); } [Fact] public void CircularEnumConstant01() { string sourceCode = @" enum E { A = B, B } class C { static void M(E e) { M(/*<bind>*/E.B/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("B", symbol.Name); Assert.False(symbol.HasConstantValue); } [Fact] public void CircularEnumConstant02() { string sourceCode = @" enum E { A = 10, B = C, C, D } class C { static void M(E e) { M(/*<bind>*/E.D/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.D", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("D", symbol.Name); Assert.False(symbol.HasConstantValue); } [Fact] public void EnumInitializer() { string sourceCode = @" enum E { A, B = 3 } enum F { C, D = 1 + /*<bind>*/E.B/*</bind>*/ } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(3, semanticInfo.ConstantValue); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("B", symbol.Name); Assert.True(symbol.HasConstantValue); Assert.Equal(3, symbol.ConstantValue); } [Fact] public void ParameterOfExplicitInterfaceImplementation() { string sourceCode = @" class Class : System.IFormattable { string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider) { return /*<bind>*/format/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String format", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BaseConstructorInitializer() { string sourceCode = @" class Class { Class(int x) : this(/*<bind>*/x/*</bind>*/ , x) { } Class(int x, int y) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.ContainingSymbol.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind); } [WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")] [WorkItem(527831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527831")] [WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")] [Fact] public void InaccessibleMethodGroup() { string sourceCode = @" class C { private static void M(long i) { } private static void M(int i) { } } class D { void Goo() { C./*<bind>*/M/*</bind>*/(1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal("void C.M(System.Int64 i)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void C.M(System.Int64 i)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_Constructors_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = /*<bind>*/new Class1(3, 7)/*</bind>*/; } } class Class1 { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleMethodGroup_Constructors_ImplicitObjectCreationExpressionSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { Class1 x = /*<bind>*/new(3, 7)/*</bind>*/; } } class Class1 { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_Constructors_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = new /*<bind>*/Class1/*</bind>*/(3, 7); } } class Class1 { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_AttributeSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1(3, 7)/*</bind>*/] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_Attribute_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1/*</bind>*/(3, 7)] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = /*<bind>*/new Class1(3, 7)/*</bind>*/; } } class Class1 { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = new /*<bind>*/Class1/*</bind>*/(3, 7); } } class Class1 { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_AttributeSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1(3, 7)/*</bind>*/] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_Attribute_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1/*</bind>*/(3, 7)] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")] [Fact] public void SyntaxErrorInReceiver() { string sourceCode = @" public delegate int D(int x); public class C { public C(int i) { } public void M(D d) { } } class Main { void Goo(int a) { new C(a.).M(x => /*<bind>*/x/*</bind>*/); } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")] [Fact] public void SyntaxErrorInReceiverWithExtension() { string sourceCode = @" public delegate int D(int x); public static class CExtensions { public static void M(this C c, D d) { } } public class C { public C(int i) { } } class Main { void Goo(int a) { new C(a.).M(x => /*<bind>*/x/*</bind>*/); } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")] [Fact] public void NonStaticInstanceMismatchMethodGroup() { string sourceCode = @" class C { public static int P { get; set; } } class D { void Goo() { C./*<bind>*/set_P/*</bind>*/(1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.P.set", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(MethodKind.PropertySet, ((IMethodSymbol)sortedCandidates[0]).MethodKind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.P.set", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540360")] [Fact] public void DuplicateTypeName() { string sourceCode = @" struct C { } class C { public static void M() { } } enum C { A, B } class D { static void Main() { /*<bind>*/C/*</bind>*/.M(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("C", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal("C", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[2].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void IfCondition() { string sourceCode = @" class C { void M(int x) { if (/*<bind>*/x == 10/*</bind>*/) {} } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ForCondition() { string sourceCode = @" class C { void M(int x) { for (int i = 0; /*<bind>*/i < 10/*</bind>*/; i = i + 1) { } } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(539925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539925")] [Fact] public void LocalIsFromSource() { string sourceCode = @" class C { void M() { int x = 1; int y = /*<bind>*/x/*</bind>*/; } } "; var compilation = CreateCompilation(sourceCode); var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(compilation); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.True(semanticInfo.Symbol.GetSymbol().IsFromCompilation(compilation)); } [WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")] [Fact] public void InEnumElementInitializer() { string sourceCode = @" class C { public const int x = 1; } enum E { q = /*<bind>*/C.x/*</bind>*/, } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")] [Fact] public void InEnumOfByteElementInitializer() { string sourceCode = @" class C { public const int x = 1; } enum E : byte { q = /*<bind>*/C.x/*</bind>*/, } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540672")] [Fact] public void LambdaExprWithErrorTypeInObjectCreationExpression() { var text = @" class Program { static int Main() { var d = /*<bind>*/() => { if (true) return new X(); else return new Y(); }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(text, parseOptions: TestOptions.Regular9); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [Fact] public void LambdaExpression() { string sourceCode = @" using System; public class TestClass { public static void Main() { Func<string, int> f = /*<bind>*/str => 10/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Func<System.String, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind); Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol); Assert.Equal(1, lambdaSym.Parameters.Length); Assert.Equal("str", lambdaSym.Parameters[0].Name); Assert.Equal("System.String", lambdaSym.Parameters[0].Type.ToTestDisplayString()); Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void UnboundLambdaExpression() { string sourceCode = @" using System; public class TestClass { public static void Main() { object f = /*<bind>*/str => 10/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol); Assert.Equal(1, lambdaSym.Parameters.Length); Assert.Equal("str", lambdaSym.Parameters[0].Name); Assert.Equal(TypeKind.Error, lambdaSym.Parameters[0].Type.TypeKind); Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540650")] [Fact] public void TypeOfExpression() { string sourceCode = @" class C { static void Main() { System.Console.WriteLine(/*<bind>*/typeof(C)/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<TypeOfExpressionSyntax>(sourceCode); Assert.Equal("System.Type", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_If() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; if (c) int j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_For() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; for (; c; c = !c) label: /*<bind>*/c/*</bind>*/ = false; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_While() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; while (c) int j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_ForEach() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; foreach (string s in args) label: /*<bind>*/c/*</bind>*/ = false; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_Else() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; if (c); else long j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_Do() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; do label: /*<bind>*/c/*</bind>*/ = false; while(c); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_Using() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; using(null) long j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_Lock() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; lock(this) label: /*<bind>*/c/*</bind>*/ = false; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_Fixed() { string sourceCode = @" unsafe class Program { static void Main(string[] args) { bool c = true; fixed (bool* p = &c) int j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")] [Fact] public void BindLiteralCastToDouble() { string sourceCode = @" class MyClass { double dbl = /*<bind>*/1/*</bind>*/ ; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540803")] [Fact] public void BindDefaultOfVoidExpr() { string sourceCode = @" class C { void M() { return /*<bind>*/default(void)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Void, semanticInfo.Type.SpecialType); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void GetSemanticInfoForBaseConstructorInitializer() { string sourceCode = @" class C { C() /*<bind>*/: base()/*</bind>*/ { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void GetSemanticInfoForThisConstructorInitializer() { string sourceCode = @" class C { C() /*<bind>*/: this(1)/*</bind>*/ { } C(int x) { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")] [Fact] public void ThisStaticConstructorInitializer() { string sourceCode = @" class MyClass { static MyClass() /*<bind>*/: this()/*</bind>*/ { intI = 2; } public MyClass() { } static int intI = 1; } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("MyClass..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")] [Fact] public void IncompleteForEachWithArrayCreationExpr() { string sourceCode = @" class Program { static void Main(string[] args) { foreach (var f in new int[] { /*<bind>*/5/*</bind>*/ { Console.WriteLine(f); } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(5, (int)semanticInfo.ConstantValue.Value); } [WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")] [Fact] public void EmptyStatementInForEach() { string sourceCode = @" class Program { static void Main(string[] args) { foreach (var a in /*<bind>*/args/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, ((IArrayTypeSymbol)semanticInfo.Type).ElementType.SpecialType); // CONSIDER: we could conceivable use the foreach collection type (vs the type of the collection expr). Assert.Equal(SpecialType.System_Collections_IEnumerable, semanticInfo.ConvertedType.SpecialType); Assert.Equal("args", semanticInfo.Symbol.Name); } [WorkItem(540922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540922")] [WorkItem(541030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541030")] [Fact] public void ImplicitlyTypedForEachIterationVariable() { string sourceCode = @" class Program { static void Main(string[] args) { foreach (/*<bind>*/var/*</bind>*/ a in args); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); var symbol = semanticInfo.Symbol; Assert.Equal(SymbolKind.NamedType, symbol.Kind); Assert.Equal(SpecialType.System_String, ((ITypeSymbol)symbol).SpecialType); } [Fact] public void ForEachCollectionConvertedType() { // Arrays don't actually use IEnumerable, but that's the spec'd behavior. CheckForEachCollectionConvertedType("int[]", "System.Int32[]", "System.Collections.IEnumerable"); CheckForEachCollectionConvertedType("int[,]", "System.Int32[,]", "System.Collections.IEnumerable"); // Strings don't actually use string.GetEnumerator, but that's the spec'd behavior. CheckForEachCollectionConvertedType("string", "System.String", "System.String"); // Special case for dynamic CheckForEachCollectionConvertedType("dynamic", "dynamic", "System.Collections.IEnumerable"); // Pattern-based, not interface-based CheckForEachCollectionConvertedType("System.Collections.Generic.List<int>", "System.Collections.Generic.List<System.Int32>", "System.Collections.Generic.List<System.Int32>"); // Interface-based CheckForEachCollectionConvertedType("Enumerable", "Enumerable", "System.Collections.IEnumerable"); // helper method knows definition of this type // Interface CheckForEachCollectionConvertedType("System.Collections.Generic.IEnumerable<int>", "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.Generic.IEnumerable<System.Int32>"); // Interface CheckForEachCollectionConvertedType("NotAType", "NotAType", "NotAType"); // name not in scope } private void CheckForEachCollectionConvertedType(string sourceType, string typeDisplayString, string convertedTypeDisplayString) { string template = @" public class Enumerable : System.Collections.IEnumerable {{ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {{ return null; }} }} class Program {{ void M({0} collection) {{ foreach (var v in /*<bind>*/collection/*</bind>*/); }} }} "; var semanticInfo = GetSemanticInfoForTest(string.Format(template, sourceType)); Assert.Equal(typeDisplayString, semanticInfo.Type.ToTestDisplayString()); Assert.Equal(convertedTypeDisplayString, semanticInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void InaccessibleParameter() { string sourceCode = @" using System; class Outer { class Inner { } } class Program { public static void f(Outer.Inner a) { /*<bind>*/a/*</bind>*/ = 4; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Outer.Inner", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Outer.Inner", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Outer.Inner a", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); // Parameter's type is an error type, because Outer.Inner is inaccessible. var param = (IParameterSymbol)semanticInfo.Symbol; Assert.Equal(TypeKind.Error, param.Type.TypeKind); // It's type is not equal to the SemanticInfo type, because that is // not an error type. Assert.NotEqual(semanticInfo.Type, param.Type); } [Fact] public void StructConstructor() { string sourceCode = @" struct Struct{ public static void Main() { Struct s = /*<bind>*/new Struct()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); var symbol = semanticInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)symbol).MethodKind); Assert.True(symbol.IsImplicitlyDeclared); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroupAsArgOfInvalidConstructorCall() { string sourceCode = @" using System; class Class { string M(int i) { new T(/*<bind>*/M/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.String Class.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.String Class.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroupInReturnStatement() { string sourceCode = @" class C { public delegate int Func(int i); public Func Goo() { return /*<bind>*/Goo/*</bind>*/; } private int Goo(int i) { return i; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("C.Func", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C.Goo(int)", semanticInfo.ImplicitConversion.Method.ToString()); Assert.Equal("System.Int32 C.Goo(System.Int32 i)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C.Func C.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.Int32 C.Goo(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateConversionExtensionMethodNoReceiver() { string sourceCode = @"class C { static System.Action<object> F() { return /*<bind>*/S.E/*</bind>*/; } } static class S { internal static void E(this object o) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.NotNull(semanticInfo); Assert.Equal("System.Action<System.Object>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("void S.E(this System.Object o)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.ImplicitConversion.IsExtensionMethod); } [Fact] public void DelegateConversionExtensionMethod() { string sourceCode = @"class C { static System.Action F(object o) { return /*<bind>*/o.E/*</bind>*/; } } static class S { internal static void E(this object o) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.NotNull(semanticInfo); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("void System.Object.E()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.IsExtensionMethod); } [Fact] public void InferredVarType() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var x = ""hello""; /*<bind>*/var/*</bind>*/ y = x; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InferredVarTypeWithNamespaceInScope() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; namespace var { } class Program { static void Main(string[] args) { var x = ""hello""; /*<bind>*/var/*</bind>*/ y = x; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NonInferredVarType() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; namespace N1 { class var { } class Program { static void Main(string[] args) { /*<bind>*/var/*</bind>*/ x = ""hello""; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("N1.var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.var", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541207")] [Fact] public void UndeclaredVarInThrowExpr() { string sourceCode = @" class Test { static void Main() { throw /*<bind>*/d1.Get/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo); } [Fact] public void FailedConstructorCall() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class C { } class Program { static void Main(string[] args) { C c = new /*<bind>*/C/*</bind>*/(17); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void FailedConstructorCall2() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class C { } class Program { static void Main(string[] args) { C c = /*<bind>*/new C(17)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MemberGroup.Length); Assert.Equal("C..ctor()", semanticInfo.MemberGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541332")] [Fact] public void ImplicitConversionCastExpression() { string sourceCode = @" using System; enum E { a, b } class Program { static int Main() { int ret = /*<bind>*/(int) E.b/*</bind>*/; return ret - 1; } } "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToString()); Assert.Equal("int", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); } [WorkItem(541333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541333")] [Fact] public void ImplicitConversionAnonymousMethod() { string sourceCode = @" using System; delegate int D(); class Program { static int Main() { D d = /*<bind>*/delegate() { return int.MaxValue; }/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<AnonymousMethodExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("D", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.IsCompileTimeConstant); sourceCode = @" using System; delegate int D(); class Program { static int Main() { D d = /*<bind>*/() => { return int.MaxValue; }/*</bind>*/; return 0; } } "; semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("D", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528476")] [Fact] public void BindingInitializerToTargetType() { string sourceCode = @" using System; class Program { static int Main() { int[] ret = new int[] /*<bind>*/ { 0, 1, 2 } /*</bind>*/; return ret[0]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); } [Fact] public void BindShortMethodArgument() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void goo(short s) { } static void Main(string[] args) { goo(/*<bind>*/123/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(123, semanticInfo.ConstantValue); } [WorkItem(541400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541400")] [Fact] public void BindingAttributeParameter() { string sourceCode = @" using System; public class MeAttribute : Attribute { public MeAttribute(short p) { } } [Me(/*<bind>*/123/*</bind>*/)] public class C { } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal("int", semanticInfo.Type.ToString()); Assert.Equal("short", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); } [Fact] public void BindAttributeFieldNamedArgumentOnMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute() { } public string F; } class C1 { [Test(/*<bind>*/F/*</bind>*/=""method"")] int f() { return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String TestAttribute.F", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BindAttributePropertyNamedArgumentOnMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute() { } public TestAttribute(int i) { } public string F; public double P { get; set; } } class C1 { [Test(/*<bind>*/P/*</bind>*/=3.14)] int f() { return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Double TestAttribute.P { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void TestAttributeNamedArgumentValueOnMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute() { } public TestAttribute(int i) { } public string F; public double P { get; set; } } class C1 { [Test(P=/*<bind>*/1/*</bind>*/)] int f() { return 0; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540775")] [Fact] public void LambdaExprPrecededByAnIncompleteUsingStmt() { var code = @" using System; class Program { static void Main(string[] args) { using Func<int, int> Dele = /*<bind>*/ x => { return x; } /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(code); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [WorkItem(540785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540785")] [Fact] public void NestedLambdaExprPrecededByAnIncompleteNamespaceStmt() { var code = @" using System; class Program { static void Main(string[] args) { namespace Func<int, int> f1 = (x) => { Func<int, int> f2 = /*<bind>*/ (y) => { return y; } /*</bind>*/; return x; } ; } } "; var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(code); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [Fact] public void DefaultStructConstructor() { string sourceCode = @" using System; struct Struct{ public static void Main() { Struct s = new /*<bind>*/Struct/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Struct", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DefaultStructConstructor2() { string sourceCode = @" using System; struct Struct{ public static void Main() { Struct s = /*<bind>*/new Struct()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Struct..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")] [Fact] public void BindAttributeInstanceWithoutAttributeSuffix() { string sourceCode = @" [assembly: /*<bind>*/My/*</bind>*/] class MyAttribute : System.Attribute { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("MyAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")] [Fact] public void BindQualifiedAttributeInstanceWithoutAttributeSuffix() { string sourceCode = @" [assembly: /*<bind>*/N1.My/*</bind>*/] namespace N1 { class MyAttribute : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode); Assert.Equal("N1.MyAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540770")] [Fact] public void IncompleteDelegateCastExpression() { string sourceCode = @" delegate void D(); class MyClass { public static int Main() { D d; d = /*<bind>*/(D) delegate /*</bind>*/ "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("D", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("D", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(7177, "DevDiv_Projects/Roslyn")] [Fact] public void IncompleteGenericDelegateDecl() { string sourceCode = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Func<int, int> ()/*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541120")] [Fact] public void DelegateCreationArguments() { string sourceCode = @" class Program { int goo(int i) { return i;} static void Main(string[] args) { var r = /*<bind>*/new System.Func<int, int>((arg)=> { return 1;}, goo)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateCreationArguments2() { string sourceCode = @" class Program { int goo(int i) { return i;} static void Main(string[] args) { var r = new /*<bind>*/System.Func<int, int>/*</bind>*/((arg)=> { return 1;}, goo); } } "; var semanticInfo = GetSemanticInfoForTest<TypeSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BaseConstructorInitializer2() { string sourceCode = @" class C { C() /*<bind>*/: base()/*</bind>*/ { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol).MethodKind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ThisConstructorInitializer2() { string sourceCode = @" class C { C() /*<bind>*/: this(1)/*</bind>*/ { } C(int x) { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")] [Fact] public void TypeInParentOnFieldInitializer() { string sourceCode = @" class MyClass { double dbl = /*<bind>*/1/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [Fact] public void ExplicitIdentityConversion() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int y = 12; long x = /*<bind>*/(int)y/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541588")] [Fact] public void ImplicitConversionElementsInArrayInit() { string sourceCode = @" class MyClass { long[] l1 = {/*<bind>*/4L/*</bind>*/, 5L }; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int64", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(4L, semanticInfo.ConstantValue); } [WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")] [Fact] public void ImplicitConversionArrayInitializer_01() { string sourceCode = @" class MyClass { int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")] [Fact] public void ImplicitConversionArrayInitializer_02() { string sourceCode = @" class MyClass { void Test() { int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541595")] [Fact] public void ImplicitConversionExprReturnedByLambda() { string sourceCode = @" using System; class MyClass { Func<long> f1 = () => /*<bind>*/4/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.ImplicitConversion.IsIdentity); Assert.True(semanticInfo.ImplicitConversion.IsImplicit); Assert.True(semanticInfo.ImplicitConversion.IsNumeric); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(4, semanticInfo.ConstantValue); } [WorkItem(541040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541040")] [WorkItem(528551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528551")] [Fact] public void InaccessibleNestedType() { string sourceCode = @" using System; internal class EClass { private enum EEK { a, b, c, d }; } class Test { public void M(EClass.EEK e) { b = /*<bind>*/ e /*</bind>*/; } EClass.EEK b = EClass.EEK.a; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(SymbolKind.NamedType, semanticInfo.Type.Kind); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter1() { string sourceCode = @" using System; class Program { public void f(int x, int y, int z) { } public void f(string y, string z) { } public void goo() { f(3, /*<bind>*/z/*</bind>*/: 4, y: 9); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 z", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter2() { string sourceCode = @" using System; class Program { public void f(int x, int y, int z) { } public void f(string y, string z, int q) { } public void f(string q, int w, int b) { } public void goo() { f(3, /*<bind>*/z/*</bind>*/: ""goo"", y: 9); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 z", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind); Assert.Equal("System.String z", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter3() { string sourceCode = @" using System; class Program { public void f(int x, int y, int z) { } public void f(string y, string z, int q) { } public void f(string q, int w, int b) { } public void goo() { f(3, z: ""goo"", /*<bind>*/yagga/*</bind>*/: 9); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter4() { string sourceCode = @" using System; namespace ClassLibrary44 { [MyAttr(/*<bind>*/x/*</bind>*/:1)] public class Class1 { } public class MyAttr: Attribute { public MyAttr(int x) {} } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")] [Fact] public void ImplicitReferenceConvExtensionMethodReceiver() { string sourceCode = @"public static class Extend { public static string TestExt(this object o1) { return o1.ToString(); } } class Program { static void Main(string[] args) { string str1 = ""Test""; var e1 = /*<bind>*/str1/*</bind>*/.TestExt(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.IsReference); Assert.Equal("System.String str1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); } [WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")] [Fact] public void ImplicitBoxingConvExtensionMethodReceiver() { string sourceCode = @"struct S { } static class C { static void M(S s) { /*<bind>*/s/*</bind>*/.F(); } static void F(this object o) { } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("S", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.IsBoxing); Assert.Equal("S s", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); } [Fact] public void AttributeSyntaxBinding() { string sourceCode = @" using System; [/*<bind>*/MyAttr(1)/*</bind>*/] public class Class1 { } public class MyAttr: Attribute { public MyAttr(int x) {} } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); // Should bind to constructor. Assert.NotNull(semanticInfo.Symbol); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void MemberAccessOnErrorType() { string sourceCode = @" public class Test2 { public static void Main() { string x1 = A./*<bind>*/M/*</bind>*/.C.D.E; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void MemberAccessOnErrorType2() { string sourceCode = @" public class Test2 { public static void Main() { string x1 = A./*<bind>*/M/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")] [Fact] public void DelegateCreation1() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = new /*<bind>*/MyDelegate/*</bind>*/(this.F); MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = new MyDelegate(MD1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateCreation1_2() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = /*<bind>*/new MyDelegate(this.F)/*</bind>*/; MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = new MyDelegate(MD1); } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")] [Fact] public void DelegateCreation2() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = new MyDelegate(this.F); MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = new /*<bind>*/MyDelegate/*</bind>*/(MD1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")] [Fact] public void DelegateCreation2_2() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = new MyDelegate(this.F); MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = /*<bind>*/new MyDelegate(MD1)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateSignatureMismatch1() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = new /*<bind>*/Action/*</bind>*/(f); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Action", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateSignatureMismatch2() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = /*<bind>*/new Action(f)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateSignatureMismatch3() { // This test and the DelegateSignatureMismatch4 should have identical results, as they are semantically identical string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = new Action(/*<bind>*/f/*</bind>*/); } } "; { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.WithoutImprovedOverloadCandidates); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void DelegateSignatureMismatch4() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = /*<bind>*/f/*</bind>*/; } } "; { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.WithoutImprovedOverloadCandidates); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } } [WorkItem(541802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541802")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void IncompleteLetClause() { string sourceCode = @" public class Test2 { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/var/*</bind>*/ q2 = from x in nums let z = x. } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541895")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void QueryErrorBaseKeywordAsSelectExpression() { string sourceCode = @" using System; using System.Linq; public class QueryExpressionTest { public static void Main() { var expr1 = new int[] { 1 }; /*<bind>*/var/*</bind>*/ query2 = from int b in expr1 select base; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541805")] [Fact] public void InToIdentifierQueryContinuation() { string sourceCode = @" using System; using System.Linq; public class Test2 { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = from x in nums select x into w select /*<bind>*/w/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541833")] [Fact] public void InOptimizedAwaySelectClause() { string sourceCode = @" using System; using System.Linq; public class Test2 { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = from x in nums where x > 1 select /*<bind>*/x/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [Fact] public void InFromClause() { string sourceCode = @" using System; using System.Linq; class C { void M() { int rolf = 732; int roark = -9; var replicator = from r in new List<int> { 1, 2, 9, rolf, /*<bind>*/roark/*</bind>*/ } select r * 2; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541911")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void QueryErrorGroupJoinFromClause() { string sourceCode = @" class Test { static void Main() { /*<bind>*/var/*</bind>*/ q = from Goo i in i from Goo<int> j in j group i by i join Goo } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541920")] [Fact] public void SymbolInfoForMissingSelectClauseNode() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string[] strings = { }; var query = from s in strings let word = s.Split(' ') from w in w } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var selectClauseNode = tree.FindNodeOrTokenByKind(SyntaxKind.SelectClause).AsNode() as SelectClauseSyntax; var symbolInfo = semanticModel.GetSymbolInfo(selectClauseNode); // https://github.com/dotnet/roslyn/issues/38509 // Assert.NotEqual(default, symbolInfo); Assert.Null(symbolInfo.Symbol); } [WorkItem(541940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541940")] [Fact] public void IdentifierInSelectNotInContext() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string[] strings = { }; var query = from ch in strings group ch by ch into chGroup where chGroup.Count() >= 2 select /*<bind>*/ x1 /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); } [Fact] public void WhereDefinedInType() { var csSource = @" using System; class Y { public int Where(Func<int, bool> predicate) { return 45; } } class P { static void Main() { var src = new Y(); var query = from x in src where x > 0 select /*<bind>*/ x /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(csSource); Assert.Equal("x", semanticInfo.Symbol.Name); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541830")] [Fact] public void AttributeUsageError() { string sourceCode = @" using System; [/*<bind>*/AttributeUsage/*</bind>*/()] class MyAtt : Attribute {} "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal("AttributeUsageAttribute", semanticInfo.Type.Name); } [WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")] [Fact] public void OpenGenericTypeInAttribute() { string sourceCode = @" class Gen<T> {} [/*<bind>*/Gen<T>/*</bind>*/] public class Test { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")] [Fact] public void OpenGenericTypeInAttribute02() { string sourceCode = @" class Goo {} [/*<bind>*/Goo/*</bind>*/] public class Test { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")] [Fact] public void IncompleteEmptyAttributeSyntax01() { string sourceCode = @" public class CSEvent { [ "; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax; var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Symbol); Assert.Null(semanticInfo.Type); } /// <summary> /// Same as above but with a token after the incomplete /// attribute so the attribute is not at the end of file. /// </summary> [WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")] [Fact] public void IncompleteEmptyAttributeSyntax02() { string sourceCode = @" public class CSEvent { [ }"; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax; var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Symbol); Assert.Null(semanticInfo.Type); } [WorkItem(541857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541857")] [Fact] public void EventWithInitializerInInterface() { string sourceCode = @" public delegate void MyDelegate(); interface test { event MyDelegate e = /*<bind>*/new MyDelegate(Test.Main)/*</bind>*/; } class Test { static void Main() { } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("MyDelegate", semanticInfo.Type.ToTestDisplayString()); } [Fact] public void SwitchExpression_Constant01() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/true/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] [WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")] public void SwitchExpression_Constant02() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; const string s = null; switch (/*<bind>*/s/*</bind>*/) { case null: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [Fact] [WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")] public void SwitchExpression_NotConstant() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; string s = null; switch (/*<bind>*/s/*</bind>*/) { case null: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchExpression_Invalid_Lambda() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/()=>3/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Null(semanticInfo.Type); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchExpression_Invalid_MethodGroup() { string sourceCode = @" using System; public class Test { public static int M() {return 0; } public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/M/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Null(semanticInfo.Type); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchExpression_Invalid_GoverningType() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/2.2/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2.2, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_Null() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; const string s = null; switch (s) { case /*<bind>*/null/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [Fact] public void SwitchCaseLabelExpression_Constant01() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (true) { case /*<bind>*/true/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_Constant02() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; const bool x = true; switch (true) { case /*<bind>*/x/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_NotConstant() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; bool x = true; switch (true) { case /*<bind>*/x/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchCaseLabelExpression_CastExpression() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (ret) { case /*<bind>*/(int)'a'/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(97, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_Invalid_Lambda() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; string s = null; switch (s) { case /*<bind>*/()=>3/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; CreateCompilation(sourceCode).VerifyDiagnostics( // (12,30): error CS1003: Syntax error, ':' expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(12, 30), // (12,30): error CS1513: } expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(12, 30), // (12,44): error CS1002: ; expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(12, 44), // (12,44): error CS1513: } expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(12, 44), // (12,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(12, 28), // (12,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type. // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(12, 28) ); } [Fact] public void SwitchCaseLabelExpression_Invalid_LambdaWithSyntaxError() { string sourceCode = @" using System; public class Test { static int M() { return 0;} public static int Main(string[] args) { int ret = 1; string s = null; switch (s) { case /*<bind>*/()=>/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; CreateCompilation(sourceCode).VerifyDiagnostics( // (13,30): error CS1003: Syntax error, ':' expected // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(13, 30), // (13,30): error CS1513: } expected // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(13, 30), // (13,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(13, 28), // (13,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type. // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(13, 28) ); } [Fact] public void SwitchCaseLabelExpression_Invalid_MethodGroup() { string sourceCode = @" using System; public class Test { static int M() { return 0;} public static int Main(string[] args) { int ret = 1; string s = null; switch (s) { case /*<bind>*/M/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")] [Fact] public void IndexingExpression() { string sourceCode = @" class Test { static void Main() { string str = ""Test""; char ch = str[/*<bind>*/ 0 /*</bind>*/]; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(0, semanticInfo.ConstantValue); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [Fact] public void InaccessibleInTypeof() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class A { class B { } } class Program { static void Main(string[] args) { object o = typeof(/*<bind>*/A.B/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode); Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A.B", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AttributeWithUnboundGenericType01() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/B<>/*</bind>*/))] class B<T> { public class C { } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.True((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [Fact] public void AttributeWithUnboundGenericType02() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/B<>.C/*</bind>*/))] class B<T> { public class C { } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.True((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [Fact] public void AttributeWithUnboundGenericType03() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/D/*</bind>*/.C<>))] class B<T> { public class C<U> { } } class D : B<int> { }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.False((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [Fact] public void AttributeWithUnboundGenericType04() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/B<>/*</bind>*/.C<>))] class B<T> { public class C<U> { } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.Equal("B", type.Name); Assert.True((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [WorkItem(542430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542430")] [Fact] public void UnboundTypeInvariants() { var sourceCode = @"using System; public class A<T> { int x; public class B<U> { int y; } } class Program { public static void Main(string[] args) { Console.WriteLine(typeof(/*<bind>*/A<>.B<>/*</bind>*/)); } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = (INamedTypeSymbol)semanticInfo.Type; Assert.Equal("B", type.Name); Assert.True(type.IsUnboundGenericType); Assert.False(type.IsErrorType()); Assert.True(type.TypeArguments[0].IsErrorType()); var constructedFrom = type.ConstructedFrom; Assert.Equal(constructedFrom, constructedFrom.ConstructedFrom); Assert.Equal(constructedFrom, constructedFrom.TypeParameters[0].ContainingSymbol); Assert.Equal(constructedFrom.TypeArguments[0], constructedFrom.TypeParameters[0]); Assert.Equal(type.ContainingSymbol, constructedFrom.ContainingSymbol); Assert.Equal(type.TypeParameters[0], constructedFrom.TypeParameters[0]); Assert.False(constructedFrom.TypeArguments[0].IsErrorType()); Assert.NotEqual(type, constructedFrom); Assert.False(constructedFrom.IsUnboundGenericType); var a = type.ContainingType; Assert.Equal(constructedFrom, a.GetTypeMembers("B").Single()); Assert.NotEqual(type.TypeParameters[0], type.OriginalDefinition.TypeParameters[0]); // alpha renamed Assert.Null(type.BaseType); Assert.Empty(type.Interfaces); Assert.NotNull(constructedFrom.BaseType); Assert.Empty(type.GetMembers()); Assert.NotEmpty(constructedFrom.GetMembers()); Assert.True(a.IsUnboundGenericType); Assert.False(a.ConstructedFrom.IsUnboundGenericType); Assert.Equal(1, a.GetMembers().Length); } [WorkItem(528659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528659")] [Fact] public void AliasTypeName() { string sourceCode = @" using A = System.String; class Test { static void Main() { /*<bind>*/A/*</bind>*/ a = null; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal("A", aliasInfo.Name); Assert.Equal("A=System.String", aliasInfo.ToTestDisplayString()); } [WorkItem(542000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542000")] [Fact] public void AmbigAttributeBindWithoutAttributeSuffix() { string sourceCode = @" namespace Blue { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Red { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Green { using Blue; using Red; public class Test { [/*<bind>*/Description/*</bind>*/(null)] static void Main() { } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528669")] [Fact] public void AmbigAttributeBind1() { string sourceCode = @" namespace Blue { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Red { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Green { using Blue; using Red; public class Test { [/*<bind>*/DescriptionAttribute/*</bind>*/(null)] static void Main() { } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542205")] [Fact] public void IncompleteAttributeSymbolInfo() { string sourceCode = @" using System; class Program { [/*<bind>*/ObsoleteAttribute(x/*</bind>*/ static void Main(string[] args) { } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var sourceCode = @" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal(5, semanticInfo.ConstantValue); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void CircularConstantFieldInitializerExpression() { var sourceCode = @" public class C { const int x = /*<bind>*/x/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542017")] [Fact] public void AmbigAttributeBind2() { string sourceCode = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute { } [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [/*<bind>*/X/*</bind>*/] class Class1 { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); } [WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")] [Fact] public void AmbigAttributeBind3() { string sourceCode = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute { } [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [/*<bind>*/X/*</bind>*/] class Class1 { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); } [Fact] public void AmbigAttributeBind4() { string sourceCode = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_01 { using ValidWithSuffix; using ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("ValidWithSuffix.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind5() { string sourceCode = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_02 { using ValidWithSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.MethodGroup[0].ToDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind6() { string sourceCode = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_03 { using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.MethodGroup[0].ToDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind7() { string sourceCode = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_04 { using ValidWithSuffix; using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind8() { string sourceCode = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_05 { using InvalidWithSuffix; using InvalidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind9() { string sourceCode = @" namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_07 { using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("InvalidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact()] public void AliasAttributeName() { string sourceCode = @" using A = A1; class A1 : System.Attribute { } [/*<bind>*/A/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A1..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A1..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("A=A1", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact()] public void AliasAttributeName_02_AttributeSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact] public void AliasAttributeName_02_IdentifierNameSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact] public void AliasAttributeName_03_AttributeSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/GooAttribute/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact] public void AliasAttributeName_03_IdentifierNameSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/GooAttribute/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact()] public void AliasQualifiedAttributeName_01() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [global::/*<bind>*/AttributeClass/*</bind>*/.NonAttributeClass()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified"); } [Fact] public void AliasQualifiedAttributeName_02() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [/*<bind>*/global::AttributeClass/*</bind>*/.NonAttributeClass()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<AliasQualifiedNameSyntax>(sourceCode); Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified"); } [Fact] public void AliasQualifiedAttributeName_03() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [global::AttributeClass./*<bind>*/NonAttributeClass/*</bind>*/()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AliasQualifiedAttributeName_04() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [/*<bind>*/global::AttributeClass.NonAttributeClass/*</bind>*/()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AliasAttributeName_NonAttributeAlias() { string sourceCode = @" using GooAttribute = C; [/*<bind>*/GooAttribute/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AliasAttributeName_NonAttributeAlias_GenericType() { string sourceCode = @" using GooAttribute = Gen<int>; [/*<bind>*/GooAttribute/*</bind>*/] class C { } class Gen<T> { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Gen<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<System.Int32>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<System.Int32>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AmbigAliasAttributeName() { string sourceCode = @" using A = A1; using AAttribute = A2; class A1 : System.Attribute { } class A2 : System.Attribute { } [/*<bind>*/A/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A1", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("A2", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AmbigAliasAttributeName_02() { string sourceCode = @" using Goo = System.ObsoleteAttribute; class GooAttribute : System.Attribute { } [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("System.ObsoleteAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AmbigAliasAttributeName_03() { string sourceCode = @" using Goo = GooAttribute; class GooAttribute : System.Attribute { } [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("GooAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")] [Fact] public void AmbigObjectCreationBind() { string sourceCode = @" using System; public class X { } public struct X { } class Class1 { public static void Main() { object x = new /*<bind>*/X/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("X", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); } [WorkItem(542027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542027")] [Fact()] public void NonStaticMemberOfOuterTypeAccessedViaNestedType() { string sourceCode = @" class MyClass { public int intTest = 1; class TestClass { public void TestMeth() { int intI = /*<bind>*/ intTest /*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass.intTest", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")] [Fact()] public void ThisInFieldInitializer() { string sourceCode = @" class MyClass { public MyClass self = /*<bind>*/ this /*</bind>*/; }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("MyClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MyClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal(1, sortedCandidates.Length); Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")] [Fact()] public void BaseInFieldInitializer() { string sourceCode = @" class MyClass { public object self = /*<bind>*/ base /*</bind>*/ .Id(); object Id() { return this; } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(SymbolKind.Parameter, semanticInfo.CandidateSymbols[0].Kind); Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal(1, sortedCandidates.Length); Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact()] public void MemberAccessToInaccessibleField() { string sourceCode = @" class MyClass1 { private static int myInt1 = 12; } class MyClass2 { public int myInt2 = /*<bind>*/MyClass1.myInt1/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass1.myInt1", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528682")] [Fact] public void PropertyGetAccessWithPrivateGetter() { string sourceCode = @" public class MyClass { public int Property { private get { return 0; } set { } } } public class Test { public static void Main(string[] args) { MyClass c = new MyClass(); int a = c./*<bind>*/Property/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass.Property { private get; set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")] [Fact] public void GetAccessPrivateProperty() { string sourceCode = @" public class Test { class Class1 { private int a { get { return 1; } set { } } } class Class2 : Class1 { public int b() { return /*<bind>*/a/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.Class1.a { get; set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")] [Fact] public void GetAccessPrivateField() { string sourceCode = @" public class Test { class Class1 { private int a; } class Class2 : Class1 { public int b() { return /*<bind>*/a/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.Class1.a", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")] [Fact] public void GetAccessPrivateEvent() { string sourceCode = @" using System; public class Test { class Class1 { private event Action a; } class Class2 : Class1 { public Action b() { return /*<bind>*/a/*</bind>*/(); } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("event System.Action Test.Class1.a", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Event, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528684")] [Fact] public void PropertySetAccessWithPrivateSetter() { string sourceCode = @" public class MyClass { public int Property { get { return 0; } private set { } } } public class Test { static void Main() { MyClass c = new MyClass(); c./*<bind>*/Property/*</bind>*/ = 10; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass.Property { get; private set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void PropertyIndexerAccessWithPrivateSetter() { string sourceCode = @" public class MyClass { public object this[int index] { get { return null; } private set { } } } public class Test { static void Main() { MyClass c = new MyClass(); /*<bind>*/c[0]/*</bind>*/ = null; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Object MyClass.this[System.Int32 index] { get; private set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542065")] [Fact] public void GenericTypeWithNoTypeArgsOnAttribute() { string sourceCode = @" class Gen<T> { } [/*<bind>*/Gen/*</bind>*/] public class Test { public static int Main() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542125")] [Fact] public void MalformedSyntaxSemanticModel_Bug9223() { string sourceCode = @" public delegate int D(int x); public st C { public event D EV; public C(D d) { EV = /*<bind>*/d/*</bind>*/; } public int OnEV(int x) { return x; } } "; // Don't crash or assert. var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); } [WorkItem(528746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528746")] [Fact] public void ImplicitConversionArrayCreationExprInQuery() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q2 = from x in /*<bind>*/new int[] { 4, 5 }/*</bind>*/ select x; } } "; var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542256")] [Fact] public void MalformedConditionalExprInWhereClause() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { 4, 5 } where /*<bind>*/new Program()/*</bind>*/ ? select x; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo.Symbol); Assert.Equal("Program..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal("Program", semanticInfo.Type.Name); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact] public void MalformedExpressionInSelectClause() { string sourceCode = @" using System.Linq; class P { static void Main() { var src = new int[] { 4, 5 }; var q = from x in src select /*<bind>*/x/*</bind>*/."; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Symbol); } [WorkItem(542344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542344")] [Fact] public void LiteralExprInGotoCaseInsideSwitch() { string sourceCode = @" public class Test { public static void Main() { int ret = 6; switch (ret) { case 0: goto case /*<bind>*/2/*</bind>*/; case 2: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); Assert.Equal(2, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ImplicitConvCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { long number = 45; switch (number) { case /*<bind>*/21/*</bind>*/: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ErrorConvCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { double number = 45; switch (number) { case /*<bind>*/21/*</bind>*/: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ImplicitConvGotoCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { long number = 45; switch (number) { case 1: goto case /*<bind>*/21/*</bind>*/; case 21: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ErrorConvGotoCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { double number = 45; switch (number) { case 1: goto case /*<bind>*/21/*</bind>*/; case 21: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")] [Fact] public void AttributeSemanticInfo_OverloadResolutionFailure_01() { string sourceCode = @" [module: /*<bind>*/System.Obsolete(typeof(.<>))/*</bind>*/] "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo); } [WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")] [Fact] public void AttributeSemanticInfo_OverloadResolutionFailure_02() { string sourceCode = @" [module: System./*<bind>*/Obsolete/*</bind>*/(typeof(.<>))] "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo); } private void Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(CompilationUtils.SemanticInfoSummary semanticInfo) { Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")] [Fact] public void ObjectCreationSemanticInfo_OverloadResolutionFailure() { string sourceCode = @" using System; class Goo { public Goo() { } public Goo(int x) { } public static void Main() { var x = new /*<bind>*/Goo/*</bind>*/(typeof(.<>)); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Goo", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectCreationSemanticInfo_OverloadResolutionFailure_2() { string sourceCode = @" using System; class Goo { public Goo() { } public Goo(int x) { } public static void Main() { var x = /*<bind>*/new Goo(typeof(Goo))/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Goo..ctor(System.Int32 x)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Goo..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ParameterDefaultValue1() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; void f(long i = 32 + Constants./*<bind>*/k/*</bind>*/, long j = i) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int16 Constants.k", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal((short)9, semanticInfo.ConstantValue); } [Fact] public void ParameterDefaultValue2() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; void f(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(12, semanticInfo.ConstantValue); } [Fact] public void ParameterDefaultValueInConstructor() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; Class1(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(12, semanticInfo.ConstantValue); } [Fact] public void ParameterDefaultValueInIndexer() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; public string this[long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/] { get { return """"; } set { } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(12, semanticInfo.ConstantValue); } [WorkItem(542589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542589")] [Fact] public void UnrecognizedGenericTypeReference() { string sourceCode = "/*<bind>*/C<object, string/*</bind>*/"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = (INamedTypeSymbol)semanticInfo.Type; Assert.Equal("System.Boolean", type.ToTestDisplayString()); } [WorkItem(542452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542452")] [Fact] public void LambdaInSelectExpressionWithObjectCreation() { string sourceCode = @" using System; using System.Linq; using System.Collections.Generic; class Test { static void Main() { } static void Goo(List<int> Scores) { var z = from y in Scores select new Action(() => { /*<bind>*/var/*</bind>*/ x = y; }); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DefaultOptionalParamValue() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { const bool v = true; public void Goo(bool b = /*<bind>*/v == true/*</bind>*/) { } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Boolean.op_Equality(System.Boolean left, System.Boolean right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] public void DefaultOptionalParamValueWithGenericTypes() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void Goo<T, U>(T t = /*<bind>*/default(U)/*</bind>*/) where U : class, T { } static void Main(string[] args) { } } "; var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode); Assert.Equal("U", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind); Assert.Equal("T", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.TypeParameter, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [WorkItem(542850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542850")] [Fact] public void InaccessibleExtensionMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; public static class Extensions { private static int Goo(this string z) { return 3; } } class Program { static void Main(string[] args) { args[0]./*<bind>*/Goo/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 System.String.Goo()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 System.String.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542883")] [Fact] public void InaccessibleNamedAttrArg() { string sourceCode = @" using System; public class B : Attribute { private int X; } [B(/*<bind>*/X/*</bind>*/ = 5)] public class D { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 B.X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528914")] [Fact] public void InvalidIdentifierAsAttrArg() { string sourceCode = @" using System.Runtime.CompilerServices; public interface Interface1 { [/*<bind>*/IndexerName(null)/*</bind>*/] string this[int arg] { get; set; } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542890")] [Fact()] public void GlobalIdentifierName() { string sourceCode = @" class Test { static void Main() { var t1 = new /*<bind>*/global/*</bind>*/::Test(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.Equal("global", aliasInfo.Name); Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString()); Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace); Assert.False(aliasInfo.IsExtern); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact()] public void GlobalIdentifierName2() { string sourceCode = @" class Test { /*<bind>*/global/*</bind>*/::Test f; static void Main() { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.Equal("global", aliasInfo.Name); Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString()); Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace); Assert.False(aliasInfo.IsExtern); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542536")] [Fact] public void UndeclaredSymbolInDefaultParameterValue() { string sourceCode = @" class Program { const int y = 1; public void Goo(bool x = (undeclared == /*<bind>*/y/*</bind>*/)) { } static void Main(string[] args) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Program.y", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(543198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543198")] [Fact] public void NamespaceAliasInsideMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; using A = NS1; namespace NS1 { class B { } } class Program { class A { } A::B y = null; void Main() { /*<bind>*/A/*</bind>*/::B.Equals(null, null); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); // Should bind to namespace alias A=NS1, not class Program.A. Assert.Equal("NS1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_ImplicitArrayCreationSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public static int Main() { var a = /*<bind>*/new[] { 1, 2, 3 }/*</bind>*/; return a[0]; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_IdentifierNameSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public static int Main() { var a = new[] { 1, 2, 3 }; return /*<bind>*/a/*</bind>*/[0]; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32[] a", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_MultiDim_ImplicitArrayCreationSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public int[][, , ] Goo() { var a3 = new[] { /*<bind>*/new [,,] {{{1, 2}}}/*</bind>*/, new [,,] {{{3, 4}}} }; return a3; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[,,]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_MultiDim_IdentifierNameSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public int[][, , ] Goo() { var a3 = new[] { new [,,] {{{3, 4}}}, new [,,] {{{3, 4}}} }; return /*<bind>*/a3/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32[][,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[][,,]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32[][,,] a3", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_ImplicitArrayCreationSyntax() { string sourceCode = @" public class C { public int[] Goo() { char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = /*<bind>*/new[] { s1, s2, s3, s4, c, '1' }/*</bind>*/; // CS0826 return array1; } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_IdentifierNameSyntax() { string sourceCode = @" public class C { public int[] Goo() { char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826 return /*<bind>*/array1/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Equal("?[] array1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr() { string sourceCode = @" using System; namespace Test { public class Program { public int[][,,] Goo() { var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, 3, 4 }/*</bind>*/, new[,,] { { { 3, 4 } } } }; return a3; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr_02() { string sourceCode = @" using System; namespace Test { public class Program { public int[][,,] Goo() { var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, x, y }/*</bind>*/, new[,,] { { { 3, 4 } } } }; return a3; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Inside_ErrorImplicitArrayCreation() { string sourceCode = @" public class C { public int[] Goo() { char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { /*<bind>*/new[] { 1, 2 }/*</bind>*/, new[] { s1, s2, s3, s4, c, '1' } }; // CS0826 return array1; } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(543201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543201")] public void BindVariableIncompleteForLoop() { string sourceCode = @" class Program { static void Main() { for (int i = 0; /*<bind>*/i/*</bind>*/ } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); } [Fact, WorkItem(542843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542843")] public void Bug10245() { string sourceCode = @" class C<T> { public T Field; } class D { void M() { new C<int>./*<bind>*/Field/*</bind>*/.ToString(); } } "; var tree = Parse(sourceCode); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo.CandidateReason); Assert.Equal(1, symbolInfo.CandidateSymbols.Length); Assert.Equal("System.Int32 C<System.Int32>.Field", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Null(symbolInfo.Symbol); } [Fact] public void StaticClassWithinNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/Stat/*</bind>*/(); } } static class Stat { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("Stat", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.CandidateSymbols[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void StaticClassWithinNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new Stat()/*</bind>*/; } } static class Stat { } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Stat", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("Stat", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543534")] [Fact] public void InterfaceWithNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/X/*</bind>*/(); } } interface X { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InterfaceWithNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new X()/*</bind>*/; } } interface X { } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("X", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("X", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void TypeParameterWithNew() { string sourceCode = @" using System; class Program<T> { static void f() { object o = new /*<bind>*/T/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("T", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.TypeParameter, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void TypeParameterWithNew2() { string sourceCode = @" using System; class Program<T> { static void f() { object o = /*<bind>*/new T()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("T", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("T", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AbstractClassWithNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/X/*</bind>*/(); } } abstract class X { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MemberGroup.Length); } [Fact] public void AbstractClassWithNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new X()/*</bind>*/; } } abstract class X { } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("X", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MemberGroup.Length); } [Fact()] public void DynamicWithNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/dynamic/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("dynamic", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact()] public void DynamicWithNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new dynamic()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("dynamic", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_01() { // There must be exactly one user-defined conversion to a non-nullable integral type, // and there is. string sourceCode = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static int Main() { Conv C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 1; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitUserDefined, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Conv.implicit operator int(Conv)", semanticInfo.ImplicitConversion.Method.ToString()); Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_02() { // The specification requires that the user-defined conversion chosen be one // which converts to an integral or string type, but *not* a nullable integral type, // oddly enough. Since the only applicable user-defined conversion here would be the // lifted conversion from Conv? to int?, the resolution of the conversion fails // and this program produces an error. string sourceCode = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static int Main() { Conv? C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 1; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Conv?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Conv? C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_01() { string sourceCode = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator int? (Conv? C) { return null; } public static int Main() { Conv C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 0; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_02() { string sourceCode = @" struct Conv { public static int Main() { Conv C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 0; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_ObjectCreationExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/new MemberInitializerTest() { x = 1, y = 2 }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InitializerExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() /*<bind>*/{ x = 1, y = 2 }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_MemberInitializerAssignment_BinaryExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/x = 1/*</bind>*/, y = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_FieldAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/x/*</bind>*/ = 1, y = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_PropertyAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_TypeParameterBaseFieldAccess_IdentifierNameSyntax() { string sourceCode = @" public class Base { public Base() { } public int x; public int y { get; set; } public static void Main() { MemberInitializerTest<Base>.Goo(); } } public class MemberInitializerTest<T> where T : Base, new() { public static void Goo() { var i = new T() { /*<bind>*/x/*</bind>*/ = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Base.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_NestedInitializer_InitializerExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public readonly MemberInitializerTest m = new MemberInitializerTest(); public static void Main() { var i = new Test() { m = /*<bind>*/{ x = 1, y = 2 }/*</bind>*/ }; System.Console.WriteLine(i.m.x); System.Console.WriteLine(i.m.y); } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_NestedInitializer_PropertyAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public readonly MemberInitializerTest m = new MemberInitializerTest(); public static void Main() { var i = new Test() { m = { x = 1, /*<bind>*/y/*</bind>*/ = 2 } }; System.Console.WriteLine(i.m.x); System.Console.WriteLine(i.m.y); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InaccessibleMember_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { protected int x; private int y { get; set; } internal int z; } public class Test { public static void Main() { var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2, z = 3 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_ReadOnlyPropertyAssign_IdentifierNameSyntax() { string sourceCode = @" public struct MemberInitializerTest { public readonly int x; public int y { get { return 0; } } } public struct Test { public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/y/*</bind>*/ = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MemberInitializerTest.y { get; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_WriteOnlyPropertyAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public MemberInitializerTest m; public MemberInitializerTest Prop { set { m = value; } } public static void Main() { var i = new Test() { /*<bind>*/Prop/*</bind>*/ = { x = 1, y = 2 } }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MemberInitializerTest Test.Prop { set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_ErrorInitializerType_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public static void Main() { var i = new X() { /*<bind>*/x/*</bind>*/ = 0 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InvalidElementInitializer_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x, y; public static void Main() { var i = new MemberInitializerTest { x = 0, /*<bind>*/y/*</bind>*/++ }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.y", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InvalidElementInitializer_InvocationExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/}; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_01() { string sourceCode = @" public class MemberInitializerTest { public int x; public MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() }; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_02() { string sourceCode = @" public class MemberInitializerTest { public int x; public static MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() }; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_MethodGroupNamedAssignmentLeft_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/Goo/*</bind>*/ }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_DuplicateMemberInitializer_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public static void Main() { var i = new MemberInitializerTest() { x = 1, /*<bind>*/x/*</bind>*/ = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = /*<bind>*/new B { 1, i, { 4L }, { 9 }, 3L }/*</bind>*/; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("B..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("B..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InitializerExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B /*<bind>*/{ 1, i, { 4L }, { 9 }, 3L }/*</bind>*/; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ElementInitializer_LiteralExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { /*<bind>*/1/*</bind>*/, i, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [Fact] public void CollectionInitializer_ElementInitializer_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { 1, /*<bind>*/i/*</bind>*/, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ComplexElementInitializer_InitializerExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { 1, i, /*<bind>*/{ 4L }/*</bind>*/, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ComplexElementInitializer_Empty_InitializerExpressionSyntax() { string sourceCode = @" using System.Collections.Generic; public class MemberInitializerTest { public List<int> y; public static void Main() { i = new MemberInitializerTest { y = { /*<bind>*/{ }/*</bind>*/ } }; // CS1920 } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ComplexElementInitializer_AddMethodOverloadResolutionFailure() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { /*<bind>*/{ 1, 2 }/*</bind>*/ }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(float i, int j) { list.Add(i); list.Add(j); } public void Add(int i, float j) { list.Add(i); list.Add(j); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_Empty_InitializerExpressionSyntax() { string sourceCode = @" using System.Collections.Generic; public class MemberInitializerTest { public static void Main() { var i = new List<int>() /*<bind>*/{ }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_Nested_InitializerExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var coll = new List<B> { new B(0) { list = new List<int>() { 1, 2, 3 } }, new B(1) { list = /*<bind>*/{ 2, 3 }/*</bind>*/ } }; DisplayCollection(coll); return 0; } public static void DisplayCollection(IEnumerable<B> collection) { foreach (var i in collection) { i.Display(); } } } public class B { public List<int> list = new List<int>(); public B() { } public B(int i) { list.Add(i); } public void Display() { foreach (var i in list) { Console.WriteLine(i); } } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InitializerTypeNotIEnumerable_InitializerExpressionSyntax() { string sourceCode = @" class MemberInitializerTest { public static int Main() { B coll = new B /*<bind>*/{ 1 }/*</bind>*/; return 0; } } class B { public B() { } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InvalidInitializer_PostfixUnaryExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int y; public static void Main() { var i = new MemberInitializerTest { /*<bind>*/y++/*</bind>*/ }; } } "; var semanticInfo = GetSemanticInfoForTest<PostfixUnaryExpressionSyntax>(sourceCode); Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InvalidInitializer_BinaryExpressionSyntax() { string sourceCode = @" using System.Collections.Generic; public class MemberInitializerTest { public int x; static MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { int y = 0; var i = new List<int> { 1, /*<bind>*/Goo().x = 1/*</bind>*/}; } } "; var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SimpleNameWithGenericTypeInAttribute() { string sourceCode = @" class Gen<T> { } class Gen2<T> : System.Attribute { } [/*<bind>*/Gen/*</bind>*/] [Gen2] public class Test { public static int Main() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SimpleNameWithGenericTypeInAttribute_02() { string sourceCode = @" class Gen<T> { } class Gen2<T> : System.Attribute { } [Gen] [/*<bind>*/Gen2/*</bind>*/] public class Test { public static int Main() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Gen2<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen2<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen2<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen2<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_VarKeyword_LocalDeclaration() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /*<bind>*/var/*</bind>*/ rand = new Random(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_VarKeyword_FieldDeclaration() { string sourceCode = @" class Program { /*<bind>*/var/*</bind>*/ x = 1; } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_VarKeyword_MethodReturnType() { string sourceCode = @" class Program { /*<bind>*/var/*</bind>*/ Goo() {} } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_InterfaceCreation_With_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = new /*<bind>*/InterfaceType/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")] [Fact] public void SemanticInfo_InterfaceArrayCreation_With_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = new /*<bind>*/InterfaceType/*</bind>*/[] { }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = /*<bind>*/new InterfaceType()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("CoClassType..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")] [Fact] public void SemanticInfo_InterfaceArrayCreation_With_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = /*<bind>*/new InterfaceType[] { }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("InterfaceType[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class GenericCoClassType<T, U> : NonGenericInterfaceType { public GenericCoClassType(U x) { Console.WriteLine(x); } } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(GenericCoClassType<int, string>))] public interface NonGenericInterfaceType { } public class MainClass { public static int Main() { var a = new /*<bind>*/NonGenericInterfaceType/*</bind>*/(""string""); return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("NonGenericInterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class GenericCoClassType<T, U> : NonGenericInterfaceType { public GenericCoClassType(U x) { Console.WriteLine(x); } } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(GenericCoClassType<int, string>))] public interface NonGenericInterfaceType { } public class MainClass { public static int Main() { var a = /*<bind>*/new NonGenericInterfaceType(""string"")/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("NonGenericInterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("NonGenericInterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class Wrapper { private class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] public interface InterfaceType { } } public class MainClass { public static int Main() { var a = new Wrapper./*<bind>*/InterfaceType/*</bind>*/(); return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Wrapper.InterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class Wrapper { private class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] public interface InterfaceType { } } public class MainClass { public static int Main() { var a = /*<bind>*/new Wrapper.InterfaceType()/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Wrapper.InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("Wrapper.InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Wrapper.CoClassType..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("Wrapper.CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(int))] public interface InterfaceType { } public class MainClass { public static int Main() { var a = /*<bind>*/new InterfaceType()/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("InterfaceType", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax_2() { string sourceCode = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(int))] public interface InterfaceType { } public class MainClass { public static int Main() { var a = new /*<bind>*/InterfaceType/*</bind>*/(); return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InterfaceType", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543593")] [Fact] public void IncompletePropertyAccessStatement() { string sourceCode = @"class C { static void M() { var c = new { P = 0 }; /*<bind>*/c.P.Q/*</bind>*/ x; } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Symbol); } [WorkItem(544449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544449")] [Fact] public void IndexerAccessorWithSyntaxErrors() { string sourceCode = @"public abstract int this[int i] ( { /*<bind>*/get/*</bind>*/; set; }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Symbol); } [WorkItem(545040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545040")] [Fact] public void OmittedArraySizeExpressionSyntax() { string sourceCode = @" class A { public static void Main() { var arr = new int[5][ ]; } } "; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.First(); var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedArraySizeExpressionSyntax>().Last(); var model = compilation.GetSemanticModel(tree); var typeInfo = model.GetTypeInfo(node); // Ensure that this doesn't throw. Assert.NotEqual(default, typeInfo); } [WorkItem(11451, "DevDiv_Projects/Roslyn")] [Fact] public void InvalidNewInterface() { string sourceCode = @" using System; public class Program { static void Main(string[] args) { var c = new /*<bind>*/IFormattable/*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.IFormattable", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InvalidNewInterface2() { string sourceCode = @" using System; public class Program { static void Main(string[] args) { var c = /*<bind>*/new IFormattable()/*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("System.IFormattable", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("System.IFormattable", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("System.IFormattable", semanticInfo.CandidateSymbols.First().ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(545376, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545376")] [Fact] public void AssignExprInExternEvent() { string sourceCode = @" struct Class1 { public event EventHandler e2; extern public event EventHandler e1 = /*<bind>*/ e2 = new EventHandler(this, new EventArgs()) = null /*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); } [Fact, WorkItem(531416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531416")] public void VarEvent() { var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(@" event /*<bind>*/var/*</bind>*/ goo; "); Assert.True(((ITypeSymbol)semanticInfo.Type).IsErrorType()); } [WorkItem(546083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546083")] [Fact] public void GenericMethodAssignedToDelegateWithDeclErrors() { string sourceCode = @" delegate void D(void t); class C { void M<T>(T t) { } D d = /*<bind>*/M/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Utils.CheckSymbol(semanticInfo.CandidateSymbols.Single(), "void C.M<T>(T t)"); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Null(semanticInfo.Type); Utils.CheckSymbol(semanticInfo.ConvertedType, "D"); } [WorkItem(545992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545992")] [Fact] public void TestSemanticInfoForMembersOfCyclicBase() { string sourceCode = @" using System; using System.Collections; class B : C { } class C : B { static void Main() { } void Goo(int x) { /*<bind>*/(this).Goo(1)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void C.Goo(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(610975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610975")] [Fact] public void AttributeOnTypeParameterWithSameName() { string source = @" class C<[T(a: 1)]T> { } "; var comp = CreateCompilation(source); comp.GetParseDiagnostics().Verify(); // Syntactically correct. var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var argumentSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); var argumentNameSyntax = argumentSyntax.NameColon.Name; var info = model.GetSymbolInfo(argumentNameSyntax); } private void CommonTestParenthesizedMethodGroup(string sourceCode) { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal("void C.Goo()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] [WorkItem(576966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576966")] public void TestParenthesizedMethodGroup() { string sourceCode = @" class C { void Goo() { /*<bind>*/Goo/*</bind>*/(); } }"; CommonTestParenthesizedMethodGroup(sourceCode); sourceCode = @" class C { void Goo() { ((/*<bind>*/Goo/*</bind>*/))(); } }"; CommonTestParenthesizedMethodGroup(sourceCode); } [WorkItem(531549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531549")] [Fact()] public void Bug531549() { var sourceCode1 = @" class C1 { void Goo() { int x = 2; long? z = /*<bind>*/x/*</bind>*/; } }"; var sourceCode2 = @" class C2 { void Goo() { long? y = /*<bind>*/x/*</bind>*/; int x = 2; } }"; var compilation = CreateCompilation(new[] { sourceCode1, sourceCode2 }); for (int i = 0; i < 2; i++) { var tree = compilation.SyntaxTrees[i]; var model = compilation.GetSemanticModel(tree); IdentifierNameSyntax syntaxToBind = GetSyntaxNodeOfTypeForBinding<IdentifierNameSyntax>(GetSyntaxNodeList(tree)); var info1 = model.GetTypeInfo(syntaxToBind); Assert.NotEqual(default, info1); Assert.Equal("System.Int32", info1.Type.ToTestDisplayString()); } } [Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")] public void ObjectCreation1() { var compilation = CreateCompilation( @" using System.Collections; namespace Test { class C : IEnumerable { public int P1 { get; set; } public void Add(int x) { } public static void Main() { var x1 = new C(); var x2 = new C() {P1 = 1}; var x3 = new C() {1, 2}; } public static void Main2() { var x1 = new Test.C(); var x2 = new Test.C() {P1 = 1}; var x3 = new Test.C() {1, 2}; } public IEnumerator GetEnumerator() { return null; } } }"); compilation.VerifyDiagnostics(); SyntaxTree tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var nodes = (from node in tree.GetRoot().DescendantNodes() select (node as ObjectCreationExpressionSyntax)). Where(node => (object)node != null).ToArray(); for (int i = 0; i < 6; i++) { ObjectCreationExpressionSyntax creation = nodes[i]; SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type); Assert.Equal("Test.C", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var memberGroup = model.GetMemberGroup(creation.Type); Assert.Equal(0, memberGroup.Length); TypeInfo typeInfo = model.GetTypeInfo(creation.Type); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); var conv = model.GetConversion(creation.Type); Assert.True(conv.IsIdentity); symbolInfo = model.GetSymbolInfo(creation); Assert.Equal("Test.C..ctor()", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); memberGroup = model.GetMemberGroup(creation); Assert.Equal(1, memberGroup.Length); Assert.Equal("Test.C..ctor()", memberGroup[0].ToTestDisplayString()); typeInfo = model.GetTypeInfo(creation); Assert.Equal("Test.C", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Test.C", typeInfo.ConvertedType.ToTestDisplayString()); conv = model.GetConversion(creation); Assert.True(conv.IsIdentity); } } [Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")] public void ObjectCreation2() { var compilation = CreateCompilation( @" using System.Collections; namespace Test { public class CoClassI : I { public int P1 { get; set; } public void Add(int x) { } public IEnumerator GetEnumerator() { return null; } } [System.Runtime.InteropServices.ComImport, System.Runtime.InteropServices.CoClass(typeof(CoClassI))] [System.Runtime.InteropServices.Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public interface I : IEnumerable { int P1 { get; set; } void Add(int x); } class C { public static void Main() { var x1 = new I(); var x2 = new I() {P1 = 1}; var x3 = new I() {1, 2}; } public static void Main2() { var x1 = new Test.I(); var x2 = new Test.I() {P1 = 1}; var x3 = new Test.I() {1, 2}; } } } "); compilation.VerifyDiagnostics(); SyntaxTree tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var nodes = (from node in tree.GetRoot().DescendantNodes() select (node as ObjectCreationExpressionSyntax)). Where(node => (object)node != null).ToArray(); for (int i = 0; i < 6; i++) { ObjectCreationExpressionSyntax creation = nodes[i]; SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type); Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var memberGroup = model.GetMemberGroup(creation.Type); Assert.Equal(0, memberGroup.Length); TypeInfo typeInfo = model.GetTypeInfo(creation.Type); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); var conv = model.GetConversion(creation.Type); Assert.True(conv.IsIdentity); symbolInfo = model.GetSymbolInfo(creation); Assert.Equal("Test.CoClassI..ctor()", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); memberGroup = model.GetMemberGroup(creation); Assert.Equal(1, memberGroup.Length); Assert.Equal("Test.CoClassI..ctor()", memberGroup[0].ToTestDisplayString()); typeInfo = model.GetTypeInfo(creation); Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString()); conv = model.GetConversion(creation); Assert.True(conv.IsIdentity); } } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")] public void ObjectCreation3() { var pia = CreateCompilation( @" using System; using System.Collections; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] namespace Test { [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b5827A"")] public class CoClassI : I { public int P1 { get; set; } public void Add(int x) { } public IEnumerator GetEnumerator() { return null; } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [System.Runtime.InteropServices.CoClass(typeof(CoClassI))] public interface I : IEnumerable { int P1 { get; set; } void Add(int x); } } ", options: TestOptions.ReleaseDll); pia.VerifyDiagnostics(); var compilation = CreateCompilation( @" namespace Test { class C { public static void Main() { var x1 = new I(); var x2 = new I() {P1 = 1}; var x3 = new I() {1, 2}; } public static void Main2() { var x1 = new Test.I(); var x2 = new Test.I() {P1 = 1}; var x3 = new Test.I() {1, 2}; } } }", references: new[] { new CSharpCompilationReference(pia, embedInteropTypes: true) }); compilation.VerifyDiagnostics(); SyntaxTree tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var nodes = (from node in tree.GetRoot().DescendantNodes() select (node as ObjectCreationExpressionSyntax)). Where(node => (object)node != null).ToArray(); for (int i = 0; i < 6; i++) { ObjectCreationExpressionSyntax creation = nodes[i]; SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type); Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var memberGroup = model.GetMemberGroup(creation.Type); Assert.Equal(0, memberGroup.Length); TypeInfo typeInfo = model.GetTypeInfo(creation.Type); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); var conv = model.GetConversion(creation.Type); Assert.True(conv.IsIdentity); symbolInfo = model.GetSymbolInfo(creation); Assert.Null(symbolInfo.Symbol); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); memberGroup = model.GetMemberGroup(creation); Assert.Equal(0, memberGroup.Length); typeInfo = model.GetTypeInfo(creation); Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString()); conv = model.GetConversion(creation); Assert.True(conv.IsIdentity); } } /// <summary> /// SymbolInfo and TypeInfo should implement IEquatable&lt;T&gt;. /// </summary> [WorkItem(792647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792647")] [Fact] public void ImplementsIEquatable() { string sourceCode = @"class C { object F() { return this; } }"; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.First(); var expr = (ExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ThisKeyword).Parent; var model = compilation.GetSemanticModel(tree); var symbolInfo1 = model.GetSymbolInfo(expr); var symbolInfo2 = model.GetSymbolInfo(expr); var symbolComparer = (IEquatable<SymbolInfo>)symbolInfo1; Assert.True(symbolComparer.Equals(symbolInfo2)); var typeInfo1 = model.GetTypeInfo(expr); var typeInfo2 = model.GetTypeInfo(expr); var typeComparer = (IEquatable<TypeInfo>)typeInfo1; Assert.True(typeComparer.Equals(typeInfo2)); } [Fact] public void ConditionalAccessErr001() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = """"qqq"""" ?/*<bind>*/.ToString().Length/*</bind>*/.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccessErr002() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = ""qqq"" ?/*<bind>*/.ToString/*</bind>*/.Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberBindingExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("string.ToString()", sortedCandidates[0].ToDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("string.ToString(System.IFormatProvider)", sortedCandidates[1].ToDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("string.ToString()", sortedMethodGroup[0].ToDisplayString()); Assert.Equal("string.ToString(System.IFormatProvider)", sortedMethodGroup[1].ToDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess001() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = ""qqq"" ?/*<bind>*/.ToString()/*</bind>*/.Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("string", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("string", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.ToString()", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess002() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = ""qqq"" ?.ToString()./*<bind>*/Length/*</bind>*/.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess003() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString()./*<bind>*/Length/*</bind>*/?.ToString(); var dummy2 = ""qqq""?.ToString().Length.ToString(); var dummy3 = 1.ToString()?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess004() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString()./*<bind>*/Length/*</bind>*/ .ToString(); var dummy2 = ""qqq"" ?.ToString().Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess005() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString() ?/*<bind>*/[1]/*</bind>*/ .ToString(); var dummy2 = ""qqq"" ?.ToString().Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<ElementBindingExpressionSyntax>(sourceCode); Assert.Equal("char", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("char", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.this[int]", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(998050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998050")] public void Bug998050() { var comp = CreateCompilation(@" class BaselineLog {} public static BaselineLog Log { get { } }= new /*<bind>*/BaselineLog/*</bind>*/(); ", parseOptions: TestOptions.Regular); var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(comp); Assert.Null(semanticInfo.Type); Assert.Equal("BaselineLog", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(982479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/982479")] public void Bug982479() { const string sourceCode = @" class C { static void Main() { new C { Dynamic = { /*<bind>*/Name/*</bind>*/ = 1 } }; } public dynamic Dynamic; } class Name { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("dynamic", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind); Assert.Equal("dynamic", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Dynamic, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(1084693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084693")] public void Bug1084693() { const string sourceCode = @" using System; public class C { public Func<Func<C, C>, C> Select; public Func<Func<C, bool>, C> Where => null; public void M() { var e = from i in this where true select true?i:i; } }"; var compilation = CreateCompilation(sourceCode); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(tree); string[] expectedNames = { null, "Where", "Select" }; int i = 0; foreach (var qc in tree.GetRoot().DescendantNodes().OfType<QueryClauseSyntax>()) { var infoSymbol = semanticModel.GetQueryClauseInfo(qc).OperationInfo.Symbol; Assert.Equal(expectedNames[i++], infoSymbol?.Name); } var qe = tree.GetRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single(); var infoSymbol2 = semanticModel.GetSymbolInfo(qe.Body.SelectOrGroup).Symbol; Assert.Equal(expectedNames[i++], infoSymbol2.Name); } [Fact] public void TestIncompleteMember() { // Note: binding information in an incomplete member is not available. // When https://github.com/dotnet/roslyn/issues/7536 is fixed this test // will have to be updated. string sourceCode = @" using System; class Program { public /*<bind>*/K/*</bind>*/ } class K { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("K", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(18763, "https://github.com/dotnet/roslyn/issues/18763")] [Fact] public void AttributeArgumentLambdaThis() { string source = @"class C { [X(() => this._Y)] public void Z() { } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.ThisExpression); var info = model.GetSemanticInfoSummary(syntax); Assert.Equal("C", info.Type.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 System; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; // Note: the easiest way to create new unit tests that use GetSemanticInfo // is to use the SemanticInfo unit test generate in Editor Test App. namespace Microsoft.CodeAnalysis.CSharp.UnitTests { using Utils = CompilationUtils; public class SemanticModelGetSemanticInfoTests : SemanticModelTestBase { [Fact] public void FailedOverloadResolution() { string sourceCode = @" class Program { static void Main(string[] args) { int i = 8; int j = i + q; /*<bind>*/X.f/*</bind>*/(""hello""); } } class X { public static void f() { } public static void f(int i) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void X.f()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("void X.f(System.Int32 i)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void X.f()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void X.f(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SimpleGenericType() { string sourceCode = @" using System; class Program { /*<bind>*/K<int>/*</bind>*/ f; } class K<T> { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("K<System.Int32>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity1() { string sourceCode = @" using System; class Program { /*<bind>*/K<int, string>/*</bind>*/ f; } class K<T> { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity2() { string sourceCode = @" using System; class Program { /*<bind>*/K/*</bind>*/ f; } class K<T> { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity3() { string sourceCode = @" using System; class Program { static void Main() { /*<bind>*/K<int, int>/*</bind>*/.f(); } } class K<T> { void f() { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void WrongArity4() { string sourceCode = @" using System; class Program { static K Main() { /*<bind>*/K/*</bind>*/.f(); } } class K<T> { void f() { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NotInvocable() { string sourceCode = @" using System; class Program { static void Main() { K./*<bind>*/f/*</bind>*/(); } } class K { public int f; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotInvocable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleField() { string sourceCode = @" class Program { static void Main() { K./*<bind>*/f/*</bind>*/ = 3; } } class K { private int f; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 K.f", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleFieldAssignment() { string sourceCode = @"class A { string F; } class B { static void M(A a) { /*<bind>*/a.F/*</bind>*/ = string.Empty; } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); var symbol = semanticInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("System.String A.F", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, symbol.Kind); } [WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")] [Fact] public void InaccessibleBaseClassConstructor01() { string sourceCode = @" namespace Test { public class Base { protected Base() { } } public class Derived : Base { void M() { Base b = /*<bind>*/new Base()/*</bind>*/; } } }"; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Test.Base..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); } [WorkItem(542481, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542481")] [Fact] public void InaccessibleBaseClassConstructor02() { string sourceCode = @" namespace Test { public class Base { protected Base() { } } public class Derived : Base { void M() { Base b = new /*<bind>*/Base/*</bind>*/(); } } }"; var semanticInfo = GetSemanticInfoForTest<NameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal("Test.Base", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MemberGroup.Length); } [Fact] public void InaccessibleFieldMethodArg() { string sourceCode = @"class A { string F; } class B { static void M(A a) { M(/*<bind>*/a.F/*</bind>*/); } static void M(string s) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); var symbol = semanticInfo.Symbol; Assert.Null(symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("System.String A.F", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, symbol.Kind); } [Fact] public void TypeNotAVariable() { string sourceCode = @" using System; class Program { static void Main() { /*<bind>*/K/*</bind>*/ = 12; } } class K { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleType1() { string sourceCode = @" using System; class Program { static void Main() { /*<bind>*/K.J/*</bind>*/ = v; } } class K { protected class J { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("K.J", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguousTypesBetweenUsings1() { string sourceCode = @" using System; using N1; using N2; class Program { /*<bind>*/A/*</bind>*/ field; } namespace N1 { class A { } } namespace N2 { class A { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguousTypesBetweenUsings2() { string sourceCode = @" using System; using N1; using N2; class Program { void f() { /*<bind>*/A/*</bind>*/.g(); } } namespace N1 { class A { } } namespace N2 { class A { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("N1.A", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.A", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("N2.A", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguousTypesBetweenUsings3() { string sourceCode = @" using System; using N1; using N2; class Program { void f() { /*<bind>*/A<int>/*</bind>*/.g(); } } namespace N1 { class A<T> { } } namespace N2 { class A<U> { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.A<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("N1.A<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.A<T>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("N2.A<U>", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbiguityBetweenInterfaceMembers() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; interface I1 { public int P { get; } } interface I2 { public string P { get; } } interface I3 : I1, I2 { } public class Class1 { void f() { I3 x = null; int o = x./*<bind>*/P/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("I1.P", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 I1.P { get; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal("System.String I2.P { get; }", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Alias1() { string sourceCode = @" using O = System.Object; partial class A : /*<bind>*/O/*</bind>*/ {} "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Alias2() { string sourceCode = @" using O = System.Object; partial class A { void f() { /*<bind>*/O/*</bind>*/.ReferenceEquals(null, null); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal("O=System.Object", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(539002, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539002")] [Fact] public void IncompleteGenericMethodCall() { string sourceCode = @" class Array { public static void Find<T>(T t) { } } class C { static void Main() { /*<bind>*/Array.Find<int>/*</bind>*/( } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void Array.Find<System.Int32>(System.Int32 t)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void IncompleteExtensionMethodCall() { string sourceCode = @"interface I<T> { } class A { } class B : A { } class C { static void M(A a) { /*<bind>*/a.M/*</bind>*/( } } static class S { internal static void M(this object o, int x) { } internal static void M(this A a, int x, int y) { } internal static void M(this B b) { } internal static void M(this string s) { } internal static void M<T>(this T t, object o) { } internal static void M<T>(this T[] t) { } internal static void M<T, U>(this T x, I<T> y, U z) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup, "void object.M(int x)", "void A.M(int x, int y)", "void A.M<A>(object o)", "void A.M<A, U>(I<A> y, U z)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void object.M(int x)", "void A.M(int x, int y)", "void A.M<A>(object o)", "void A.M<A, U>(I<A> y, U z)"); Utils.CheckReducedExtensionMethod(semanticInfo.MethodGroup[3].GetSymbol(), "void A.M<A, U>(I<A> y, U z)", "void S.M<T, U>(T x, I<T> y, U z)", "void T.M<T, U>(I<T> y, U z)", "void S.M<T, U>(T x, I<T> y, U z)"); } [Fact] public void IncompleteExtensionMethodCallBadThisType() { string sourceCode = @"interface I<T> { } class B { static void M(I<A> a) { /*<bind>*/a.M/*</bind>*/( } } static class S { internal static void M(this object o) { } internal static void M<T>(this T t, object o) { } internal static void M<T>(this T[] t) { } internal static void M<T, U>(this I<T> x, I<T> y, U z) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Utils.CheckISymbols(semanticInfo.MethodGroup, "void object.M()", "void I<A>.M<I<A>>(object o)", "void I<A>.M<A, U>(I<A> y, U z)"); } [WorkItem(541141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541141")] [Fact] public void IncompleteGenericExtensionMethodCall() { string sourceCode = @"using System.Linq; class C { static void M(double[] a) { /*<bind>*/a.Where/*</bind>*/( } }"; var compilation = CreateCompilation(source: sourceCode); var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckISymbols(semanticInfo.MethodGroup, "IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, bool> predicate)", "IEnumerable<double> IEnumerable<double>.Where<double>(Func<double, int, bool> predicate)"); } [WorkItem(541349, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541349")] [Fact] public void GenericExtensionMethodCallExplicitTypeArgs() { string sourceCode = @"interface I<T> { } class C { static void M(object o) { /*<bind>*/o.E<int>/*</bind>*/(); } } static class S { internal static void E(this object x, object y) { } internal static void E<T>(this object o) { } internal static void E<T>(this object o, T t) { } internal static void E<T>(this I<T> t) { } internal static void E<T, U>(this I<T> t) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Utils.CheckSymbol(semanticInfo.Symbol, "void object.E<int>()"); Utils.CheckISymbols(semanticInfo.MethodGroup, "void object.E<int>()", "void object.E<int>(int t)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); } [Fact] public void GenericExtensionMethodCallExplicitTypeArgsOfT() { string sourceCode = @"interface I<T> { } class C { static void M<T, U>(T t, U u) { /*<bind>*/t.E<T, U>/*</bind>*/(u); } } static class S { internal static void E(this object x, object y) { } internal static void E<T>(this object o) { } internal static void E<T, U>(this T t, U u) { } internal static void E<T, U>(this I<T> t, U u) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Utils.CheckISymbols(semanticInfo.MethodGroup, "void T.E<T, U>(U u)"); } [WorkItem(541297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541297")] [Fact] public void GenericExtensionMethodCall() { // Single applicable overload with valid argument. var semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { /*<bind>*/s.E(s)/*</bind>*/; } } static class S { internal static void E<T>(this T x, object y) { } internal static void E<T, U>(this T x, U y) { } }"); Utils.CheckSymbol(semanticInfo.Symbol, "void string.E<string, string>(string y)"); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Multiple applicable overloads with valid arguments. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s, object o) { /*<bind>*/s.E(s, o)/*</bind>*/; } } static class S { internal static void E<T>(this object x, T y, object z) { } internal static void E<T, U>(this T x, object y, U z) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void object.E<string>(string y, object z)", "void string.E<string, object>(object y, object z)"); // Multiple applicable overloads with error argument. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { /*<bind>*/s.E(t, s)/*</bind>*/; } } static class S { internal static void E<T>(this T x, T y, object z) { } internal static void E<T, U>(this T x, string y, U z) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void string.E<string>(string y, object z)", "void string.E<string, string>(string y, string z)"); // Multiple overloads but all inaccessible. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { /*<bind>*/s.E()/*</bind>*/; } } static class S { static void E(this string x) { } static void E<T>(this T x) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols /* no candidates */ ); } [Fact] public void GenericExtensionDelegateMethod() { // Single applicable overload. var semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { System.Action<string> a = /*<bind>*/s.E/*</bind>*/; } } static class S { internal static void E<T>(this T x, T y) { } internal static void E<T>(this object x, T y) { } }"); Utils.CheckSymbol(semanticInfo.Symbol, "void string.E<string>(string y)"); Utils.CheckISymbols(semanticInfo.MethodGroup, "void string.E<string>(string y)", "void object.E<T>(T y)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Multiple applicable overloads. semanticInfo = GetSemanticInfoForTest( @"class C { static void M(string s) { System.Action<string> a = /*<bind>*/s.E/*</bind>*/; } } static class S { internal static void E<T>(this T x, T y) { } internal static void E<T, U>(this T x, U y) { } }"); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MethodGroup, "void string.E<string>(string y)", "void string.E<string, U>(U y)"); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "void string.E<string>(string y)", "void string.E<string, U>(U y)"); } /// <summary> /// Overloads from different scopes should /// be included in method group. /// </summary> [WorkItem(541890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541890")] [Fact] public void IncompleteExtensionOverloadedDifferentScopes() { // Instance methods and extension method (implicit instance). var sourceCode = @"class C { void M() { /*<bind>*/F/*</bind>*/( } void F(int x) { } void F(object x, object y) { } } static class E { internal static void F(this object x, object y) { } }"; var compilation = (Compilation)CreateCompilation(source: sourceCode); var type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); var symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)"); symbols = model.LookupSymbols(expr.SpanStart, container: null, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)", "void object.F(object y)"); // Instance methods and extension method (explicit instance). sourceCode = @"class C { void M() { /*<bind>*/this.F/*</bind>*/( } void F(int x) { } void F(object x, object y) { } } static class E { internal static void F(this object x, object y) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)", "void object.F(object y)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void C.F(object x, object y)", "void object.F(object y)"); // Applicable instance method and inapplicable extension method. sourceCode = @"class C { void M() { /*<bind>*/this.F<string>/*</bind>*/( } void F<T>(T t) { } } static class E { internal static void F(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F<string>(string t)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F<T>(T t)", "void object.F()"); // Inaccessible instance method and accessible extension method. sourceCode = @"class A { void F() { } } class B : A { static void M(A a) { /*<bind>*/a.F/*</bind>*/( } } static class E { internal static void F(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("A"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void object.F()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F()"); // Inapplicable instance method and applicable extension method. sourceCode = @"class C { void M() { /*<bind>*/this.F<string>/*</bind>*/( } void F(object o) { } } static class E { internal static void F<T>(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void object.F<string>()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(object o)", "void object.F<T>()"); // Viable instance and extension methods, binding to extension method. sourceCode = @"class C { void M() { /*<bind>*/this.F/*</bind>*/(); } void F(object o) { } } static class E { internal static void F(this object x) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(object o)", "void object.F()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(object o)", "void object.F()"); // Applicable and inaccessible extension methods. sourceCode = @"class C { void M(string s) { /*<bind>*/s.F<string>/*</bind>*/( } } static class E { internal static void F(this object x, object y) { } internal static void F<T>(this T t) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GetSpecialType(SpecialType.System_String); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void string.F<string>()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F(object y)", "void string.F<string>()"); // Inapplicable and inaccessible extension methods. sourceCode = @"class C { void M(string s) { /*<bind>*/s.F<string>/*</bind>*/( } } static class E { internal static void F(this object x, object y) { } private static void F<T>(this T t) { } }"; compilation = (Compilation)CreateCompilation(source: sourceCode); type = compilation.GetSpecialType(SpecialType.System_String); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void string.F<string>()"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F(object y)"); // Multiple scopes. sourceCode = @"namespace N1 { static class E { internal static void F(this object o) { } } } namespace N2 { using N1; class C { static void M(C c) { /*<bind>*/c.F/*</bind>*/( } void F(int x) { } } static class E { internal static void F(this object x, object y) { } } } static class E { internal static void F(this object x, object y, object z) { } }"; compilation = CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N2").GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void C.F(int x)", "void object.F(object y)", "void object.F()", "void object.F(object y, object z)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void C.F(int x)", "void object.F(object y)", "void object.F()", "void object.F(object y, object z)"); // Multiple scopes, no instance methods. sourceCode = @"namespace N { class C { static void M(C c) { /*<bind>*/c.F/*</bind>*/( } } static class E { internal static void F(this object x, object y) { } } } static class E { internal static void F(this object x, object y, object z) { } }"; compilation = CreateCompilation(source: sourceCode); type = compilation.GlobalNamespace.GetMember<INamespaceSymbol>("N").GetMember<INamedTypeSymbol>("C"); tree = compilation.SyntaxTrees.First(); model = compilation.GetSemanticModel(tree); expr = GetSyntaxNodeOfTypeForBinding<ExpressionSyntax>(GetSyntaxNodeList(tree)); symbols = model.GetMemberGroup(expr); Utils.CheckISymbols(symbols, "void object.F(object y)", "void object.F(object y, object z)"); symbols = model.LookupSymbols(expr.SpanStart, container: type, name: "F", includeReducedExtensionMethods: true); Utils.CheckISymbols(symbols, "void object.F(object y)", "void object.F(object y, object z)"); } [ClrOnlyFact] public void PropertyGroup() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Property P(Optional x As Integer = 0) As Object Get Return Nothing End Get Set End Set End Property Property P(x As Integer, y As Integer) As Integer Get Return Nothing End Get Set End Set End Property Property P(x As Integer, y As String) As String Get Return Nothing End Get Set End Set End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped); // Assignment (property group). var source2 = @"class B { static void M(A a) { /*<bind>*/a.P/*</bind>*/[1, null] = string.Empty; } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Assignment (property access). source2 = @"class B { static void M(A a) { /*<bind>*/a.P[1, null]/*</bind>*/ = string.Empty; } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.MemberGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Object initializer. source2 = @"class B { static A F = new A() { /*<bind>*/P/*</bind>*/ = 1 }; }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object A.P[int x = 0]"); Utils.CheckISymbols(semanticInfo.MemberGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Incomplete reference, overload resolution failure (property group). source2 = @"class B { static void M(A a) { var o = /*<bind>*/a.P/*</bind>*/[1, a } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); // Incomplete reference, overload resolution failure (property access). source2 = @"class B { static void M(A a) { var o = /*<bind>*/a.P[1, a/*</bind>*/ } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Assert.Null(semanticInfo.Symbol); Utils.CheckISymbols(semanticInfo.MemberGroup); Utils.CheckISymbols(semanticInfo.CandidateSymbols, "object A.P[int x = 0]", "int A.P[int x, int y]", "string A.P[int x, string y]"); } [ClrOnlyFact] public void PropertyGroupOverloadsOverridesHides() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Overridable ReadOnly Property P1(index As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P2(index As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P2(x As Object, y As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P3(index As Object) As Object Get Return Nothing End Get End Property ReadOnly Property P3(x As Object, y As Object) As Object Get Return Nothing End Get End Property End Class <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E212"")> Public Class B Inherits A Overrides ReadOnly Property P1(index As Object) As Object Get Return Nothing End Get End Property Shadows ReadOnly Property P2(index As String) As Object Get Return Nothing End Get End Property End Class"; var reference1 = BasicCompilationUtils.CompileToMetadata(source1, verify: Verification.Skipped); // Overridden property. var source2 = @"class C { static object F(B b) { return /*<bind>*/b.P1/*</bind>*/[null]; } }"; var compilation = CreateCompilation(source2, new[] { reference1 }); var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object B.P1[object index]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P1[object index]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Hidden property. source2 = @"class C { static object F(B b) { return /*<bind>*/b.P2/*</bind>*/[null]; } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object B.P2[string index]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object B.P2[string index]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); // Overloaded property. source2 = @"class C { static object F(B b) { return /*<bind>*/b.P3/*</bind>*/[null]; } }"; compilation = CreateCompilation(source2, new[] { reference1 }); semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(compilation); Utils.CheckSymbol(semanticInfo.Symbol, "object A.P3[object index]"); Utils.CheckISymbols(semanticInfo.MemberGroup, "object A.P3[object index]", "object A.P3[object x, object y]"); Utils.CheckISymbols(semanticInfo.CandidateSymbols); } [WorkItem(538859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538859")] [Fact] public void ThisExpression() { string sourceCode = @" class C { void M() { /*<bind>*/this/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C this", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538143, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538143")] [Fact] public void GetSemanticInfoOfNull() { var compilation = CreateCompilation(""); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetConstantValue((ExpressionSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetSymbolInfo((ConstructorInitializerSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetTypeInfo((ConstructorInitializerSyntax)null)); Assert.Throws<ArgumentNullException>(() => model.GetMemberGroup((ConstructorInitializerSyntax)null)); } [WorkItem(537860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537860")] [Fact] public void UsingNamespaceName() { string sourceCode = @" using /*<bind>*/System/*</bind>*/; class Test { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3017, "DevDiv_Projects/Roslyn")] [Fact] public void VariableUsedInForInit() { string sourceCode = @" class Test { void Fill() { for (int i = 0; /*<bind>*/i/*</bind>*/ < 10 ; i++ ) { } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527269, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527269")] [Fact] public void NullLiteral() { string sourceCode = @" class Test { public static void Main() { string s = /*<bind>*/null/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [WorkItem(3019, "DevDiv_Projects/Roslyn")] [Fact] public void PostfixIncrement() { string sourceCode = @" class Test { public static void Main() { int i = 10; /*<bind>*/i++/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 System.Int32.op_Increment(System.Int32 value)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3199, "DevDiv_Projects/Roslyn")] [Fact] public void ConditionalOrExpr() { string sourceCode = @" class Program { static void T1() { bool result = /*<bind>*/true || true/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [WorkItem(3222, "DevDiv_Projects/Roslyn")] [Fact] public void ConditionalOperExpr() { string sourceCode = @" class Program { static void Main() { int i = /*<bind>*/(true ? 0 : 1)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(0, semanticInfo.ConstantValue); } [WorkItem(3223, "DevDiv_Projects/Roslyn")] [Fact] public void DefaultValueExpr() { string sourceCode = @" class Test { static void Main(string[] args) { int s = /*<bind>*/default(int)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(0, semanticInfo.ConstantValue); } [WorkItem(537979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537979")] [Fact] public void StringConcatWithInt() { string sourceCode = @" public class Test { public static void Main(string[] args) { string str = /*<bind>*/""Count value is: "" + 5/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3226, "DevDiv_Projects/Roslyn")] [Fact] public void StringConcatWithIntAndNullableInt() { string sourceCode = @" public class Test { public static void Main(string[] args) { string str = /*<bind>*/""Count value is: "" + (int?) 10 + 5/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String System.String.op_Addition(System.String left, System.Object right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3234, "DevDiv_Projects/Roslyn")] [Fact] public void AsOper() { string sourceCode = @" public class Test { public static void Main(string[] args) { object o = null; string str = /*<bind>*/o as string/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537983")] [Fact] public void AddWithUIntAndInt() { string sourceCode = @" public class Test { public static void Main(string[] args) { uint ui = 0; ulong ui2 = /*<bind>*/ui + 5/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.UInt32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.UInt64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.UInt32 System.UInt32.op_Addition(System.UInt32 left, System.UInt32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527314")] [Fact()] public void AddExprWithNullableUInt64AndInt32() { string sourceCode = @" public class Test { public static void Main(string[] args) { ulong? ui = 0; ulong? ui2 = /*<bind>*/ui + 5/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.UInt64?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.UInt64?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("ulong.operator +(ulong, ulong)", semanticInfo.Symbol.ToString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3248, "DevDiv_Projects/Roslyn")] [Fact] public void NegatedIsExpr() { string sourceCode = @" using System; public class Test { public static void Main() { Exception e = new Exception(); bool bl = /*<bind>*/!(e is DivideByZeroException)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Boolean.op_LogicalNot(System.Boolean value)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3249, "DevDiv_Projects/Roslyn")] [Fact] public void IsExpr() { string sourceCode = @" using System; public class Test { public static void Main() { Exception e = new Exception(); bool bl = /*<bind>*/ (e is DivideByZeroException) /*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527324")] [Fact] public void ExceptionCatchVariable() { string sourceCode = @" using System; public class Test { public static void Main() { try { } catch (Exception e) { bool bl = (/*<bind>*/e/*</bind>*/ is DivideByZeroException) ; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Exception", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Exception", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Exception e", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3478, "DevDiv_Projects/Roslyn")] [Fact] public void GenericInvocation() { string sourceCode = @" class Program { public static void Ref<T>(T array) { } static void Main() { /*<bind>*/Ref<object>(null)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void Program.Ref<System.Object>(System.Object array)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538039, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538039")] [Fact] public void GlobalAliasQualifiedName() { string sourceCode = @" namespace N1 { interface I1 { void Method(); } } namespace N2 { class Test : N1.I1 { void /*<bind>*/global::N1.I1/*</bind>*/.Method() { } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.I1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("N1.I1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.I1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527363, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527363")] [Fact] public void ArrayInitializer() { string sourceCode = @" class Test { static void Main() { int[] arr = new int[] /*<bind>*/{5}/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538041, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538041")] [Fact] public void AliasQualifiedName() { string sourceCode = @" using NSA = A; namespace A { class Goo {} } namespace B { class Test { class NSA { } static void Main() { /*<bind>*/NSA::Goo/*</bind>*/ goo = new NSA::Goo(); } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A.Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A.Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A.Goo", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538021, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538021")] [Fact] public void EnumToStringInvocationExpr() { string sourceCode = @" using System; enum E { Red, Blue, Green} public class MainClass { public static int Main () { E e = E.Red; string s = /*<bind>*/e.ToString()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String System.Enum.ToString()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538026")] [Fact] public void ExplIfaceMethInvocationExpr() { string sourceCode = @" namespace N1 { interface I1 { int Method(); } } namespace N2 { class Test : N1.I1 { int N1.I1.Method() { return 5; } static int Main() { Test t = new Test(); if (/*<bind>*/((N1.I1)t).Method()/*</bind>*/ != 5) return 1; return 0; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 N1.I1.Method()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538027")] [Fact] public void InvocExprWithAliasIdentifierNameSameAsType() { string sourceCode = @" using N1 = NGoo; namespace NGoo { class Goo { public static void method() { } } } namespace N2 { class N1 { } class Test { static void Main() { /*<bind>*/N1::Goo.method()/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void NGoo.Goo.method()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3498, "DevDiv_Projects/Roslyn")] [Fact] public void BaseAccessMethodInvocExpr() { string sourceCode = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { /*<bind>*/base.MyMeth()/*</bind>*/; } public static void Main() { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void BaseClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")] [Fact] public void OverloadResolutionForVirtualMethods() { string sourceCode = @" using System; class Program { static void Main() { D d = new D(); string s = ""hello""; long l = 1; /*<bind>*/d.goo(ref s, l, l)/*</bind>*/; } } public class B { // Should bind to this method. public virtual int goo(ref string x, long y, long z) { Console.WriteLine(""Base: goo(ref string x, long y, long z)""); return 0; } public virtual void goo(ref string x, params long[] y) { Console.WriteLine(""Base: goo(ref string x, params long[] y)""); } } public class D: B { // Roslyn erroneously binds to this override. // Roslyn binds to the correct method above if you comment out this override. public override void goo(ref string x, params long[] y) { Console.WriteLine(""Derived: goo(ref string x, params long[] y)""); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 B.goo(ref System.String x, System.Int64 y, System.Int64 z)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538104")] [Fact] public void OverloadResolutionForVirtualMethods2() { string sourceCode = @" using System; class Program { static void Main() { D d = new D(); int i = 1; /*<bind>*/d.goo(i, i)/*</bind>*/; } } public class B { public virtual int goo(params int[] x) { Console.WriteLine(""""Base: goo(params int[] x)""""); return 0; } public virtual void goo(params object[] x) { Console.WriteLine(""""Base: goo(params object[] x)""""); } } public class D: B { public override void goo(params object[] x) { Console.WriteLine(""""Derived: goo(params object[] x)""""); } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 B.goo(params System.Int32[] x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ThisInStaticMethod() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/this/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("Program", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("Program this", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Constructor1() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/A/*</bind>*/(4); } } class A { public A() { } public A(int x) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void Constructor2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new A(4)/*</bind>*/; } } class A { public A() { } public A(int x) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("A..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void FailedOverloadResolution1() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; /*<bind>*/A.f(o)/*</bind>*/; } } class A { public void f(int x, int y) { } public void f(string z) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void FailedOverloadResolution2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; A./*<bind>*/f/*</bind>*/(o); } } class A { public void f(int x, int y) { } public void f(string z) { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("void A.f(System.String z)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void A.f(System.String z)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541745")] [Fact] public void FailedOverloadResolution3() { string sourceCode = @" class C { public int M { get; set; } } static class Extensions1 { public static int M(this C c) { return 0; } } static class Extensions2 { public static int M(this C c) { return 0; } } class Goo { void M() { C c = new C(); /*<bind>*/c.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("System.Int32 C.M()", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.Int32 C.M()", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542833")] [Fact] public void FailedOverloadResolution4() { string sourceCode = @" class C { public int M; } static class Extensions { public static int M(this C c, int i) { return 0; } } class Goo { void M() { C c = new C(); /*<bind>*/c.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SucceededOverloadResolution1() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; /*<bind>*/A.f(""hi"")/*</bind>*/; } } class A { public static void f(int x, int y) { } public static int f(string z) { return 3; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SucceededOverloadResolution2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = null; A./*<bind>*/f/*</bind>*/(""hi""); } } class A { public static void f(int x, int y) { } public static int f(string z) { return 3; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 A.f(System.String z)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 A.f(System.String z)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void A.f(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541878")] [Fact] public void TestCandidateReasonForInaccessibleMethod() { string sourceCode = @" class Test { class NestedTest { static void Method1() { } } static void Main() { /*<bind>*/NestedTest.Method1()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void Test.NestedTest.Method1()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); } [WorkItem(541879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541879")] [Fact] public void InaccessibleTypeInObjectCreationExpression() { string sourceCode = @" class Test { class NestedTest { class NestedNestedTest { } } static void Main() { var nnt = /*<bind>*/new NestedTest.NestedNestedTest()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Test.NestedTest.NestedNestedTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Test.NestedTest.NestedNestedTest..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); } [WorkItem(541883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541883")] [Fact] public void InheritedMemberHiding() { string sourceCode = @" public class A { public static int m() { return 1; } } public class B : A { public static int m() { return 5; } public static void Main1() { /*<bind>*/m/*</bind>*/(10); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 B.m()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 B.m()", sortedMethodGroup[0].ToTestDisplayString()); } [WorkItem(538106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538106")] [Fact] public void UsingAliasNameSystemInvocExpr() { string sourceCode = @" using System = MySystem.IO.StreamReader; namespace N1 { using NullStreamReader = System::NullStreamReader; class Test { static int Main() { NullStreamReader nr = new NullStreamReader(); /*<bind>*/nr.ReadLine()/*</bind>*/; return 0; } } } namespace MySystem { namespace IO { namespace StreamReader { public class NullStreamReader { public string ReadLine() { return null; } } } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String MySystem.IO.StreamReader.NullStreamReader.ReadLine()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538109")] [Fact] public void InterfaceMethodImplInvocExpr() { string sourceCode = @" interface ISomething { string ToString(); } class A : ISomething { string ISomething.ToString() { return null; } } class Test { static void Main() { ISomething isome = new A(); /*<bind>*/isome.ToString()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String ISomething.ToString()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538112")] [Fact] public void MemberAccessMethodWithNew() { string sourceCode = @" public class MyBase { public void MyMeth() { } } public class MyClass : MyBase { new public void MyMeth() { } public static void Main() { MyClass test = new MyClass(); /*<bind>*/test.MyMeth/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void MyClass.MyMeth()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void MyClass.MyMeth()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527386")] [Fact] public void MethodGroupWithStaticInstanceSameName() { string sourceCode = @" class D { public static void M2(int x, int y) { } public void M2(int x) { } } class C { public static void Main() { D d = new D(); /*<bind>*/d.M2/*</bind>*/(5); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void D.M2(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void D.M2(System.Int32 x)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void D.M2(System.Int32 x, System.Int32 y)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538123")] [Fact] public void VirtualOverriddenMember() { string sourceCode = @" public class C1 { public virtual void M1() { } } public class C2:C1 { public override void M1() { } } public class Test { static void Main() { C2 c2 = new C2(); /*<bind>*/c2.M1/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void C2.M1()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C2.M1()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538125")] [Fact] public void AbstractOverriddenMember() { string sourceCode = @" public abstract class AbsClass { public abstract void Test(); } public class TestClass : AbsClass { public override void Test() { } public static void Main() { TestClass tc = new TestClass(); /*<bind>*/tc.Test/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void TestClass.Test()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void TestClass.Test()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DiamondInheritanceMember() { string sourceCode = @" public interface IB { void M(); } public interface IM1 : IB {} public interface IM2 : IB {} public interface ID : IM1, IM2 {} public class Program { public static void Main() { ID id = null; /*<bind>*/id.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); // We must ensure that the method is only found once, even though there are two paths to it. Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void IB.M()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void IB.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InconsistentlyHiddenMember() { string sourceCode = @" public interface IB { void M(); } public interface IL : IB {} public interface IR : IB { new void M(); } public interface ID : IR, IL {} public class Program { public static void Main() { ID id = null; /*<bind>*/id.M/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); // Even though there is a "path" from ID to IB.M via IL on which IB.M is not hidden, // it is still hidden because *any possible hiding* hides the method. Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void IR.M()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void IR.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538138")] [Fact] public void ParenExprWithMethodInvocExpr() { string sourceCode = @" class Test { public static int Meth1() { return 9; } public static void Main() { int var1 = /*<bind>*/(Meth1())/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Test.Meth1()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(527397, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527397")] [Fact()] public void ExplicitIdentityCastExpr() { string sourceCode = @" class Test { public static void Main() { int i = 10; object j = /*<bind>*/(int)i/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(3652, "DevDiv_Projects/Roslyn")] [WorkItem(529056, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529056")] [WorkItem(543619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543619")] [Fact()] public void OutOfBoundsConstCastToByte() { string sourceCode = @" class Test { public static void Main() { byte j = unchecked(/*<bind>*/(byte)-123/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Byte", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal((byte)133, semanticInfo.ConstantValue); } [WorkItem(538160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538160")] [Fact] public void InsideCollectionsNamespace() { string sourceCode = @" using System; namespace Collections { public class Test { public static /*<bind>*/void/*</bind>*/ Main() { } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Void", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538161")] [Fact] public void ErrorTypeNameSameAsVariable() { string sourceCode = @" public class A { public static void RunTest() { /*<bind>*/B/*</bind>*/ B = new B(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotATypeOrNamespace, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("B B", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Local, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537117, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537117")] [WorkItem(537127, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537127")] [Fact] public void SystemNamespace() { string sourceCode = @" namespace System { class A { /*<bind>*/System/*</bind>*/.Exception c; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537118")] [Fact] public void SystemNamespace2() { string sourceCode = @" namespace N1 { namespace N2 { public class A1 { } } public class A2 { /*<bind>*/N1.N2.A1/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.N2.A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.N2.A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.N2.A1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537119")] [Fact] public void SystemNamespace3() { string sourceCode = @" class H<T> { } class A { } namespace N1 { public class A1 { /*<bind>*/H<A>/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("H<A>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("H<A>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("H<A>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537124, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537124")] [Fact] public void SystemNamespace4() { string sourceCode = @" using System; class H<T> { } class H<T1, T2> { } class A { } namespace N1 { public class A1 { /*<bind>*/H<H<A>, H<A>>/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("H<H<A>, H<A>>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("H<H<A>, H<A>>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("H<H<A>, H<A>>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537160")] [Fact] public void SystemNamespace5() { string sourceCode = @" namespace N1 { namespace N2 { public class A2 { public class A1 { } /*<bind>*/N1.N2.A2.A1/*</bind>*/ a; } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.N2.A2.A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.N2.A2.A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.N2.A2.A1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537161")] [Fact] public void SystemNamespace6() { string sourceCode = @" namespace N1 { class NC1 { public class A1 { } } public class A2 { /*<bind>*/N1.NC1.A1/*</bind>*/ a; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("N1.NC1.A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.NC1.A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.NC1.A1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537340")] [Fact] public void LeftOfDottedTypeName() { string sourceCode = @" class Main { A./*<bind>*/B/*</bind>*/ x; // this refers to the B within A. } class A { public class B {} } class B {} "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A.B", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537592, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537592")] [Fact] public void Parameters() { string sourceCode = @" class C { void M(DateTime dt) { /*<bind>*/dt/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("DateTime", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("DateTime", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("DateTime dt", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } // TODO: This should probably have a candidate symbol! [WorkItem(527212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527212")] [Fact] public void FieldMemberOfConstructedType() { string sourceCode = @" class C<T> { public T Field; } class D { void M() { new C<int>./*<bind>*/Field/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C<System.Int32>.Field", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("C<System.Int32>.Field", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); // Should bind to "field" with a candidateReason (not a typeornamespace>) Assert.NotEqual(CandidateReason.None, semanticInfo.CandidateReason); Assert.NotEqual(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(537593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537593")] [Fact] public void Constructor() { string sourceCode = @" class C { public C() { /*<bind>*/new C()/*</bind>*/.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538046")] [Fact] public void TypeNameInTypeThatMatchesNamespace() { string sourceCode = @" namespace T { class T { void M() { /*<bind>*/T/*</bind>*/.T T = new T.T(); } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("T.T", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("T.T", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("T.T", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538267")] [Fact] public void RHSExpressionInTryParent() { string sourceCode = @" using System; public class Test { static int Main() { try { object obj = /*<bind>*/null/*</bind>*/; } catch {} return 0; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")] [Fact] public void GenericArgumentInBase1() { string sourceCode = @" public class X { public interface Z { } } class A<T> { public class X { } } class B : A<B.Y./*<bind>*/Z/*</bind>*/> { public class Y : X { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("B.Y.Z", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("B.Y.Z", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538215")] [Fact] public void GenericArgumentInBase2() { string sourceCode = @" public class X { public interface Z { } } class A<T> { public class X { } } class B : /*<bind>*/A<B.Y.Z>/*</bind>*/ { public class Y : X { } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("A<B.Y.Z>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A<B.Y.Z>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A<B.Y.Z>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538097")] [Fact] public void InvokedLocal1() { string sourceCode = @" class C { static void Goo() { int x = 10; /*<bind>*/x/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538318, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538318")] [Fact] public void TooManyConstructorArgs() { string sourceCode = @" class C { C() {} void M() { /*<bind>*/new C(null /*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("C..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(538185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538185")] [Fact] public void NamespaceAndFieldSameName1() { string sourceCode = @" class C { void M() { /*<bind>*/System/*</bind>*/.String x = F(); } string F() { return null; } public int System; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void PEProperty() { string sourceCode = @" class C { void M(string s) { /*<bind>*/s.Length/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 System.String.Length { get; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NotPresentGenericType1() { string sourceCode = @" class Class { void Test() { /*<bind>*/List<int>/*</bind>*/ l; } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NotPresentGenericType2() { string sourceCode = @" class Class { /*<bind>*/List<int>/*</bind>*/ Test() { return null;} } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("List<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("List<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BadArityConstructorCall() { string sourceCode = @" class C<T1> { public void Test() { C c = new /*<bind>*/C/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.WrongArity, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C<T1>", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BadArityConstructorCall2() { string sourceCode = @" class C<T1> { public void Test() { C c = /*<bind>*/new C()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("C<T1>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C<T1>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C<T1>..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C<T1>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void UnresolvedBaseConstructor() { string sourceCode = @" class C : B { public C(int i) /*<bind>*/: base(i)/*</bind>*/ { } public C(string j, string k) : base() { } } class B { public B(string a, string b) { } public B() { } int i; } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("B..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("B..ctor(System.String a, System.String b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BoundBaseConstructor() { string sourceCode = @" class C : B { public C(int i) /*<bind>*/: base(""hi"", ""hello"")/*</bind>*/ { } public C(string j, string k) : base() { } } class B { public B(string a, string b) { } public B() { } int i; } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("B..ctor(System.String a, System.String b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540998, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540998")] [Fact] public void DeclarationWithinSwitchStatement() { string sourceCode = @"class C { static void M(int i) { switch (i) { case 0: string name = /*<bind>*/null/*</bind>*/; if (name != null) { } break; } } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.NotNull(semanticInfo); } [WorkItem(537573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537573")] [Fact] public void UndeclaredTypeAndCheckContainingSymbol() { string sourceCode = @" class C1 { void M() { /*<bind>*/F/*</bind>*/ f; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("F", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("F", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.Equal(SymbolKind.Namespace, semanticInfo.Type.ContainingSymbol.Kind); Assert.True(((INamespaceSymbol)semanticInfo.Type.ContainingSymbol).IsGlobalNamespace); } [WorkItem(538538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538538")] [Fact] public void AliasQualifier() { string sourceCode = @" using X = A; namespace A.B { } namespace N { using /*<bind>*/X/*</bind>*/::B; class X { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal("A", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("X=A", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AliasQualifier2() { string sourceCode = @" using S = System.String; { class X { void Goo() { string x; x = /*<bind>*/S/*</bind>*/.Empty; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Equal("S=System.String", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal("String", aliasInfo.Target.Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void PropertyAccessor() { string sourceCode = @" class C { private object p = null; internal object P { set { p = /*<bind>*/value/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Object value", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void IndexerAccessorValue() { string sourceCode = @"class C { string[] values = new string[10]; internal string this[int i] { get { return values[i]; } set { values[i] = /*<bind>*/value/*</bind>*/; } } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("System.String value", semanticInfo.Symbol.ToTestDisplayString()); } [Fact] public void IndexerAccessorParameter() { string sourceCode = @"class C { string[] values = new string[10]; internal string this[short i] { get { return values[/*<bind>*/i/*</bind>*/]; } } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("System.Int16 i", semanticInfo.Symbol.ToTestDisplayString()); } [Fact] public void IndexerAccessNamedParameter() { string sourceCode = @"class C { string[] values = new string[10]; internal string this[short i] { get { return values[i]; } } void Method() { string s = this[/*<bind>*/i/*</bind>*/: 0]; } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); var symbol = semanticInfo.Symbol; Assert.Equal(SymbolKind.Parameter, symbol.Kind); Assert.True(symbol.ContainingSymbol.Kind == SymbolKind.Property && ((IPropertySymbol)symbol.ContainingSymbol).IsIndexer); Assert.Equal("System.Int16 i", symbol.ToTestDisplayString()); } [Fact] public void LocalConstant() { string sourceCode = @" class C { static void M() { const int i = 1; const int j = i + 1; const int k = /*<bind>*/j/*</bind>*/ - 2; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 j", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2, semanticInfo.ConstantValue); var symbol = (ILocalSymbol)semanticInfo.Symbol; Assert.True(symbol.HasConstantValue); Assert.Equal(2, symbol.ConstantValue); } [Fact] public void FieldConstant() { string sourceCode = @" class C { const int i = 1; const int j = i + 1; static void M() { const int k = /*<bind>*/j/*</bind>*/ - 2; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.j", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2, semanticInfo.ConstantValue); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.Equal("j", symbol.Name); Assert.True(symbol.HasConstantValue); Assert.Equal(2, symbol.ConstantValue); } [Fact] public void FieldInitializer() { string sourceCode = @" class C { int F = /*<bind>*/G() + 1/*</bind>*/; static int G() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void EnumConstant() { string sourceCode = @" enum E { A, B, C, D = B } class C { static void M(E e) { M(/*<bind>*/E.C/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2, semanticInfo.ConstantValue); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("C", symbol.Name); Assert.True(symbol.HasConstantValue); Assert.Equal(2, symbol.ConstantValue); } [Fact] public void BadEnumConstant() { string sourceCode = @" enum E { W = Z, X, Y } class C { static void M(E e) { M(/*<bind>*/E.Y/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.Y", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("Y", symbol.Name); Assert.False(symbol.HasConstantValue); } [Fact] public void CircularEnumConstant01() { string sourceCode = @" enum E { A = B, B } class C { static void M(E e) { M(/*<bind>*/E.B/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("B", symbol.Name); Assert.False(symbol.HasConstantValue); } [Fact] public void CircularEnumConstant02() { string sourceCode = @" enum E { A = 10, B = C, C, D } class C { static void M(E e) { M(/*<bind>*/E.D/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("E", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.D", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("D", symbol.Name); Assert.False(symbol.HasConstantValue); } [Fact] public void EnumInitializer() { string sourceCode = @" enum E { A, B = 3 } enum F { C, D = 1 + /*<bind>*/E.B/*</bind>*/ } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("E", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("E.B", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(3, semanticInfo.ConstantValue); var symbol = (IFieldSymbol)semanticInfo.Symbol; Assert.IsAssignableFrom<SourceEnumConstantSymbol>(symbol.GetSymbol()); Assert.Equal("B", symbol.Name); Assert.True(symbol.HasConstantValue); Assert.Equal(3, symbol.ConstantValue); } [Fact] public void ParameterOfExplicitInterfaceImplementation() { string sourceCode = @" class Class : System.IFormattable { string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider) { return /*<bind>*/format/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String format", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BaseConstructorInitializer() { string sourceCode = @" class Class { Class(int x) : this(/*<bind>*/x/*</bind>*/ , x) { } Class(int x, int y) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.ContainingSymbol.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol.ContainingSymbol).MethodKind); } [WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")] [WorkItem(527831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527831")] [WorkItem(538794, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538794")] [Fact] public void InaccessibleMethodGroup() { string sourceCode = @" class C { private static void M(long i) { } private static void M(int i) { } } class D { void Goo() { C./*<bind>*/M/*</bind>*/(1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal("void C.M(System.Int64 i)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("void C.M(System.Int64 i)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_Constructors_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = /*<bind>*/new Class1(3, 7)/*</bind>*/; } } class Class1 { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InaccessibleMethodGroup_Constructors_ImplicitObjectCreationExpressionSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { Class1 x = /*<bind>*/new(3, 7)/*</bind>*/; } } class Class1 { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); sortedCandidates = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("Class1..ctor(System.Int32 x)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_Constructors_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = new /*<bind>*/Class1/*</bind>*/(3, 7); } } class Class1 { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_AttributeSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1(3, 7)/*</bind>*/] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleMethodGroup_Attribute_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1/*</bind>*/(3, 7)] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } protected Class1(int x) { } private Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = /*<bind>*/new Class1(3, 7)/*</bind>*/; } } class Class1 { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { public static void Main(string[] args) { var x = new /*<bind>*/Class1/*</bind>*/(3, 7); } } class Class1 { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_AttributeSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1(3, 7)/*</bind>*/] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542782")] [Fact] public void InaccessibleConstructorsFiltered_Attribute_IdentifierNameSyntax() { string sourceCode = @" using System; class Program { [/*<bind>*/Class1/*</bind>*/(3, 7)] public static void Main(string[] args) { } } class Class1 : Attribute { protected Class1() { } public Class1(int x) { } public Class1(int a, long b) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Class1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Class1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Class1..ctor(System.Int32 a, System.Int64 b)", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Class1..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")] [Fact] public void SyntaxErrorInReceiver() { string sourceCode = @" public delegate int D(int x); public class C { public C(int i) { } public void M(D d) { } } class Main { void Goo(int a) { new C(a.).M(x => /*<bind>*/x/*</bind>*/); } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(528754, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528754")] [Fact] public void SyntaxErrorInReceiverWithExtension() { string sourceCode = @" public delegate int D(int x); public static class CExtensions { public static void M(this C c, D d) { } } public class C { public C(int i) { } } class Main { void Goo(int a) { new C(a.).M(x => /*<bind>*/x/*</bind>*/); } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541011")] [Fact] public void NonStaticInstanceMismatchMethodGroup() { string sourceCode = @" class C { public static int P { get; set; } } class D { void Goo() { C./*<bind>*/set_P/*</bind>*/(1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.P.set", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(MethodKind.PropertySet, ((IMethodSymbol)sortedCandidates[0]).MethodKind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.P.set", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540360, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540360")] [Fact] public void DuplicateTypeName() { string sourceCode = @" struct C { } class C { public static void M() { } } enum C { A, B } class D { static void Main() { /*<bind>*/C/*</bind>*/.M(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("C", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal("C", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[2].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void IfCondition() { string sourceCode = @" class C { void M(int x) { if (/*<bind>*/x == 10/*</bind>*/) {} } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Int32.op_Equality(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ForCondition() { string sourceCode = @" class C { void M(int x) { for (int i = 0; /*<bind>*/i < 10/*</bind>*/; i = i + 1) { } } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Int32.op_LessThan(System.Int32 left, System.Int32 right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(539925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539925")] [Fact] public void LocalIsFromSource() { string sourceCode = @" class C { void M() { int x = 1; int y = /*<bind>*/x/*</bind>*/; } } "; var compilation = CreateCompilation(sourceCode); var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(compilation); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.True(semanticInfo.Symbol.GetSymbol().IsFromCompilation(compilation)); } [WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")] [Fact] public void InEnumElementInitializer() { string sourceCode = @" class C { public const int x = 1; } enum E { q = /*<bind>*/C.x/*</bind>*/, } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540541, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540541")] [Fact] public void InEnumOfByteElementInitializer() { string sourceCode = @" class C { public const int x = 1; } enum E : byte { q = /*<bind>*/C.x/*</bind>*/, } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Byte", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 C.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540672")] [Fact] public void LambdaExprWithErrorTypeInObjectCreationExpression() { var text = @" class Program { static int Main() { var d = /*<bind>*/() => { if (true) return new X(); else return new Y(); }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(text, parseOptions: TestOptions.Regular9); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [Fact] public void LambdaExpression() { string sourceCode = @" using System; public class TestClass { public static void Main() { Func<string, int> f = /*<bind>*/str => 10/*</bind>*/ ; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Func<System.String, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind); Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol); Assert.Equal(1, lambdaSym.Parameters.Length); Assert.Equal("str", lambdaSym.Parameters[0].Name); Assert.Equal("System.String", lambdaSym.Parameters[0].Type.ToTestDisplayString()); Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void UnboundLambdaExpression() { string sourceCode = @" using System; public class TestClass { public static void Main() { object f = /*<bind>*/str => 10/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); var lambdaSym = (IMethodSymbol)(semanticInfo.Symbol); Assert.Equal(1, lambdaSym.Parameters.Length); Assert.Equal("str", lambdaSym.Parameters[0].Name); Assert.Equal(TypeKind.Error, lambdaSym.Parameters[0].Type.TypeKind); Assert.Equal("System.Int32", lambdaSym.ReturnType.ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540650, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540650")] [Fact] public void TypeOfExpression() { string sourceCode = @" class C { static void Main() { System.Console.WriteLine(/*<bind>*/typeof(C)/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<TypeOfExpressionSyntax>(sourceCode); Assert.Equal("System.Type", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_If() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; if (c) int j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_For() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; for (; c; c = !c) label: /*<bind>*/c/*</bind>*/ = false; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_While() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; while (c) int j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_ForEach() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; foreach (string s in args) label: /*<bind>*/c/*</bind>*/ = false; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_Else() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; if (c); else long j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_Do() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; do label: /*<bind>*/c/*</bind>*/ = false; while(c); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_Using() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; using(null) long j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void LabeledEmbeddedStatement_Lock() { string sourceCode = @" class Program { static void Main(string[] args) { bool c = true; lock(this) label: /*<bind>*/c/*</bind>*/ = false; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean c", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540759, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540759")] [Fact] public void DeclarationEmbeddedStatement_Fixed() { string sourceCode = @" unsafe class Program { static void Main(string[] args) { bool c = true; fixed (bool* p = &c) int j = /*<bind>*/43/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(43, semanticInfo.ConstantValue); } [WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")] [Fact] public void BindLiteralCastToDouble() { string sourceCode = @" class MyClass { double dbl = /*<bind>*/1/*</bind>*/ ; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540803")] [Fact] public void BindDefaultOfVoidExpr() { string sourceCode = @" class C { void M() { return /*<bind>*/default(void)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Void, semanticInfo.Type.SpecialType); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void GetSemanticInfoForBaseConstructorInitializer() { string sourceCode = @" class C { C() /*<bind>*/: base()/*</bind>*/ { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void GetSemanticInfoForThisConstructorInitializer() { string sourceCode = @" class C { C() /*<bind>*/: this(1)/*</bind>*/ { } C(int x) { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540862, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540862")] [Fact] public void ThisStaticConstructorInitializer() { string sourceCode = @" class MyClass { static MyClass() /*<bind>*/: this()/*</bind>*/ { intI = 2; } public MyClass() { } static int intI = 1; } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("MyClass..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")] [Fact] public void IncompleteForEachWithArrayCreationExpr() { string sourceCode = @" class Program { static void Main(string[] args) { foreach (var f in new int[] { /*<bind>*/5/*</bind>*/ { Console.WriteLine(f); } } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(5, (int)semanticInfo.ConstantValue.Value); } [WorkItem(541037, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541037")] [Fact] public void EmptyStatementInForEach() { string sourceCode = @" class Program { static void Main(string[] args) { foreach (var a in /*<bind>*/args/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, ((IArrayTypeSymbol)semanticInfo.Type).ElementType.SpecialType); // CONSIDER: we could conceivable use the foreach collection type (vs the type of the collection expr). Assert.Equal(SpecialType.System_Collections_IEnumerable, semanticInfo.ConvertedType.SpecialType); Assert.Equal("args", semanticInfo.Symbol.Name); } [WorkItem(540922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540922")] [WorkItem(541030, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541030")] [Fact] public void ImplicitlyTypedForEachIterationVariable() { string sourceCode = @" class Program { static void Main(string[] args) { foreach (/*<bind>*/var/*</bind>*/ a in args); } } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); var symbol = semanticInfo.Symbol; Assert.Equal(SymbolKind.NamedType, symbol.Kind); Assert.Equal(SpecialType.System_String, ((ITypeSymbol)symbol).SpecialType); } [Fact] public void ForEachCollectionConvertedType() { // Arrays don't actually use IEnumerable, but that's the spec'd behavior. CheckForEachCollectionConvertedType("int[]", "System.Int32[]", "System.Collections.IEnumerable"); CheckForEachCollectionConvertedType("int[,]", "System.Int32[,]", "System.Collections.IEnumerable"); // Strings don't actually use string.GetEnumerator, but that's the spec'd behavior. CheckForEachCollectionConvertedType("string", "System.String", "System.String"); // Special case for dynamic CheckForEachCollectionConvertedType("dynamic", "dynamic", "System.Collections.IEnumerable"); // Pattern-based, not interface-based CheckForEachCollectionConvertedType("System.Collections.Generic.List<int>", "System.Collections.Generic.List<System.Int32>", "System.Collections.Generic.List<System.Int32>"); // Interface-based CheckForEachCollectionConvertedType("Enumerable", "Enumerable", "System.Collections.IEnumerable"); // helper method knows definition of this type // Interface CheckForEachCollectionConvertedType("System.Collections.Generic.IEnumerable<int>", "System.Collections.Generic.IEnumerable<System.Int32>", "System.Collections.Generic.IEnumerable<System.Int32>"); // Interface CheckForEachCollectionConvertedType("NotAType", "NotAType", "NotAType"); // name not in scope } private void CheckForEachCollectionConvertedType(string sourceType, string typeDisplayString, string convertedTypeDisplayString) { string template = @" public class Enumerable : System.Collections.IEnumerable {{ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {{ return null; }} }} class Program {{ void M({0} collection) {{ foreach (var v in /*<bind>*/collection/*</bind>*/); }} }} "; var semanticInfo = GetSemanticInfoForTest(string.Format(template, sourceType)); Assert.Equal(typeDisplayString, semanticInfo.Type.ToTestDisplayString()); Assert.Equal(convertedTypeDisplayString, semanticInfo.ConvertedType.ToTestDisplayString()); } [Fact] public void InaccessibleParameter() { string sourceCode = @" using System; class Outer { class Inner { } } class Program { public static void f(Outer.Inner a) { /*<bind>*/a/*</bind>*/ = 4; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Outer.Inner", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Outer.Inner", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Outer.Inner a", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); // Parameter's type is an error type, because Outer.Inner is inaccessible. var param = (IParameterSymbol)semanticInfo.Symbol; Assert.Equal(TypeKind.Error, param.Type.TypeKind); // It's type is not equal to the SemanticInfo type, because that is // not an error type. Assert.NotEqual(semanticInfo.Type, param.Type); } [Fact] public void StructConstructor() { string sourceCode = @" struct Struct{ public static void Main() { Struct s = /*<bind>*/new Struct()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); var symbol = semanticInfo.Symbol; Assert.NotNull(symbol); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)symbol).MethodKind); Assert.True(symbol.IsImplicitlyDeclared); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroupAsArgOfInvalidConstructorCall() { string sourceCode = @" using System; class Class { string M(int i) { new T(/*<bind>*/M/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.String Class.M(System.Int32 i)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.String Class.M(System.Int32 i)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void MethodGroupInReturnStatement() { string sourceCode = @" class C { public delegate int Func(int i); public Func Goo() { return /*<bind>*/Goo/*</bind>*/; } private int Goo(int i) { return i; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("C.Func", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C.Goo(int)", semanticInfo.ImplicitConversion.Method.ToString()); Assert.Equal("System.Int32 C.Goo(System.Int32 i)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C.Func C.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.Int32 C.Goo(System.Int32 i)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateConversionExtensionMethodNoReceiver() { string sourceCode = @"class C { static System.Action<object> F() { return /*<bind>*/S.E/*</bind>*/; } } static class S { internal static void E(this object o) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.NotNull(semanticInfo); Assert.Equal("System.Action<System.Object>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("void S.E(this System.Object o)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.ImplicitConversion.IsExtensionMethod); } [Fact] public void DelegateConversionExtensionMethod() { string sourceCode = @"class C { static System.Action F(object o) { return /*<bind>*/o.E/*</bind>*/; } } static class S { internal static void E(this object o) { } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.NotNull(semanticInfo); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal("void System.Object.E()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.IsExtensionMethod); } [Fact] public void InferredVarType() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var x = ""hello""; /*<bind>*/var/*</bind>*/ y = x; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InferredVarTypeWithNamespaceInScope() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; namespace var { } class Program { static void Main(string[] args) { var x = ""hello""; /*<bind>*/var/*</bind>*/ y = x; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NonInferredVarType() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; namespace N1 { class var { } class Program { static void Main(string[] args) { /*<bind>*/var/*</bind>*/ x = ""hello""; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("N1.var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.var", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541207")] [Fact] public void UndeclaredVarInThrowExpr() { string sourceCode = @" class Test { static void Main() { throw /*<bind>*/d1.Get/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo); } [Fact] public void FailedConstructorCall() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class C { } class Program { static void Main(string[] args) { C c = new /*<bind>*/C/*</bind>*/(17); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void FailedConstructorCall2() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class C { } class Program { static void Main(string[] args) { C c = /*<bind>*/new C(17)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MemberGroup.Length); Assert.Equal("C..ctor()", semanticInfo.MemberGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541332")] [Fact] public void ImplicitConversionCastExpression() { string sourceCode = @" using System; enum E { a, b } class Program { static int Main() { int ret = /*<bind>*/(int) E.b/*</bind>*/; return ret - 1; } } "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToString()); Assert.Equal("int", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); } [WorkItem(541333, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541333")] [Fact] public void ImplicitConversionAnonymousMethod() { string sourceCode = @" using System; delegate int D(); class Program { static int Main() { D d = /*<bind>*/delegate() { return int.MaxValue; }/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<AnonymousMethodExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("D", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.IsCompileTimeConstant); sourceCode = @" using System; delegate int D(); class Program { static int Main() { D d = /*<bind>*/() => { return int.MaxValue; }/*</bind>*/; return 0; } } "; semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("D", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.AnonymousFunction, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528476")] [Fact] public void BindingInitializerToTargetType() { string sourceCode = @" using System; class Program { static int Main() { int[] ret = new int[] /*<bind>*/ { 0, 1, 2 } /*</bind>*/; return ret[0]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); } [Fact] public void BindShortMethodArgument() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void goo(short s) { } static void Main(string[] args) { goo(/*<bind>*/123/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int16", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(123, semanticInfo.ConstantValue); } [WorkItem(541400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541400")] [Fact] public void BindingAttributeParameter() { string sourceCode = @" using System; public class MeAttribute : Attribute { public MeAttribute(short p) { } } [Me(/*<bind>*/123/*</bind>*/)] public class C { } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal("int", semanticInfo.Type.ToString()); Assert.Equal("short", semanticInfo.ConvertedType.ToString()); Assert.Equal(ConversionKind.ImplicitConstant, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); } [Fact] public void BindAttributeFieldNamedArgumentOnMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute() { } public string F; } class C1 { [Test(/*<bind>*/F/*</bind>*/=""method"")] int f() { return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String TestAttribute.F", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BindAttributePropertyNamedArgumentOnMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute() { } public TestAttribute(int i) { } public string F; public double P { get; set; } } class C1 { [Test(/*<bind>*/P/*</bind>*/=3.14)] int f() { return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Double TestAttribute.P { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void TestAttributeNamedArgumentValueOnMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class TestAttribute : Attribute { public TestAttribute() { } public TestAttribute(int i) { } public string F; public double P { get; set; } } class C1 { [Test(P=/*<bind>*/1/*</bind>*/)] int f() { return 0; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(540775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540775")] [Fact] public void LambdaExprPrecededByAnIncompleteUsingStmt() { var code = @" using System; class Program { static void Main(string[] args) { using Func<int, int> Dele = /*<bind>*/ x => { return x; } /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<SimpleLambdaExpressionSyntax>(code); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [WorkItem(540785, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540785")] [Fact] public void NestedLambdaExprPrecededByAnIncompleteNamespaceStmt() { var code = @" using System; class Program { static void Main(string[] args) { namespace Func<int, int> f1 = (x) => { Func<int, int> f2 = /*<bind>*/ (y) => { return y; } /*</bind>*/; return x; } ; } } "; var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(code); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Type); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [Fact] public void DefaultStructConstructor() { string sourceCode = @" using System; struct Struct{ public static void Main() { Struct s = new /*<bind>*/Struct/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Struct", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DefaultStructConstructor2() { string sourceCode = @" using System; struct Struct{ public static void Main() { Struct s = /*<bind>*/new Struct()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Struct", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Struct", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Struct..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Struct..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")] [Fact] public void BindAttributeInstanceWithoutAttributeSuffix() { string sourceCode = @" [assembly: /*<bind>*/My/*</bind>*/] class MyAttribute : System.Attribute { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("MyAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541451")] [Fact] public void BindQualifiedAttributeInstanceWithoutAttributeSuffix() { string sourceCode = @" [assembly: /*<bind>*/N1.My/*</bind>*/] namespace N1 { class MyAttribute : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode); Assert.Equal("N1.MyAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("N1.MyAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("N1.MyAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("N1.MyAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(540770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540770")] [Fact] public void IncompleteDelegateCastExpression() { string sourceCode = @" delegate void D(); class MyClass { public static int Main() { D d; d = /*<bind>*/(D) delegate /*</bind>*/ "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("D", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("D", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(7177, "DevDiv_Projects/Roslyn")] [Fact] public void IncompleteGenericDelegateDecl() { string sourceCode = @" using System; class Program { static void Main(string[] args) { /*<bind>*/Func<int, int> ()/*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541120")] [Fact] public void DelegateCreationArguments() { string sourceCode = @" class Program { int goo(int i) { return i;} static void Main(string[] args) { var r = /*<bind>*/new System.Func<int, int>((arg)=> { return 1;}, goo)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateCreationArguments2() { string sourceCode = @" class Program { int goo(int i) { return i;} static void Main(string[] args) { var r = new /*<bind>*/System.Func<int, int>/*</bind>*/((arg)=> { return 1;}, goo); } } "; var semanticInfo = GetSemanticInfoForTest<TypeSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Func<System.Int32, System.Int32>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void BaseConstructorInitializer2() { string sourceCode = @" class C { C() /*<bind>*/: base()/*</bind>*/ { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Object..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(MethodKind.Constructor, ((IMethodSymbol)semanticInfo.Symbol).MethodKind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ThisConstructorInitializer2() { string sourceCode = @" class C { C() /*<bind>*/: this(1)/*</bind>*/ { } C(int x) { } } "; var semanticInfo = GetSemanticInfoForTest<ConstructorInitializerSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C..ctor(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(539255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539255")] [Fact] public void TypeInParentOnFieldInitializer() { string sourceCode = @" class MyClass { double dbl = /*<bind>*/1/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [Fact] public void ExplicitIdentityConversion() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { int y = 12; long x = /*<bind>*/(int)y/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541588")] [Fact] public void ImplicitConversionElementsInArrayInit() { string sourceCode = @" class MyClass { long[] l1 = {/*<bind>*/4L/*</bind>*/, 5L }; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int64", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(4L, semanticInfo.ConstantValue); } [WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")] [Fact] public void ImplicitConversionArrayInitializer_01() { string sourceCode = @" class MyClass { int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(116, "https://github.com/dotnet/roslyn/issues/116")] [Fact] public void ImplicitConversionArrayInitializer_02() { string sourceCode = @" class MyClass { void Test() { int[] arr = /*<bind>*/{ 1, 2, 3 }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541595, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541595")] [Fact] public void ImplicitConversionExprReturnedByLambda() { string sourceCode = @" using System; class MyClass { Func<long> f1 = () => /*<bind>*/4/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.False(semanticInfo.ImplicitConversion.IsIdentity); Assert.True(semanticInfo.ImplicitConversion.IsImplicit); Assert.True(semanticInfo.ImplicitConversion.IsNumeric); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(4, semanticInfo.ConstantValue); } [WorkItem(541040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541040")] [WorkItem(528551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528551")] [Fact] public void InaccessibleNestedType() { string sourceCode = @" using System; internal class EClass { private enum EEK { a, b, c, d }; } class Test { public void M(EClass.EEK e) { b = /*<bind>*/ e /*</bind>*/; } EClass.EEK b = EClass.EEK.a; } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(SymbolKind.NamedType, semanticInfo.Type.Kind); Assert.Equal(TypeKind.Enum, semanticInfo.Type.TypeKind); Assert.NotNull(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(semanticInfo.Type, semanticInfo.ConvertedType); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter1() { string sourceCode = @" using System; class Program { public void f(int x, int y, int z) { } public void f(string y, string z) { } public void goo() { f(3, /*<bind>*/z/*</bind>*/: 4, y: 9); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 z", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter2() { string sourceCode = @" using System; class Program { public void f(int x, int y, int z) { } public void f(string y, string z, int q) { } public void f(string q, int w, int b) { } public void goo() { f(3, /*<bind>*/z/*</bind>*/: ""goo"", y: 9); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 z", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind); Assert.Equal("System.String z", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter3() { string sourceCode = @" using System; class Program { public void f(int x, int y, int z) { } public void f(string y, string z, int q) { } public void f(string q, int w, int b) { } public void goo() { f(3, z: ""goo"", /*<bind>*/yagga/*</bind>*/: 9); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void NamedParameter4() { string sourceCode = @" using System; namespace ClassLibrary44 { [MyAttr(/*<bind>*/x/*</bind>*/:1)] public class Class1 { } public class MyAttr: Attribute { public MyAttr(int x) {} } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")] [Fact] public void ImplicitReferenceConvExtensionMethodReceiver() { string sourceCode = @"public static class Extend { public static string TestExt(this object o1) { return o1.ToString(); } } class Program { static void Main(string[] args) { string str1 = ""Test""; var e1 = /*<bind>*/str1/*</bind>*/.TestExt(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.IsReference); Assert.Equal("System.String str1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); } [WorkItem(541623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541623")] [Fact] public void ImplicitBoxingConvExtensionMethodReceiver() { string sourceCode = @"struct S { } static class C { static void M(S s) { /*<bind>*/s/*</bind>*/.F(); } static void F(this object o) { } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("S", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.IsBoxing); Assert.Equal("S s", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, semanticInfo.Symbol.Kind); } [Fact] public void AttributeSyntaxBinding() { string sourceCode = @" using System; [/*<bind>*/MyAttr(1)/*</bind>*/] public class Class1 { } public class MyAttr: Attribute { public MyAttr(int x) {} } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); // Should bind to constructor. Assert.NotNull(semanticInfo.Symbol); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); } [WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void MemberAccessOnErrorType() { string sourceCode = @" public class Test2 { public static void Main() { string x1 = A./*<bind>*/M/*</bind>*/.C.D.E; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541653")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void MemberAccessOnErrorType2() { string sourceCode = @" public class Test2 { public static void Main() { string x1 = A./*<bind>*/M/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")] [Fact] public void DelegateCreation1() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = new /*<bind>*/MyDelegate/*</bind>*/(this.F); MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = new MyDelegate(MD1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateCreation1_2() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = /*<bind>*/new MyDelegate(this.F)/*</bind>*/; MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = new MyDelegate(MD1); } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")] [Fact] public void DelegateCreation2() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = new MyDelegate(this.F); MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = new /*<bind>*/MyDelegate/*</bind>*/(MD1); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("C.MyDelegate", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541764")] [Fact] public void DelegateCreation2_2() { string sourceCode = @" class C { delegate void MyDelegate(); public void F() { MyDelegate MD1 = new MyDelegate(this.F); MyDelegate MD2 = MD1 + MD1; MyDelegate MD3 = /*<bind>*/new MyDelegate(MD1)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("C.MyDelegate", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("C.MyDelegate", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateSignatureMismatch1() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = new /*<bind>*/Action/*</bind>*/(f); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Action", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateSignatureMismatch2() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = /*<bind>*/new Action(f)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DelegateSignatureMismatch3() { // This test and the DelegateSignatureMismatch4 should have identical results, as they are semantically identical string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = new Action(/*<bind>*/f/*</bind>*/); } } "; { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.WithoutImprovedOverloadCandidates); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } } [Fact] public void DelegateSignatureMismatch4() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static int f() { return 1; } static void Main(string[] args) { Action a = /*<bind>*/f/*</bind>*/; } } "; { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.WithoutImprovedOverloadCandidates); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.MethodGroup, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Program.f()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Empty(semanticInfo.CandidateSymbols); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Program.f()", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("System.Int32 Program.f()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } } [WorkItem(541802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541802")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void IncompleteLetClause() { string sourceCode = @" public class Test2 { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/var/*</bind>*/ q2 = from x in nums let z = x. } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541895, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541895")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void QueryErrorBaseKeywordAsSelectExpression() { string sourceCode = @" using System; using System.Linq; public class QueryExpressionTest { public static void Main() { var expr1 = new int[] { 1 }; /*<bind>*/var/*</bind>*/ query2 = from int b in expr1 select base; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541805, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541805")] [Fact] public void InToIdentifierQueryContinuation() { string sourceCode = @" using System; using System.Linq; public class Test2 { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = from x in nums select x into w select /*<bind>*/w/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541833")] [Fact] public void InOptimizedAwaySelectClause() { string sourceCode = @" using System; using System.Linq; public class Test2 { public static void Main() { var nums = new int[] { 1, 2, 3, 4 }; var q2 = from x in nums where x > 1 select /*<bind>*/x/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [Fact] public void InFromClause() { string sourceCode = @" using System; using System.Linq; class C { void M() { int rolf = 732; int roark = -9; var replicator = from r in new List<int> { 1, 2, 9, rolf, /*<bind>*/roark/*</bind>*/ } select r * 2; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541911")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void QueryErrorGroupJoinFromClause() { string sourceCode = @" class Test { static void Main() { /*<bind>*/var/*</bind>*/ q = from Goo i in i from Goo<int> j in j group i by i join Goo } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(SymbolKind.ErrorType, semanticInfo.Type.Kind); } [WorkItem(541920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541920")] [Fact] public void SymbolInfoForMissingSelectClauseNode() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string[] strings = { }; var query = from s in strings let word = s.Split(' ') from w in w } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var selectClauseNode = tree.FindNodeOrTokenByKind(SyntaxKind.SelectClause).AsNode() as SelectClauseSyntax; var symbolInfo = semanticModel.GetSymbolInfo(selectClauseNode); // https://github.com/dotnet/roslyn/issues/38509 // Assert.NotEqual(default, symbolInfo); Assert.Null(symbolInfo.Symbol); } [WorkItem(541940, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541940")] [Fact] public void IdentifierInSelectNotInContext() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { string[] strings = { }; var query = from ch in strings group ch by ch into chGroup where chGroup.Count() >= 2 select /*<bind>*/ x1 /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); } [Fact] public void WhereDefinedInType() { var csSource = @" using System; class Y { public int Where(Func<int, bool> predicate) { return 45; } } class P { static void Main() { var src = new Y(); var query = from x in src where x > 0 select /*<bind>*/ x /*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(csSource); Assert.Equal("x", semanticInfo.Symbol.Name); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [WorkItem(541830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541830")] [Fact] public void AttributeUsageError() { string sourceCode = @" using System; [/*<bind>*/AttributeUsage/*</bind>*/()] class MyAtt : Attribute {} "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); Assert.Equal("AttributeUsageAttribute", semanticInfo.Type.Name); } [WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")] [Fact] public void OpenGenericTypeInAttribute() { string sourceCode = @" class Gen<T> {} [/*<bind>*/Gen<T>/*</bind>*/] public class Test { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541832")] [Fact] public void OpenGenericTypeInAttribute02() { string sourceCode = @" class Goo {} [/*<bind>*/Goo/*</bind>*/] public class Test { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")] [Fact] public void IncompleteEmptyAttributeSyntax01() { string sourceCode = @" public class CSEvent { [ "; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax; var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Symbol); Assert.Null(semanticInfo.Type); } /// <summary> /// Same as above but with a token after the incomplete /// attribute so the attribute is not at the end of file. /// </summary> [WorkItem(541896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541896")] [Fact] public void IncompleteEmptyAttributeSyntax02() { string sourceCode = @" public class CSEvent { [ }"; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var attributeNode = tree.FindNodeOrTokenByKind(SyntaxKind.Attribute).AsNode() as AttributeSyntax; var semanticInfo = semanticModel.GetSemanticInfoSummary(attributeNode); Assert.NotNull(semanticInfo); Assert.Null(semanticInfo.Symbol); Assert.Null(semanticInfo.Type); } [WorkItem(541857, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541857")] [Fact] public void EventWithInitializerInInterface() { string sourceCode = @" public delegate void MyDelegate(); interface test { event MyDelegate e = /*<bind>*/new MyDelegate(Test.Main)/*</bind>*/; } class Test { static void Main() { } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("MyDelegate", semanticInfo.Type.ToTestDisplayString()); } [Fact] public void SwitchExpression_Constant01() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/true/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] [WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")] public void SwitchExpression_Constant02() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; const string s = null; switch (/*<bind>*/s/*</bind>*/) { case null: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [Fact] [WorkItem(40352, "https://github.com/dotnet/roslyn/issues/40352")] public void SwitchExpression_NotConstant() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; string s = null; switch (/*<bind>*/s/*</bind>*/) { case null: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.Nullability.FlowState); Assert.Equal(CodeAnalysis.NullableFlowState.None, semanticInfo.ConvertedNullability.FlowState); Assert.Equal("System.String", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.String s", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchExpression_Invalid_Lambda() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/()=>3/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<ParenthesizedLambdaExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Null(semanticInfo.Type); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("lambda expression", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchExpression_Invalid_MethodGroup() { string sourceCode = @" using System; public class Test { public static int M() {return 0; } public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/M/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Null(semanticInfo.Type); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchExpression_Invalid_GoverningType() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (/*<bind>*/2.2/*</bind>*/) { default: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("System.Double", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(2.2, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_Null() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; const string s = null; switch (s) { case /*<bind>*/null/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [Fact] public void SwitchCaseLabelExpression_Constant01() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (true) { case /*<bind>*/true/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_Constant02() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; const bool x = true; switch (true) { case /*<bind>*/x/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_NotConstant() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; bool x = true; switch (true) { case /*<bind>*/x/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SwitchCaseLabelExpression_CastExpression() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; switch (ret) { case /*<bind>*/(int)'a'/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<CastExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(97, semanticInfo.ConstantValue); } [Fact] public void SwitchCaseLabelExpression_Invalid_Lambda() { string sourceCode = @" using System; public class Test { public static int Main(string[] args) { int ret = 1; string s = null; switch (s) { case /*<bind>*/()=>3/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; CreateCompilation(sourceCode).VerifyDiagnostics( // (12,30): error CS1003: Syntax error, ':' expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(12, 30), // (12,30): error CS1513: } expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(12, 30), // (12,44): error CS1002: ; expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(12, 44), // (12,44): error CS1513: } expected // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(12, 44), // (12,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(12, 28), // (12,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type. // case /*<bind>*/()=>3/*</bind>*/: Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(12, 28) ); } [Fact] public void SwitchCaseLabelExpression_Invalid_LambdaWithSyntaxError() { string sourceCode = @" using System; public class Test { static int M() { return 0;} public static int Main(string[] args) { int ret = 1; string s = null; switch (s) { case /*<bind>*/()=>/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; CreateCompilation(sourceCode).VerifyDiagnostics( // (13,30): error CS1003: Syntax error, ':' expected // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_SyntaxError, "=>").WithArguments(":", "=>").WithLocation(13, 30), // (13,30): error CS1513: } expected // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(13, 30), // (13,28): error CS1501: No overload for method 'Deconstruct' takes 0 arguments // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_BadArgCount, "()").WithArguments("Deconstruct", "0").WithLocation(13, 28), // (13,28): error CS8129: No suitable Deconstruct instance or extension method was found for type 'string', with 0 out parameters and a void return type. // case /*<bind>*/()=>/*</bind>*/: Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("string", "0").WithLocation(13, 28) ); } [Fact] public void SwitchCaseLabelExpression_Invalid_MethodGroup() { string sourceCode = @" using System; public class Test { static int M() { return 0;} public static int Main(string[] args) { int ret = 1; string s = null; switch (s) { case /*<bind>*/M/*</bind>*/: ret = 0; break; } Console.Write(ret); return (ret); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("System.String", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal("System.Int32 Test.M()", semanticInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.M()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541932")] [Fact] public void IndexingExpression() { string sourceCode = @" class Test { static void Main() { string str = ""Test""; char ch = str[/*<bind>*/ 0 /*</bind>*/]; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(0, semanticInfo.ConstantValue); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); } [Fact] public void InaccessibleInTypeof() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class A { class B { } } class Program { static void Main(string[] args) { object o = typeof(/*<bind>*/A.B/*</bind>*/); } } "; var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode); Assert.Equal("A.B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A.B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A.B", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AttributeWithUnboundGenericType01() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/B<>/*</bind>*/))] class B<T> { public class C { } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.True((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [Fact] public void AttributeWithUnboundGenericType02() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/B<>.C/*</bind>*/))] class B<T> { public class C { } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.True((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [Fact] public void AttributeWithUnboundGenericType03() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/D/*</bind>*/.C<>))] class B<T> { public class C<U> { } } class D : B<int> { }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.False((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [Fact] public void AttributeWithUnboundGenericType04() { var sourceCode = @"using System; class A : Attribute { public A(object o) { } } [A(typeof(/*<bind>*/B<>/*</bind>*/.C<>))] class B<T> { public class C<U> { } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = semanticInfo.Type; Assert.Equal("B", type.Name); Assert.True((type as INamedTypeSymbol).IsUnboundGenericType); Assert.False((type as INamedTypeSymbol).IsErrorType()); } [WorkItem(542430, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542430")] [Fact] public void UnboundTypeInvariants() { var sourceCode = @"using System; public class A<T> { int x; public class B<U> { int y; } } class Program { public static void Main(string[] args) { Console.WriteLine(typeof(/*<bind>*/A<>.B<>/*</bind>*/)); } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = (INamedTypeSymbol)semanticInfo.Type; Assert.Equal("B", type.Name); Assert.True(type.IsUnboundGenericType); Assert.False(type.IsErrorType()); Assert.True(type.TypeArguments[0].IsErrorType()); var constructedFrom = type.ConstructedFrom; Assert.Equal(constructedFrom, constructedFrom.ConstructedFrom); Assert.Equal(constructedFrom, constructedFrom.TypeParameters[0].ContainingSymbol); Assert.Equal(constructedFrom.TypeArguments[0], constructedFrom.TypeParameters[0]); Assert.Equal(type.ContainingSymbol, constructedFrom.ContainingSymbol); Assert.Equal(type.TypeParameters[0], constructedFrom.TypeParameters[0]); Assert.False(constructedFrom.TypeArguments[0].IsErrorType()); Assert.NotEqual(type, constructedFrom); Assert.False(constructedFrom.IsUnboundGenericType); var a = type.ContainingType; Assert.Equal(constructedFrom, a.GetTypeMembers("B").Single()); Assert.NotEqual(type.TypeParameters[0], type.OriginalDefinition.TypeParameters[0]); // alpha renamed Assert.Null(type.BaseType); Assert.Empty(type.Interfaces); Assert.NotNull(constructedFrom.BaseType); Assert.Empty(type.GetMembers()); Assert.NotEmpty(constructedFrom.GetMembers()); Assert.True(a.IsUnboundGenericType); Assert.False(a.ConstructedFrom.IsUnboundGenericType); Assert.Equal(1, a.GetMembers().Length); } [WorkItem(528659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528659")] [Fact] public void AliasTypeName() { string sourceCode = @" using A = System.String; class Test { static void Main() { /*<bind>*/A/*</bind>*/ a = null; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal("System.String", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); Assert.Equal("A", aliasInfo.Name); Assert.Equal("A=System.String", aliasInfo.ToTestDisplayString()); } [WorkItem(542000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542000")] [Fact] public void AmbigAttributeBindWithoutAttributeSuffix() { string sourceCode = @" namespace Blue { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Red { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Green { using Blue; using Red; public class Test { [/*<bind>*/Description/*</bind>*/(null)] static void Main() { } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528669, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528669")] [Fact] public void AmbigAttributeBind1() { string sourceCode = @" namespace Blue { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Red { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace Green { using Blue; using Red; public class Test { [/*<bind>*/DescriptionAttribute/*</bind>*/(null)] static void Main() { } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Blue.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Blue.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("Red.DescriptionAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542205")] [Fact] public void IncompleteAttributeSymbolInfo() { string sourceCode = @" using System; class Program { [/*<bind>*/ObsoleteAttribute(x/*</bind>*/ static void Main(string[] args) { } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var sourceCode = @" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal(5, semanticInfo.ConstantValue); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void CircularConstantFieldInitializerExpression() { var sourceCode = @" public class C { const int x = /*<bind>*/x/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542017, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542017")] [Fact] public void AmbigAttributeBind2() { string sourceCode = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute { } [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [/*<bind>*/X/*</bind>*/] class Class1 { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); } [WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")] [Fact] public void AmbigAttributeBind3() { string sourceCode = @" using System; [AttributeUsage(AttributeTargets.All)] public class X : Attribute { } [AttributeUsage(AttributeTargets.All)] public class XAttribute : Attribute { } [/*<bind>*/X/*</bind>*/] class Class1 { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("XAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); } [Fact] public void AmbigAttributeBind4() { string sourceCode = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_01 { using ValidWithSuffix; using ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("ValidWithSuffix.DescriptionAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind5() { string sourceCode = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_02 { using ValidWithSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description.Description(string)", semanticInfo.MethodGroup[0].ToDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind6() { string sourceCode = @" namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_03 { using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.DescriptionAttribute.DescriptionAttribute(string)", semanticInfo.MethodGroup[0].ToDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind7() { string sourceCode = @" namespace ValidWithSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } } namespace ValidWithoutSuffix { public class Description : System.Attribute { public Description(string name) { } } } namespace ValidWithSuffix_And_ValidWithoutSuffix { public class DescriptionAttribute : System.Attribute { public DescriptionAttribute(string name) { } } public class Description : System.Attribute { public Description(string name) { } } } namespace TestNamespace_04 { using ValidWithSuffix; using ValidWithoutSuffix; using ValidWithSuffix_And_ValidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("ValidWithSuffix_And_ValidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("ValidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind8() { string sourceCode = @" namespace InvalidWithSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } } namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace TestNamespace_05 { using InvalidWithSuffix; using InvalidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InvalidWithoutSuffix.Description..ctor(System.String name)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AmbigAttributeBind9() { string sourceCode = @" namespace InvalidWithoutSuffix { public class Description { public Description(string name) { } } } namespace InvalidWithSuffix_And_InvalidWithoutSuffix { public class DescriptionAttribute { public DescriptionAttribute(string name) { } } public class Description { public Description(string name) { } } } namespace TestNamespace_07 { using InvalidWithoutSuffix; using InvalidWithSuffix_And_InvalidWithoutSuffix; [/*<bind>*/Description/*</bind>*/(null)] public class Test { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InvalidWithSuffix_And_InvalidWithoutSuffix.Description", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("InvalidWithoutSuffix.Description", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact()] public void AliasAttributeName() { string sourceCode = @" using A = A1; class A1 : System.Attribute { } [/*<bind>*/A/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("A1", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("A1", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("A1..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A1..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("A=A1", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact()] public void AliasAttributeName_02_AttributeSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact] public void AliasAttributeName_02_IdentifierNameSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact] public void AliasAttributeName_03_AttributeSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/GooAttribute/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact] public void AliasAttributeName_03_IdentifierNameSyntax() { string sourceCode = @" using GooAttribute = System.ObsoleteAttribute; [/*<bind>*/GooAttribute/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.ObsoleteAttribute..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.NotNull(aliasInfo); Assert.Equal("GooAttribute=System.ObsoleteAttribute", aliasInfo.ToTestDisplayString()); Assert.Equal(SymbolKind.Alias, aliasInfo.Kind); } [WorkItem(542979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542979")] [Fact()] public void AliasQualifiedAttributeName_01() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [global::/*<bind>*/AttributeClass/*</bind>*/.NonAttributeClass()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified"); } [Fact] public void AliasQualifiedAttributeName_02() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [/*<bind>*/global::AttributeClass/*</bind>*/.NonAttributeClass()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<AliasQualifiedNameSyntax>(sourceCode); Assert.Equal("AttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("AttributeClass", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); Assert.False(SyntaxFacts.IsAttributeName(((SourceNamedTypeSymbol)((CSharp.Symbols.PublicModel.NamedTypeSymbol)semanticInfo.Symbol).UnderlyingNamedTypeSymbol).SyntaxReferences.First().GetSyntax()), "IsAttributeName can be true only for alias name being qualified"); } [Fact] public void AliasQualifiedAttributeName_03() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [global::AttributeClass./*<bind>*/NonAttributeClass/*</bind>*/()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AliasQualifiedAttributeName_04() { string sourceCode = @" class AttributeClass : System.Attribute { class NonAttributeClass { } } namespace N { [/*<bind>*/global::AttributeClass.NonAttributeClass/*</bind>*/()] class C { } class AttributeClass : System.Attribute { } } "; var semanticInfo = GetSemanticInfoForTest<QualifiedNameSyntax>(sourceCode); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("AttributeClass.NonAttributeClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("AttributeClass.NonAttributeClass..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AliasAttributeName_NonAttributeAlias() { string sourceCode = @" using GooAttribute = C; [/*<bind>*/GooAttribute/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("C", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("C", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("C..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AliasAttributeName_NonAttributeAlias_GenericType() { string sourceCode = @" using GooAttribute = Gen<int>; [/*<bind>*/GooAttribute/*</bind>*/] class C { } class Gen<T> { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Gen<System.Int32>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<System.Int32>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<System.Int32>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<System.Int32>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AmbigAliasAttributeName() { string sourceCode = @" using A = A1; using AAttribute = A2; class A1 : System.Attribute { } class A2 : System.Attribute { } [/*<bind>*/A/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("A", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("A", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("A1", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("A2", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AmbigAliasAttributeName_02() { string sourceCode = @" using Goo = System.ObsoleteAttribute; class GooAttribute : System.Attribute { } [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("System.ObsoleteAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [Fact] public void AmbigAliasAttributeName_03() { string sourceCode = @" using Goo = GooAttribute; class GooAttribute : System.Attribute { } [/*<bind>*/Goo/*</bind>*/] class C { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("GooAttribute", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("GooAttribute", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(aliasInfo); } [WorkItem(542018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542018")] [Fact] public void AmbigObjectCreationBind() { string sourceCode = @" using System; public class X { } public struct X { } class Class1 { public static void Main() { object x = new /*<bind>*/X/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Ambiguous, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal("X", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[1].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); } [WorkItem(542027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542027")] [Fact()] public void NonStaticMemberOfOuterTypeAccessedViaNestedType() { string sourceCode = @" class MyClass { public int intTest = 1; class TestClass { public void TestMeth() { int intI = /*<bind>*/ intTest /*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.StaticInstanceMismatch, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass.intTest", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")] [Fact()] public void ThisInFieldInitializer() { string sourceCode = @" class MyClass { public MyClass self = /*<bind>*/ this /*</bind>*/; }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("MyClass", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MyClass", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal(1, sortedCandidates.Length); Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(530093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530093")] [Fact()] public void BaseInFieldInitializer() { string sourceCode = @" class MyClass { public object self = /*<bind>*/ base /*</bind>*/ .Id(); object Id() { return this; } }"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(SymbolKind.Parameter, semanticInfo.CandidateSymbols[0].Kind); Assert.Equal(CandidateReason.NotReferencable, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal(1, sortedCandidates.Length); Assert.Equal("MyClass this", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact()] public void MemberAccessToInaccessibleField() { string sourceCode = @" class MyClass1 { private static int myInt1 = 12; } class MyClass2 { public int myInt2 = /*<bind>*/MyClass1.myInt1/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass1.myInt1", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528682")] [Fact] public void PropertyGetAccessWithPrivateGetter() { string sourceCode = @" public class MyClass { public int Property { private get { return 0; } set { } } } public class Test { public static void Main(string[] args) { MyClass c = new MyClass(); int a = c./*<bind>*/Property/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass.Property { private get; set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")] [Fact] public void GetAccessPrivateProperty() { string sourceCode = @" public class Test { class Class1 { private int a { get { return 1; } set { } } } class Class2 : Class1 { public int b() { return /*<bind>*/a/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.Class1.a { get; set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")] [Fact] public void GetAccessPrivateField() { string sourceCode = @" public class Test { class Class1 { private int a; } class Class2 : Class1 { public int b() { return /*<bind>*/a/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 Test.Class1.a", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542053, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542053")] [Fact] public void GetAccessPrivateEvent() { string sourceCode = @" using System; public class Test { class Class1 { private event Action a; } class Class2 : Class1 { public Action b() { return /*<bind>*/a/*</bind>*/(); } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Action", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.Type.TypeKind); Assert.Equal("System.Action", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Delegate, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("event System.Action Test.Class1.a", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Event, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528684")] [Fact] public void PropertySetAccessWithPrivateSetter() { string sourceCode = @" public class MyClass { public int Property { get { return 0; } private set { } } } public class Test { static void Main() { MyClass c = new MyClass(); c./*<bind>*/Property/*</bind>*/ = 10; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MyClass.Property { get; private set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void PropertyIndexerAccessWithPrivateSetter() { string sourceCode = @" public class MyClass { public object this[int index] { get { return null; } private set { } } } public class Test { static void Main() { MyClass c = new MyClass(); /*<bind>*/c[0]/*</bind>*/ = null; } } "; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); Assert.Equal("System.Object", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Object MyClass.this[System.Int32 index] { get; private set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542065, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542065")] [Fact] public void GenericTypeWithNoTypeArgsOnAttribute() { string sourceCode = @" class Gen<T> { } [/*<bind>*/Gen/*</bind>*/] public class Test { public static int Main() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542125")] [Fact] public void MalformedSyntaxSemanticModel_Bug9223() { string sourceCode = @" public delegate int D(int x); public st C { public event D EV; public C(D d) { EV = /*<bind>*/d/*</bind>*/; } public int OnEV(int x) { return x; } } "; // Don't crash or assert. var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); } [WorkItem(528746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528746")] [Fact] public void ImplicitConversionArrayCreationExprInQuery() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q2 = from x in /*<bind>*/new int[] { 4, 5 }/*</bind>*/ select x; } } "; var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542256")] [Fact] public void MalformedConditionalExprInWhereClause() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { 4, 5 } where /*<bind>*/new Program()/*</bind>*/ ? select x; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo.Symbol); Assert.Equal("Program..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal("Program", semanticInfo.Type.Name); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact] public void MalformedExpressionInSelectClause() { string sourceCode = @" using System.Linq; class P { static void Main() { var src = new int[] { 4, 5 }; var q = from x in src select /*<bind>*/x/*</bind>*/."; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.NotNull(semanticInfo.Symbol); } [WorkItem(542344, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542344")] [Fact] public void LiteralExprInGotoCaseInsideSwitch() { string sourceCode = @" public class Test { public static void Main() { int ret = 6; switch (ret) { case 0: goto case /*<bind>*/2/*</bind>*/; case 2: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(SpecialType.System_Int32, semanticInfo.Type.SpecialType); Assert.Equal(2, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ImplicitConvCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { long number = 45; switch (number) { case /*<bind>*/21/*</bind>*/: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ErrorConvCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { double number = 45; switch (number) { case /*<bind>*/21/*</bind>*/: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ImplicitConvGotoCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { long number = 45; switch (number) { case 1: goto case /*<bind>*/21/*</bind>*/; case 21: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542405")] [Fact] public void ErrorConvGotoCaseConstantExpr() { string sourceCode = @" class Program { static void Main() { double number = 45; switch (number) { case 1: goto case /*<bind>*/21/*</bind>*/; case 21: break; } } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Double", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(21, semanticInfo.ConstantValue); } [WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")] [Fact] public void AttributeSemanticInfo_OverloadResolutionFailure_01() { string sourceCode = @" [module: /*<bind>*/System.Obsolete(typeof(.<>))/*</bind>*/] "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo); } [WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")] [Fact] public void AttributeSemanticInfo_OverloadResolutionFailure_02() { string sourceCode = @" [module: System./*<bind>*/Obsolete/*</bind>*/(typeof(.<>))] "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(semanticInfo); } private void Verify_AttributeSemanticInfo_OverloadResolutionFailure_Common(CompilationUtils.SemanticInfoSummary semanticInfo) { Assert.Equal("System.ObsoleteAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.ObsoleteAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(3, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedCandidates[2].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[2].Kind); Assert.Equal(3, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.ObsoleteAttribute..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message)", sortedMethodGroup[1].ToTestDisplayString()); Assert.Equal("System.ObsoleteAttribute..ctor(System.String message, System.Boolean error)", sortedMethodGroup[2].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542351, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542351")] [Fact] public void ObjectCreationSemanticInfo_OverloadResolutionFailure() { string sourceCode = @" using System; class Goo { public Goo() { } public Goo(int x) { } public static void Main() { var x = new /*<bind>*/Goo/*</bind>*/(typeof(.<>)); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Goo", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectCreationSemanticInfo_OverloadResolutionFailure_2() { string sourceCode = @" using System; class Goo { public Goo() { } public Goo(int x) { } public static void Main() { var x = /*<bind>*/new Goo(typeof(Goo))/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Goo", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Goo", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("Goo..ctor(System.Int32 x)", sortedCandidates[1].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Goo..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.Equal("Goo..ctor(System.Int32 x)", sortedMethodGroup[1].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ParameterDefaultValue1() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; void f(long i = 32 + Constants./*<bind>*/k/*</bind>*/, long j = i) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int16", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int16 Constants.k", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal((short)9, semanticInfo.ConstantValue); } [Fact] public void ParameterDefaultValue2() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; void f(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(12, semanticInfo.ConstantValue); } [Fact] public void ParameterDefaultValueInConstructor() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; Class1(long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(12, semanticInfo.ConstantValue); } [Fact] public void ParameterDefaultValueInIndexer() { string sourceCode = @" using System; class Constants { public const short k = 9; } public class Class1 { const int i = 12; const int j = 14; public string this[long i = 32 + Constants.k, long j = /*<bind>*/i/*</bind>*/] { get { return """"; } set { } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Class1.i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(12, semanticInfo.ConstantValue); } [WorkItem(542589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542589")] [Fact] public void UnrecognizedGenericTypeReference() { string sourceCode = "/*<bind>*/C<object, string/*</bind>*/"; var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(sourceCode); var type = (INamedTypeSymbol)semanticInfo.Type; Assert.Equal("System.Boolean", type.ToTestDisplayString()); } [WorkItem(542452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542452")] [Fact] public void LambdaInSelectExpressionWithObjectCreation() { string sourceCode = @" using System; using System.Linq; using System.Collections.Generic; class Test { static void Main() { } static void Goo(List<int> Scores) { var z = from y in Scores select new Action(() => { /*<bind>*/var/*</bind>*/ x = y; }); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void DefaultOptionalParamValue() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { const bool v = true; public void Goo(bool b = /*<bind>*/v == true/*</bind>*/) { } } "; var semanticInfo = GetSemanticInfoForTest<BinaryExpressionSyntax>(sourceCode); Assert.Equal("System.Boolean", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Boolean", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Boolean System.Boolean.op_Equality(System.Boolean left, System.Boolean right)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(true, semanticInfo.ConstantValue); } [Fact] public void DefaultOptionalParamValueWithGenericTypes() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void Goo<T, U>(T t = /*<bind>*/default(U)/*</bind>*/) where U : class, T { } static void Main(string[] args) { } } "; var semanticInfo = GetSemanticInfoForTest<DefaultExpressionSyntax>(sourceCode); Assert.Equal("U", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind); Assert.Equal("T", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.TypeParameter, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Null(semanticInfo.ConstantValue.Value); } [WorkItem(542850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542850")] [Fact] public void InaccessibleExtensionMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; public static class Extensions { private static int Goo(this string z) { return 3; } } class Program { static void Main(string[] args) { args[0]./*<bind>*/Goo/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 System.String.Goo()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 System.String.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542883, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542883")] [Fact] public void InaccessibleNamedAttrArg() { string sourceCode = @" using System; public class B : Attribute { private int X; } [B(/*<bind>*/X/*</bind>*/ = 5)] public class D { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 B.X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Field, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(528914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528914")] [Fact] public void InvalidIdentifierAsAttrArg() { string sourceCode = @" using System.Runtime.CompilerServices; public interface Interface1 { [/*<bind>*/IndexerName(null)/*</bind>*/] string this[int arg] { get; set; } } "; var semanticInfo = GetSemanticInfoForTest<AttributeSyntax>(sourceCode); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.Type.ToTestDisplayString()); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Runtime.CompilerServices.IndexerNameAttribute..ctor(System.String indexerName)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542890")] [Fact()] public void GlobalIdentifierName() { string sourceCode = @" class Test { static void Main() { var t1 = new /*<bind>*/global/*</bind>*/::Test(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.Equal("global", aliasInfo.Name); Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString()); Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace); Assert.False(aliasInfo.IsExtern); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact()] public void GlobalIdentifierName2() { string sourceCode = @" class Test { /*<bind>*/global/*</bind>*/::Test f; static void Main() { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); var aliasInfo = GetAliasInfoForTest(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("<global namespace>", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.True(((INamespaceSymbol)semanticInfo.Symbol).IsGlobalNamespace); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.Equal("global", aliasInfo.Name); Assert.Equal("<global namespace>", aliasInfo.Target.ToTestDisplayString()); Assert.True(((NamespaceSymbol)(aliasInfo.Target)).IsGlobalNamespace); Assert.False(aliasInfo.IsExtern); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(542536, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542536")] [Fact] public void UndeclaredSymbolInDefaultParameterValue() { string sourceCode = @" class Program { const int y = 1; public void Goo(bool x = (undeclared == /*<bind>*/y/*</bind>*/)) { } static void Main(string[] args) { } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Program.y", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [WorkItem(543198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543198")] [Fact] public void NamespaceAliasInsideMethod() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; using A = NS1; namespace NS1 { class B { } } class Program { class A { } A::B y = null; void Main() { /*<bind>*/A/*</bind>*/::B.Equals(null, null); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); // Should bind to namespace alias A=NS1, not class Program.A. Assert.Equal("NS1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Namespace, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_ImplicitArrayCreationSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public static int Main() { var a = /*<bind>*/new[] { 1, 2, 3 }/*</bind>*/; return a[0]; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_IdentifierNameSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public static int Main() { var a = new[] { 1, 2, 3 }; return /*<bind>*/a/*</bind>*/[0]; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32[] a", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_MultiDim_ImplicitArrayCreationSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public int[][, , ] Goo() { var a3 = new[] { /*<bind>*/new [,,] {{{1, 2}}}/*</bind>*/, new [,,] {{{3, 4}}} }; return a3; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[,,]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_MultiDim_IdentifierNameSyntax() { string sourceCode = @" using System; namespace Test { public class Program { public int[][, , ] Goo() { var a3 = new[] { new [,,] {{{3, 4}}}, new [,,] {{{3, 4}}} }; return /*<bind>*/a3/*</bind>*/; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32[][,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[][,,]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32[][,,] a3", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_ImplicitArrayCreationSyntax() { string sourceCode = @" public class C { public int[] Goo() { char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = /*<bind>*/new[] { s1, s2, s3, s4, c, '1' }/*</bind>*/; // CS0826 return array1; } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_IdentifierNameSyntax() { string sourceCode = @" public class C { public int[] Goo() { char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { s1, s2, s3, s4, c, '1' }; // CS0826 return /*<bind>*/array1/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("?[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Equal("?[] array1", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr() { string sourceCode = @" using System; namespace Test { public class Program { public int[][,,] Goo() { var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, 3, 4 }/*</bind>*/, new[,,] { { { 3, 4 } } } }; return a3; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Error_NonArrayInitExpr_02() { string sourceCode = @" using System; namespace Test { public class Program { public int[][,,] Goo() { var a3 = new[] { /*<bind>*/new[,,] { { { 3, 4 } }, x, y }/*</bind>*/, new[,,] { { { 3, 4 } } } }; return a3; } } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("?[,,]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ImplicitArrayCreationExpression_Inside_ErrorImplicitArrayCreation() { string sourceCode = @" public class C { public int[] Goo() { char c = 'c'; short s1 = 0; short s2 = -0; short s3 = 1; short s4 = -1; var array1 = new[] { /*<bind>*/new[] { 1, 2 }/*</bind>*/, new[] { s1, s2, s3, s4, c, '1' } }; // CS0826 return array1; } } "; var semanticInfo = GetSemanticInfoForTest<ImplicitArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("System.Int32[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(543201, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543201")] public void BindVariableIncompleteForLoop() { string sourceCode = @" class Program { static void Main() { for (int i = 0; /*<bind>*/i/*</bind>*/ } }"; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); } [Fact, WorkItem(542843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542843")] public void Bug10245() { string sourceCode = @" class C<T> { public T Field; } class D { void M() { new C<int>./*<bind>*/Field/*</bind>*/.ToString(); } } "; var tree = Parse(sourceCode); var comp = CreateCompilation(tree); var model = comp.GetSemanticModel(tree); var expr = GetExprSyntaxForBinding(GetExprSyntaxList(tree)); var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal(CandidateReason.NotATypeOrNamespace, symbolInfo.CandidateReason); Assert.Equal(1, symbolInfo.CandidateSymbols.Length); Assert.Equal("System.Int32 C<System.Int32>.Field", symbolInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Null(symbolInfo.Symbol); } [Fact] public void StaticClassWithinNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/Stat/*</bind>*/(); } } static class Stat { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("Stat", semanticInfo.CandidateSymbols[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.CandidateSymbols[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void StaticClassWithinNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new Stat()/*</bind>*/; } } static class Stat { } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Stat", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("Stat", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543534")] [Fact] public void InterfaceWithNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/X/*</bind>*/(); } } interface X { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InterfaceWithNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new X()/*</bind>*/; } } interface X { } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("X", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("X", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void TypeParameterWithNew() { string sourceCode = @" using System; class Program<T> { static void f() { object o = new /*<bind>*/T/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("T", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.TypeParameter, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void TypeParameterWithNew2() { string sourceCode = @" using System; class Program<T> { static void f() { object o = /*<bind>*/new T()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("T", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.TypeParameter, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Boxing, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("T", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void AbstractClassWithNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/X/*</bind>*/(); } } abstract class X { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("X", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MemberGroup.Length); } [Fact] public void AbstractClassWithNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new X()/*</bind>*/; } } abstract class X { } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("X", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MemberGroup.Length); } [Fact()] public void DynamicWithNew() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = new /*<bind>*/dynamic/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("dynamic", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact()] public void DynamicWithNew2() { string sourceCode = @" using System; class Program { static void Main(string[] args) { object o = /*<bind>*/new dynamic()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("dynamic", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind); Assert.Equal("System.Object", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.NoConversion, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_01() { // There must be exactly one user-defined conversion to a non-nullable integral type, // and there is. string sourceCode = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static int Main() { Conv C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 1; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitUserDefined, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Conv.implicit operator int(Conv)", semanticInfo.ImplicitConversion.Method.ToString()); Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_02() { // The specification requires that the user-defined conversion chosen be one // which converts to an integral or string type, but *not* a nullable integral type, // oddly enough. Since the only applicable user-defined conversion here would be the // lifted conversion from Conv? to int?, the resolution of the conversion fails // and this program produces an error. string sourceCode = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static int Main() { Conv? C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 1; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Conv?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Conv? C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_01() { string sourceCode = @" struct Conv { public static implicit operator int (Conv C) { return 1; } public static implicit operator int? (Conv? C) { return null; } public static int Main() { Conv C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 0; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SwitchGoverningImplicitUserDefined_Error_02() { string sourceCode = @" struct Conv { public static int Main() { Conv C = new Conv(); switch (/*<bind>*/C/*</bind>*/) { default: return 0; } } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode, parseOptions: TestOptions.Regular6); Assert.Equal("Conv", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("Conv", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Conv C", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_ObjectCreationExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/new MemberInitializerTest() { x = 1, y = 2 }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("MemberInitializerTest..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InitializerExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() /*<bind>*/{ x = 1, y = 2 }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_MemberInitializerAssignment_BinaryExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/x = 1/*</bind>*/, y = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_FieldAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/x/*</bind>*/ = 1, y = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_PropertyAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_TypeParameterBaseFieldAccess_IdentifierNameSyntax() { string sourceCode = @" public class Base { public Base() { } public int x; public int y { get; set; } public static void Main() { MemberInitializerTest<Base>.Goo(); } } public class MemberInitializerTest<T> where T : Base, new() { public static void Goo() { var i = new T() { /*<bind>*/x/*</bind>*/ = 1, y = 2 }; System.Console.WriteLine(i.x); System.Console.WriteLine(i.y); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 Base.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_NestedInitializer_InitializerExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public readonly MemberInitializerTest m = new MemberInitializerTest(); public static void Main() { var i = new Test() { m = /*<bind>*/{ x = 1, y = 2 }/*</bind>*/ }; System.Console.WriteLine(i.m.x); System.Console.WriteLine(i.m.y); } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_NestedInitializer_PropertyAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public readonly MemberInitializerTest m = new MemberInitializerTest(); public static void Main() { var i = new Test() { m = { x = 1, /*<bind>*/y/*</bind>*/ = 2 } }; System.Console.WriteLine(i.m.x); System.Console.WriteLine(i.m.y); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InaccessibleMember_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { protected int x; private int y { get; set; } internal int z; } public class Test { public static void Main() { var i = new MemberInitializerTest() { x = 1, /*<bind>*/y/*</bind>*/ = 2, z = 3 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MemberInitializerTest.y { get; set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_ReadOnlyPropertyAssign_IdentifierNameSyntax() { string sourceCode = @" public struct MemberInitializerTest { public readonly int x; public int y { get { return 0; } } } public struct Test { public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/y/*</bind>*/ = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.Int32 MemberInitializerTest.y { get; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_WriteOnlyPropertyAccess_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public int y { get; set; } } public class Test { public MemberInitializerTest m; public MemberInitializerTest Prop { set { m = value; } } public static void Main() { var i = new Test() { /*<bind>*/Prop/*</bind>*/ = { x = 1, y = 2 } }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAValue, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MemberInitializerTest Test.Prop { set; }", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Property, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_ErrorInitializerType_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public static void Main() { var i = new X() { /*<bind>*/x/*</bind>*/ = 0 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InvalidElementInitializer_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x, y; public static void Main() { var i = new MemberInitializerTest { x = 0, /*<bind>*/y/*</bind>*/++ }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.y", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_InvalidElementInitializer_InvocationExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/}; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_01() { string sourceCode = @" public class MemberInitializerTest { public int x; public MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() }; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_BadNamedAssignmentLeft_InvocationExpressionSyntax_02() { string sourceCode = @" public class MemberInitializerTest { public int x; public static MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { x = 0, /*<bind>*/Goo()/*</bind>*/ = new MemberInitializerTest() }; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("MemberInitializerTest", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("MemberInitializerTest", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAVariable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var symbol = semanticInfo.CandidateSymbols[0]; Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, symbol.Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_MethodGroupNamedAssignmentLeft_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { var i = new MemberInitializerTest() { /*<bind>*/Goo/*</bind>*/ }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("MemberInitializerTest MemberInitializerTest.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ObjectInitializer_DuplicateMemberInitializer_IdentifierNameSyntax() { string sourceCode = @" public class MemberInitializerTest { public int x; public static void Main() { var i = new MemberInitializerTest() { x = 1, /*<bind>*/x/*</bind>*/ = 2 }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 MemberInitializerTest.x", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Field, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = /*<bind>*/new B { 1, i, { 4L }, { 9 }, 3L }/*</bind>*/; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("B", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("B", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("B..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("B..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InitializerExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B /*<bind>*/{ 1, i, { 4L }, { 9 }, 3L }/*</bind>*/; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ElementInitializer_LiteralExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { /*<bind>*/1/*</bind>*/, i, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<LiteralExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.True(semanticInfo.IsCompileTimeConstant); Assert.Equal(1, semanticInfo.ConstantValue); } [Fact] public void CollectionInitializer_ElementInitializer_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { 1, /*<bind>*/i/*</bind>*/, { 4L }, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int64", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.ImplicitNumeric, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Int32 i", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ComplexElementInitializer_InitializerExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { 1, i, /*<bind>*/{ 4L }/*</bind>*/, { 9 }, 3L }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(long i) { list.Add(i); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ComplexElementInitializer_Empty_InitializerExpressionSyntax() { string sourceCode = @" using System.Collections.Generic; public class MemberInitializerTest { public List<int> y; public static void Main() { i = new MemberInitializerTest { y = { /*<bind>*/{ }/*</bind>*/ } }; // CS1920 } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_ComplexElementInitializer_AddMethodOverloadResolutionFailure() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var i = 2; B coll = new B { /*<bind>*/{ 1, 2 }/*</bind>*/ }; DisplayCollection(coll.GetEnumerator()); return 0; } public static void DisplayCollection(IEnumerator collection) { while (collection.MoveNext()) { Console.WriteLine(collection.Current); } } } public class B : IEnumerable { List<object> list = new List<object>(); public void Add(float i, int j) { list.Add(i); list.Add(j); } public void Add(int i, float j) { list.Add(i); list.Add(j); } public IEnumerator GetEnumerator() { for (int i = 0; i < list.Count; i++) yield return list[i]; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_Empty_InitializerExpressionSyntax() { string sourceCode = @" using System.Collections.Generic; public class MemberInitializerTest { public static void Main() { var i = new List<int>() /*<bind>*/{ }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_Nested_InitializerExpressionSyntax() { string sourceCode = @" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { var coll = new List<B> { new B(0) { list = new List<int>() { 1, 2, 3 } }, new B(1) { list = /*<bind>*/{ 2, 3 }/*</bind>*/ } }; DisplayCollection(coll); return 0; } public static void DisplayCollection(IEnumerable<B> collection) { foreach (var i in collection) { i.Display(); } } } public class B { public List<int> list = new List<int>(); public B() { } public B(int i) { list.Add(i); } public void Display() { foreach (var i in list) { Console.WriteLine(i); } } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InitializerTypeNotIEnumerable_InitializerExpressionSyntax() { string sourceCode = @" class MemberInitializerTest { public static int Main() { B coll = new B /*<bind>*/{ 1 }/*</bind>*/; return 0; } } class B { public B() { } } "; var semanticInfo = GetSemanticInfoForTest<InitializerExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InvalidInitializer_PostfixUnaryExpressionSyntax() { string sourceCode = @" public class MemberInitializerTest { public int y; public static void Main() { var i = new MemberInitializerTest { /*<bind>*/y++/*</bind>*/ }; } } "; var semanticInfo = GetSemanticInfoForTest<PostfixUnaryExpressionSyntax>(sourceCode); Assert.Equal("?", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void CollectionInitializer_InvalidInitializer_BinaryExpressionSyntax() { string sourceCode = @" using System.Collections.Generic; public class MemberInitializerTest { public int x; static MemberInitializerTest Goo() { return new MemberInitializerTest(); } public static void Main() { int y = 0; var i = new List<int> { 1, /*<bind>*/Goo().x = 1/*</bind>*/}; } } "; var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode); Assert.Equal("System.Int32", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Int32", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SimpleNameWithGenericTypeInAttribute() { string sourceCode = @" class Gen<T> { } class Gen2<T> : System.Attribute { } [/*<bind>*/Gen/*</bind>*/] [Gen2] public class Test { public static int Main() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Gen<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_SimpleNameWithGenericTypeInAttribute_02() { string sourceCode = @" class Gen<T> { } class Gen2<T> : System.Attribute { } [Gen] [/*<bind>*/Gen2/*</bind>*/] public class Test { public static int Main() { return 1; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("Gen2<T>", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("Gen2<T>", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotAnAttributeType, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen2<T>..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Gen2<T>..ctor()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_VarKeyword_LocalDeclaration() { string sourceCode = @" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { /*<bind>*/var/*</bind>*/ rand = new Random(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("System.Random", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("System.Random", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("System.Random", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_VarKeyword_FieldDeclaration() { string sourceCode = @" class Program { /*<bind>*/var/*</bind>*/ x = 1; } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_VarKeyword_MethodReturnType() { string sourceCode = @" class Program { /*<bind>*/var/*</bind>*/ Goo() {} } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("var", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.Type.TypeKind); Assert.Equal("var", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543860, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543860")] [Fact] public void SemanticInfo_InterfaceCreation_With_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = new /*<bind>*/InterfaceType/*</bind>*/(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")] [Fact] public void SemanticInfo_InterfaceArrayCreation_With_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = new /*<bind>*/InterfaceType/*</bind>*/[] { }; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("InterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = /*<bind>*/new InterfaceType()/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("CoClassType..ctor()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(546242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546242")] [Fact] public void SemanticInfo_InterfaceArrayCreation_With_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] interface InterfaceType { } public class Program { public static void Main() { var a = /*<bind>*/new InterfaceType[] { }/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<ArrayCreationExpressionSyntax>(sourceCode); Assert.Equal("InterfaceType[]", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType[]", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Array, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class GenericCoClassType<T, U> : NonGenericInterfaceType { public GenericCoClassType(U x) { Console.WriteLine(x); } } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(GenericCoClassType<int, string>))] public interface NonGenericInterfaceType { } public class MainClass { public static int Main() { var a = new /*<bind>*/NonGenericInterfaceType/*</bind>*/(""string""); return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("NonGenericInterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Generic_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class GenericCoClassType<T, U> : NonGenericInterfaceType { public GenericCoClassType(U x) { Console.WriteLine(x); } } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(GenericCoClassType<int, string>))] public interface NonGenericInterfaceType { } public class MainClass { public static int Main() { var a = /*<bind>*/new NonGenericInterfaceType(""string"")/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("NonGenericInterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("NonGenericInterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("GenericCoClassType<System.Int32, System.String>..ctor(System.String x)", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_IdentifierNameSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class Wrapper { private class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] public interface InterfaceType { } } public class MainClass { public static int Main() { var a = new Wrapper./*<bind>*/InterfaceType/*</bind>*/(); return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("Wrapper.InterfaceType", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Inaccessible_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; public class Wrapper { private class CoClassType : InterfaceType { } [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(CoClassType))] public interface InterfaceType { } } public class MainClass { public static int Main() { var a = /*<bind>*/new Wrapper.InterfaceType()/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("Wrapper.InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("Wrapper.InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.Inaccessible, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("Wrapper.CoClassType..ctor()", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal(1, semanticInfo.MethodGroup.Length); Assert.Equal("Wrapper.CoClassType..ctor()", semanticInfo.MethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax() { string sourceCode = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(int))] public interface InterfaceType { } public class MainClass { public static int Main() { var a = /*<bind>*/new InterfaceType()/*</bind>*/; return 0; } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("InterfaceType", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("InterfaceType", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("InterfaceType", semanticInfo.CandidateSymbols.First().Name); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void SemanticInfo_InterfaceCreation_With_Invalid_CoClass_ObjectCreationExpressionSyntax_2() { string sourceCode = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""00020810 - 0000 - 0000 - C000 - 000000000046"")] [CoClass(typeof(int))] public interface InterfaceType { } public class MainClass { public static int Main() { var a = new /*<bind>*/InterfaceType/*</bind>*/(); return 0; } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("InterfaceType", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(543593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543593")] [Fact] public void IncompletePropertyAccessStatement() { string sourceCode = @"class C { static void M() { var c = new { P = 0 }; /*<bind>*/c.P.Q/*</bind>*/ x; } }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Symbol); } [WorkItem(544449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544449")] [Fact] public void IndexerAccessorWithSyntaxErrors() { string sourceCode = @"public abstract int this[int i] ( { /*<bind>*/get/*</bind>*/; set; }"; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Null(semanticInfo.Symbol); } [WorkItem(545040, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545040")] [Fact] public void OmittedArraySizeExpressionSyntax() { string sourceCode = @" class A { public static void Main() { var arr = new int[5][ ]; } } "; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.First(); var node = tree.GetCompilationUnitRoot().DescendantNodes().OfType<OmittedArraySizeExpressionSyntax>().Last(); var model = compilation.GetSemanticModel(tree); var typeInfo = model.GetTypeInfo(node); // Ensure that this doesn't throw. Assert.NotEqual(default, typeInfo); } [WorkItem(11451, "DevDiv_Projects/Roslyn")] [Fact] public void InvalidNewInterface() { string sourceCode = @" using System; public class Program { static void Main(string[] args) { var c = new /*<bind>*/IFormattable/*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("System.IFormattable", sortedCandidates[0].ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, sortedCandidates[0].Kind); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void InvalidNewInterface2() { string sourceCode = @" using System; public class Program { static void Main(string[] args) { var c = /*<bind>*/new IFormattable()/*</bind>*/ } } "; var semanticInfo = GetSemanticInfoForTest<ObjectCreationExpressionSyntax>(sourceCode); Assert.Equal("System.IFormattable", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.Type.TypeKind); Assert.Equal("System.IFormattable", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Interface, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.NotCreatable, semanticInfo.CandidateReason); Assert.Equal(1, semanticInfo.CandidateSymbols.Length); Assert.Equal("System.IFormattable", semanticInfo.CandidateSymbols.First().ToTestDisplayString()); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(545376, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545376")] [Fact] public void AssignExprInExternEvent() { string sourceCode = @" struct Class1 { public event EventHandler e2; extern public event EventHandler e1 = /*<bind>*/ e2 = new EventHandler(this, new EventArgs()) = null /*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<AssignmentExpressionSyntax>(sourceCode); Assert.NotNull(semanticInfo.Type); } [Fact, WorkItem(531416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531416")] public void VarEvent() { var semanticInfo = GetSemanticInfoForTest<ExpressionSyntax>(@" event /*<bind>*/var/*</bind>*/ goo; "); Assert.True(((ITypeSymbol)semanticInfo.Type).IsErrorType()); } [WorkItem(546083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546083")] [Fact] public void GenericMethodAssignedToDelegateWithDeclErrors() { string sourceCode = @" delegate void D(void t); class C { void M<T>(T t) { } D d = /*<bind>*/M/*</bind>*/; } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Utils.CheckSymbol(semanticInfo.CandidateSymbols.Single(), "void C.M<T>(T t)"); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Null(semanticInfo.Type); Utils.CheckSymbol(semanticInfo.ConvertedType, "D"); } [WorkItem(545992, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545992")] [Fact] public void TestSemanticInfoForMembersOfCyclicBase() { string sourceCode = @" using System; using System.Collections; class B : C { } class C : B { static void Main() { } void Goo(int x) { /*<bind>*/(this).Goo(1)/*</bind>*/; } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("System.Void", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("System.Void", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("void C.Goo(System.Int32 x)", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(610975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610975")] [Fact] public void AttributeOnTypeParameterWithSameName() { string source = @" class C<[T(a: 1)]T> { } "; var comp = CreateCompilation(source); comp.GetParseDiagnostics().Verify(); // Syntactically correct. var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var argumentSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AttributeArgumentSyntax>().Single(); var argumentNameSyntax = argumentSyntax.NameColon.Name; var info = model.GetSymbolInfo(argumentNameSyntax); } private void CommonTestParenthesizedMethodGroup(string sourceCode) { var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal("void C.Goo()", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(1, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.OrderBy(s => s.ToTestDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("void C.Goo()", sortedMethodGroup[0].ToTestDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] [WorkItem(576966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576966")] public void TestParenthesizedMethodGroup() { string sourceCode = @" class C { void Goo() { /*<bind>*/Goo/*</bind>*/(); } }"; CommonTestParenthesizedMethodGroup(sourceCode); sourceCode = @" class C { void Goo() { ((/*<bind>*/Goo/*</bind>*/))(); } }"; CommonTestParenthesizedMethodGroup(sourceCode); } [WorkItem(531549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531549")] [Fact()] public void Bug531549() { var sourceCode1 = @" class C1 { void Goo() { int x = 2; long? z = /*<bind>*/x/*</bind>*/; } }"; var sourceCode2 = @" class C2 { void Goo() { long? y = /*<bind>*/x/*</bind>*/; int x = 2; } }"; var compilation = CreateCompilation(new[] { sourceCode1, sourceCode2 }); for (int i = 0; i < 2; i++) { var tree = compilation.SyntaxTrees[i]; var model = compilation.GetSemanticModel(tree); IdentifierNameSyntax syntaxToBind = GetSyntaxNodeOfTypeForBinding<IdentifierNameSyntax>(GetSyntaxNodeList(tree)); var info1 = model.GetTypeInfo(syntaxToBind); Assert.NotEqual(default, info1); Assert.Equal("System.Int32", info1.Type.ToTestDisplayString()); } } [Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")] public void ObjectCreation1() { var compilation = CreateCompilation( @" using System.Collections; namespace Test { class C : IEnumerable { public int P1 { get; set; } public void Add(int x) { } public static void Main() { var x1 = new C(); var x2 = new C() {P1 = 1}; var x3 = new C() {1, 2}; } public static void Main2() { var x1 = new Test.C(); var x2 = new Test.C() {P1 = 1}; var x3 = new Test.C() {1, 2}; } public IEnumerator GetEnumerator() { return null; } } }"); compilation.VerifyDiagnostics(); SyntaxTree tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var nodes = (from node in tree.GetRoot().DescendantNodes() select (node as ObjectCreationExpressionSyntax)). Where(node => (object)node != null).ToArray(); for (int i = 0; i < 6; i++) { ObjectCreationExpressionSyntax creation = nodes[i]; SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type); Assert.Equal("Test.C", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var memberGroup = model.GetMemberGroup(creation.Type); Assert.Equal(0, memberGroup.Length); TypeInfo typeInfo = model.GetTypeInfo(creation.Type); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); var conv = model.GetConversion(creation.Type); Assert.True(conv.IsIdentity); symbolInfo = model.GetSymbolInfo(creation); Assert.Equal("Test.C..ctor()", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); memberGroup = model.GetMemberGroup(creation); Assert.Equal(1, memberGroup.Length); Assert.Equal("Test.C..ctor()", memberGroup[0].ToTestDisplayString()); typeInfo = model.GetTypeInfo(creation); Assert.Equal("Test.C", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Test.C", typeInfo.ConvertedType.ToTestDisplayString()); conv = model.GetConversion(creation); Assert.True(conv.IsIdentity); } } [Fact, WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")] public void ObjectCreation2() { var compilation = CreateCompilation( @" using System.Collections; namespace Test { public class CoClassI : I { public int P1 { get; set; } public void Add(int x) { } public IEnumerator GetEnumerator() { return null; } } [System.Runtime.InteropServices.ComImport, System.Runtime.InteropServices.CoClass(typeof(CoClassI))] [System.Runtime.InteropServices.Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] public interface I : IEnumerable { int P1 { get; set; } void Add(int x); } class C { public static void Main() { var x1 = new I(); var x2 = new I() {P1 = 1}; var x3 = new I() {1, 2}; } public static void Main2() { var x1 = new Test.I(); var x2 = new Test.I() {P1 = 1}; var x3 = new Test.I() {1, 2}; } } } "); compilation.VerifyDiagnostics(); SyntaxTree tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var nodes = (from node in tree.GetRoot().DescendantNodes() select (node as ObjectCreationExpressionSyntax)). Where(node => (object)node != null).ToArray(); for (int i = 0; i < 6; i++) { ObjectCreationExpressionSyntax creation = nodes[i]; SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type); Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var memberGroup = model.GetMemberGroup(creation.Type); Assert.Equal(0, memberGroup.Length); TypeInfo typeInfo = model.GetTypeInfo(creation.Type); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); var conv = model.GetConversion(creation.Type); Assert.True(conv.IsIdentity); symbolInfo = model.GetSymbolInfo(creation); Assert.Equal("Test.CoClassI..ctor()", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); memberGroup = model.GetMemberGroup(creation); Assert.Equal(1, memberGroup.Length); Assert.Equal("Test.CoClassI..ctor()", memberGroup[0].ToTestDisplayString()); typeInfo = model.GetTypeInfo(creation); Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString()); conv = model.GetConversion(creation); Assert.True(conv.IsIdentity); } } [ConditionalFact(typeof(DesktopOnly))] [WorkItem(665920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/665920")] public void ObjectCreation3() { var pia = CreateCompilation( @" using System; using System.Collections; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] namespace Test { [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b5827A"")] public class CoClassI : I { public int P1 { get; set; } public void Add(int x) { } public IEnumerator GetEnumerator() { return null; } } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58279"")] [System.Runtime.InteropServices.CoClass(typeof(CoClassI))] public interface I : IEnumerable { int P1 { get; set; } void Add(int x); } } ", options: TestOptions.ReleaseDll); pia.VerifyDiagnostics(); var compilation = CreateCompilation( @" namespace Test { class C { public static void Main() { var x1 = new I(); var x2 = new I() {P1 = 1}; var x3 = new I() {1, 2}; } public static void Main2() { var x1 = new Test.I(); var x2 = new Test.I() {P1 = 1}; var x3 = new Test.I() {1, 2}; } } }", references: new[] { new CSharpCompilationReference(pia, embedInteropTypes: true) }); compilation.VerifyDiagnostics(); SyntaxTree tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var nodes = (from node in tree.GetRoot().DescendantNodes() select (node as ObjectCreationExpressionSyntax)). Where(node => (object)node != null).ToArray(); for (int i = 0; i < 6; i++) { ObjectCreationExpressionSyntax creation = nodes[i]; SymbolInfo symbolInfo = model.GetSymbolInfo(creation.Type); Assert.Equal("Test.I", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); var memberGroup = model.GetMemberGroup(creation.Type); Assert.Equal(0, memberGroup.Length); TypeInfo typeInfo = model.GetTypeInfo(creation.Type); Assert.Null(typeInfo.Type); Assert.Null(typeInfo.ConvertedType); var conv = model.GetConversion(creation.Type); Assert.True(conv.IsIdentity); symbolInfo = model.GetSymbolInfo(creation); Assert.Null(symbolInfo.Symbol); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); memberGroup = model.GetMemberGroup(creation); Assert.Equal(0, memberGroup.Length); typeInfo = model.GetTypeInfo(creation); Assert.Equal("Test.I", typeInfo.Type.ToTestDisplayString()); Assert.Equal("Test.I", typeInfo.ConvertedType.ToTestDisplayString()); conv = model.GetConversion(creation); Assert.True(conv.IsIdentity); } } /// <summary> /// SymbolInfo and TypeInfo should implement IEquatable&lt;T&gt;. /// </summary> [WorkItem(792647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/792647")] [Fact] public void ImplementsIEquatable() { string sourceCode = @"class C { object F() { return this; } }"; var compilation = CreateCompilation(sourceCode); var tree = compilation.SyntaxTrees.First(); var expr = (ExpressionSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.ThisKeyword).Parent; var model = compilation.GetSemanticModel(tree); var symbolInfo1 = model.GetSymbolInfo(expr); var symbolInfo2 = model.GetSymbolInfo(expr); var symbolComparer = (IEquatable<SymbolInfo>)symbolInfo1; Assert.True(symbolComparer.Equals(symbolInfo2)); var typeInfo1 = model.GetTypeInfo(expr); var typeInfo2 = model.GetTypeInfo(expr); var typeComparer = (IEquatable<TypeInfo>)typeInfo1; Assert.True(typeComparer.Equals(typeInfo2)); } [Fact] public void ConditionalAccessErr001() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = """"qqq"""" ?/*<bind>*/.ToString().Length/*</bind>*/.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberAccessExpressionSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccessErr002() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = ""qqq"" ?/*<bind>*/.ToString/*</bind>*/.Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<MemberBindingExpressionSyntax>(sourceCode); Assert.Null(semanticInfo.Type); Assert.Null(semanticInfo.ConvertedType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, semanticInfo.CandidateReason); Assert.Equal(2, semanticInfo.CandidateSymbols.Length); var sortedCandidates = semanticInfo.CandidateSymbols.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("string.ToString()", sortedCandidates[0].ToDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[0].Kind); Assert.Equal("string.ToString(System.IFormatProvider)", sortedCandidates[1].ToDisplayString()); Assert.Equal(SymbolKind.Method, sortedCandidates[1].Kind); Assert.Equal(2, semanticInfo.MethodGroup.Length); var sortedMethodGroup = semanticInfo.MethodGroup.AsEnumerable().OrderBy(s => s.ToDisplayString(), StringComparer.Ordinal).ToArray(); Assert.Equal("string.ToString()", sortedMethodGroup[0].ToDisplayString()); Assert.Equal("string.ToString(System.IFormatProvider)", sortedMethodGroup[1].ToDisplayString()); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess001() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = ""qqq"" ?/*<bind>*/.ToString()/*</bind>*/.Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<InvocationExpressionSyntax>(sourceCode); Assert.Equal("string", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("string", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.ToString()", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess002() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString().Length ?.ToString(); var dummy2 = ""qqq"" ?.ToString()./*<bind>*/Length/*</bind>*/.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess003() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null)?.ToString()./*<bind>*/Length/*</bind>*/?.ToString(); var dummy2 = ""qqq""?.ToString().Length.ToString(); var dummy3 = 1.ToString()?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("?", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Error, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess004() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString()./*<bind>*/Length/*</bind>*/ .ToString(); var dummy2 = ""qqq"" ?.ToString().Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("int", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("int", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.Length", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact] public void ConditionalAccess005() { string sourceCode = @" public class C { static void Main() { var dummy1 = ((string)null) ?.ToString() ?/*<bind>*/[1]/*</bind>*/ .ToString(); var dummy2 = ""qqq"" ?.ToString().Length.ToString(); var dummy3 = 1.ToString() ?.ToString().Length.ToString(); } } "; var semanticInfo = GetSemanticInfoForTest<ElementBindingExpressionSyntax>(sourceCode); Assert.Equal("char", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.Type.TypeKind); Assert.Equal("char", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Struct, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("string.this[int]", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.Property, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(998050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998050")] public void Bug998050() { var comp = CreateCompilation(@" class BaselineLog {} public static BaselineLog Log { get { } }= new /*<bind>*/BaselineLog/*</bind>*/(); ", parseOptions: TestOptions.Regular); var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(comp); Assert.Null(semanticInfo.Type); Assert.Equal("BaselineLog", semanticInfo.Symbol.ToDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(982479, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/982479")] public void Bug982479() { const string sourceCode = @" class C { static void Main() { new C { Dynamic = { /*<bind>*/Name/*</bind>*/ = 1 } }; } public dynamic Dynamic; } class Name { } "; var semanticInfo = GetSemanticInfoForTest<IdentifierNameSyntax>(sourceCode); Assert.Equal("dynamic", semanticInfo.Type.ToDisplayString()); Assert.Equal(TypeKind.Dynamic, semanticInfo.Type.TypeKind); Assert.Equal("dynamic", semanticInfo.ConvertedType.ToDisplayString()); Assert.Equal(TypeKind.Dynamic, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Null(semanticInfo.Symbol); Assert.Equal(CandidateReason.None, semanticInfo.CandidateReason); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [Fact, WorkItem(1084693, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084693")] public void Bug1084693() { const string sourceCode = @" using System; public class C { public Func<Func<C, C>, C> Select; public Func<Func<C, bool>, C> Where => null; public void M() { var e = from i in this where true select true?i:i; } }"; var compilation = CreateCompilation(sourceCode); compilation.VerifyDiagnostics(); var tree = compilation.SyntaxTrees[0]; var semanticModel = compilation.GetSemanticModel(tree); string[] expectedNames = { null, "Where", "Select" }; int i = 0; foreach (var qc in tree.GetRoot().DescendantNodes().OfType<QueryClauseSyntax>()) { var infoSymbol = semanticModel.GetQueryClauseInfo(qc).OperationInfo.Symbol; Assert.Equal(expectedNames[i++], infoSymbol?.Name); } var qe = tree.GetRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single(); var infoSymbol2 = semanticModel.GetSymbolInfo(qe.Body.SelectOrGroup).Symbol; Assert.Equal(expectedNames[i++], infoSymbol2.Name); } [Fact] public void TestIncompleteMember() { // Note: binding information in an incomplete member is not available. // When https://github.com/dotnet/roslyn/issues/7536 is fixed this test // will have to be updated. string sourceCode = @" using System; class Program { public /*<bind>*/K/*</bind>*/ } class K { } "; var semanticInfo = GetSemanticInfoForTest(sourceCode); Assert.Equal("K", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.Type.TypeKind); Assert.Equal("K", semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(TypeKind.Class, semanticInfo.ConvertedType.TypeKind); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); Assert.Equal("K", semanticInfo.Symbol.ToTestDisplayString()); Assert.Equal(SymbolKind.NamedType, semanticInfo.Symbol.Kind); Assert.Equal(0, semanticInfo.CandidateSymbols.Length); Assert.Equal(0, semanticInfo.MethodGroup.Length); Assert.False(semanticInfo.IsCompileTimeConstant); } [WorkItem(18763, "https://github.com/dotnet/roslyn/issues/18763")] [Fact] public void AttributeArgumentLambdaThis() { string source = @"class C { [X(() => this._Y)] public void Z() { } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var syntax = tree.GetCompilationUnitRoot().DescendantNodes().Single(n => n.Kind() == SyntaxKind.ThisExpression); var info = model.GetSemanticInfoSummary(syntax); Assert.Equal("C", info.Type.Name); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/Symbols/ITypeSymbol.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; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a type. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface ITypeSymbol : INamespaceOrTypeSymbol { /// <summary> /// An enumerated value that identifies whether this type is an array, pointer, enum, and so on. /// </summary> TypeKind TypeKind { get; } /// <summary> /// The declared base type of this type, or null. The object type, interface types, /// and pointer types do not have a base type. The base type of a type parameter /// is its effective base class. /// </summary> INamedTypeSymbol? BaseType { get; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. This does /// include the interfaces declared as constraints on type parameters. /// </summary> ImmutableArray<INamedTypeSymbol> Interfaces { get; } /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). This also is the effective /// interface set of a type parameter. Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt;. /// </summary> ImmutableArray<INamedTypeSymbol> AllInterfaces { get; } /// <summary> /// True if this type is known to be a reference type. It is never the case that /// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type /// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false. /// </summary> bool IsReferenceType { get; } /// <summary> /// True if this type is known to be a value type. It is never the case that /// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type /// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false. /// </summary> bool IsValueType { get; } /// <summary> /// Is this a symbol for an anonymous type (including anonymous VB delegate). /// </summary> bool IsAnonymousType { get; } /// <summary> /// Is this a symbol for a tuple . /// </summary> bool IsTupleType { get; } /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> bool IsNativeIntegerType { get; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then <see cref="OriginalDefinition"/> gets the original symbol as it was defined in /// source or metadata. /// </summary> new ITypeSymbol OriginalDefinition { get; } /// <summary> /// An enumerated value that identifies certain 'special' types such as <see cref="System.Object"/>. /// Returns <see cref="Microsoft.CodeAnalysis.SpecialType.None"/> if the type is not special. /// </summary> SpecialType SpecialType { get; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> ISymbol? FindImplementationForInterfaceMember(ISymbol interfaceMember); /// <summary> /// True if the type is ref-like, meaning it follows rules similar to CLR by-ref variables. False if the type /// is not ref-like or if the language has no concept of ref-like types. /// </summary> /// <remarks> /// <see cref="Span{T}" /> is a commonly used ref-like type. /// </remarks> bool IsRefLikeType { get; } /// <summary> /// True if the type is unmanaged according to language rules. False if managed or if the language /// has no concept of unmanaged types. /// </summary> bool IsUnmanagedType { get; } /// <summary> /// True if the type is readonly. /// </summary> bool IsReadOnly { get; } /// <summary> /// True if the type is a record. /// </summary> bool IsRecord { get; } /// <summary> /// Converts an <c>ITypeSymbol</c> and a nullable flow state to a string representation. /// </summary> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="format">Format or null for the default.</param> /// <returns>A formatted string representation of the symbol with the given nullability.</returns> string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null); /// <summary> /// Converts a symbol to an array of string parts, each of which has a kind. Useful /// for colorizing the display string. /// </summary> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="format">Format or null for the default.</param> /// <returns>A read-only array of string parts.</returns> ImmutableArray<SymbolDisplayPart> ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null); /// <summary> /// Converts a symbol to a string that can be displayed to the user. May be tailored to a /// specific location in the source code. /// </summary> /// <param name="semanticModel">Binding information (for determining names appropriate to /// the context).</param> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="position">A position in the source code (context).</param> /// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param> /// <returns>A formatted string that can be displayed to the user.</returns> string ToMinimalDisplayString( SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat? format = null); /// <summary> /// Convert a symbol to an array of string parts, each of which has a kind. May be tailored /// to a specific location in the source code. Useful for colorizing the display string. /// </summary> /// <param name="semanticModel">Binding information (for determining names appropriate to /// the context).</param> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="position">A position in the source code (context).</param> /// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param> /// <returns>A read-only array of string parts.</returns> ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat? format = null); /// <summary> /// Nullable annotation associated with the type, or <see cref="NullableAnnotation.None"/> if there are none. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns the same type as this type but with the given nullable annotation. /// </summary> /// <param name="nullableAnnotation">The nullable annotation to use</param> ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation); } // Intentionally not extension methods. We don't want them ever be called for symbol classes // Once Default Interface Implementations are supported, we can move these methods into the interface. internal static class ITypeSymbolHelpers { internal static bool IsNullableType([NotNullWhen(returnValue: true)] ITypeSymbol? typeOpt) { return typeOpt?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; } internal static bool IsNullableOfBoolean([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return IsNullableType(type) && IsBooleanType(GetNullableUnderlyingType(type)); } internal static ITypeSymbol GetNullableUnderlyingType(ITypeSymbol type) { Debug.Assert(IsNullableType(type)); return ((INamedTypeSymbol)type).TypeArguments[0]; } internal static bool IsBooleanType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType == SpecialType.System_Boolean; } internal static bool IsObjectType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType == SpecialType.System_Object; } internal static bool IsSignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType.IsSignedIntegralType() == true; } internal static bool IsUnsignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType.IsUnsignedIntegralType() == true; } internal static bool IsNumericType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType.IsNumericType() == true; } internal static ITypeSymbol? GetEnumUnderlyingType(ITypeSymbol? type) { return (type as INamedTypeSymbol)?.EnumUnderlyingType; } [return: NotNullIfNotNull(parameterName: "type")] internal static ITypeSymbol? GetEnumUnderlyingTypeOrSelf(ITypeSymbol? type) { return GetEnumUnderlyingType(type) ?? type; } internal static bool IsDynamicType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.Kind == SymbolKind.DynamicType; } } }
// 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; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a type. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface ITypeSymbol : INamespaceOrTypeSymbol { /// <summary> /// An enumerated value that identifies whether this type is an array, pointer, enum, and so on. /// </summary> TypeKind TypeKind { get; } /// <summary> /// The declared base type of this type, or null. The object type, interface types, /// and pointer types do not have a base type. The base type of a type parameter /// is its effective base class. /// </summary> INamedTypeSymbol? BaseType { get; } /// <summary> /// Gets the set of interfaces that this type directly implements. This set does not include /// interfaces that are base interfaces of directly implemented interfaces. This does /// include the interfaces declared as constraints on type parameters. /// </summary> ImmutableArray<INamedTypeSymbol> Interfaces { get; } /// <summary> /// The list of all interfaces of which this type is a declared subtype, excluding this type /// itself. This includes all declared base interfaces, all declared base interfaces of base /// types, and all declared base interfaces of those results (recursively). This also is the effective /// interface set of a type parameter. Each result /// appears exactly once in the list. This list is topologically sorted by the inheritance /// relationship: if interface type A extends interface type B, then A precedes B in the /// list. This is not quite the same as "all interfaces of which this type is a proper /// subtype" because it does not take into account variance: AllInterfaces for /// IEnumerable&lt;string&gt; will not include IEnumerable&lt;object&gt;. /// </summary> ImmutableArray<INamedTypeSymbol> AllInterfaces { get; } /// <summary> /// True if this type is known to be a reference type. It is never the case that /// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type /// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false. /// </summary> bool IsReferenceType { get; } /// <summary> /// True if this type is known to be a value type. It is never the case that /// <see cref="IsReferenceType"/> and <see cref="IsValueType"/> both return true. However, for an unconstrained type /// parameter, <see cref="IsReferenceType"/> and <see cref="IsValueType"/> will both return false. /// </summary> bool IsValueType { get; } /// <summary> /// Is this a symbol for an anonymous type (including anonymous VB delegate). /// </summary> bool IsAnonymousType { get; } /// <summary> /// Is this a symbol for a tuple . /// </summary> bool IsTupleType { get; } /// <summary> /// True if the type represents a native integer. In C#, the types represented /// by language keywords 'nint' and 'nuint'. /// </summary> bool IsNativeIntegerType { get; } /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then <see cref="OriginalDefinition"/> gets the original symbol as it was defined in /// source or metadata. /// </summary> new ITypeSymbol OriginalDefinition { get; } /// <summary> /// An enumerated value that identifies certain 'special' types such as <see cref="System.Object"/>. /// Returns <see cref="Microsoft.CodeAnalysis.SpecialType.None"/> if the type is not special. /// </summary> SpecialType SpecialType { get; } /// <summary> /// Returns the corresponding symbol in this type or a base type that implements /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists /// (which might be either because this type doesn't implement the container of /// interfaceMember, or this type doesn't supply a member that successfully implements /// interfaceMember). /// </summary> /// <param name="interfaceMember"> /// Must be a non-null interface property, method, or event. /// </param> ISymbol? FindImplementationForInterfaceMember(ISymbol interfaceMember); /// <summary> /// True if the type is ref-like, meaning it follows rules similar to CLR by-ref variables. False if the type /// is not ref-like or if the language has no concept of ref-like types. /// </summary> /// <remarks> /// <see cref="Span{T}" /> is a commonly used ref-like type. /// </remarks> bool IsRefLikeType { get; } /// <summary> /// True if the type is unmanaged according to language rules. False if managed or if the language /// has no concept of unmanaged types. /// </summary> bool IsUnmanagedType { get; } /// <summary> /// True if the type is readonly. /// </summary> bool IsReadOnly { get; } /// <summary> /// True if the type is a record. /// </summary> bool IsRecord { get; } /// <summary> /// Converts an <c>ITypeSymbol</c> and a nullable flow state to a string representation. /// </summary> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="format">Format or null for the default.</param> /// <returns>A formatted string representation of the symbol with the given nullability.</returns> string ToDisplayString(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null); /// <summary> /// Converts a symbol to an array of string parts, each of which has a kind. Useful /// for colorizing the display string. /// </summary> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="format">Format or null for the default.</param> /// <returns>A read-only array of string parts.</returns> ImmutableArray<SymbolDisplayPart> ToDisplayParts(NullableFlowState topLevelNullability, SymbolDisplayFormat? format = null); /// <summary> /// Converts a symbol to a string that can be displayed to the user. May be tailored to a /// specific location in the source code. /// </summary> /// <param name="semanticModel">Binding information (for determining names appropriate to /// the context).</param> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="position">A position in the source code (context).</param> /// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param> /// <returns>A formatted string that can be displayed to the user.</returns> string ToMinimalDisplayString( SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat? format = null); /// <summary> /// Convert a symbol to an array of string parts, each of which has a kind. May be tailored /// to a specific location in the source code. Useful for colorizing the display string. /// </summary> /// <param name="semanticModel">Binding information (for determining names appropriate to /// the context).</param> /// <param name="topLevelNullability">The top-level nullability to use for formatting.</param> /// <param name="position">A position in the source code (context).</param> /// <param name="format">Formatting rules - null implies <see cref="SymbolDisplayFormat.MinimallyQualifiedFormat"/></param> /// <returns>A read-only array of string parts.</returns> ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, NullableFlowState topLevelNullability, int position, SymbolDisplayFormat? format = null); /// <summary> /// Nullable annotation associated with the type, or <see cref="NullableAnnotation.None"/> if there are none. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns the same type as this type but with the given nullable annotation. /// </summary> /// <param name="nullableAnnotation">The nullable annotation to use</param> ITypeSymbol WithNullableAnnotation(NullableAnnotation nullableAnnotation); } // Intentionally not extension methods. We don't want them ever be called for symbol classes // Once Default Interface Implementations are supported, we can move these methods into the interface. internal static class ITypeSymbolHelpers { internal static bool IsNullableType([NotNullWhen(returnValue: true)] ITypeSymbol? typeOpt) { return typeOpt?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T; } internal static bool IsNullableOfBoolean([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return IsNullableType(type) && IsBooleanType(GetNullableUnderlyingType(type)); } internal static ITypeSymbol GetNullableUnderlyingType(ITypeSymbol type) { Debug.Assert(IsNullableType(type)); return ((INamedTypeSymbol)type).TypeArguments[0]; } internal static bool IsBooleanType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType == SpecialType.System_Boolean; } internal static bool IsObjectType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType == SpecialType.System_Object; } internal static bool IsSignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType.IsSignedIntegralType() == true; } internal static bool IsUnsignedIntegralType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType.IsUnsignedIntegralType() == true; } internal static bool IsNumericType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.SpecialType.IsNumericType() == true; } internal static ITypeSymbol? GetEnumUnderlyingType(ITypeSymbol? type) { return (type as INamedTypeSymbol)?.EnumUnderlyingType; } [return: NotNullIfNotNull(parameterName: "type")] internal static ITypeSymbol? GetEnumUnderlyingTypeOrSelf(ITypeSymbol? type) { return GetEnumUnderlyingType(type) ?? type; } internal static bool IsDynamicType([NotNullWhen(returnValue: true)] ITypeSymbol? type) { return type?.Kind == SymbolKind.DynamicType; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/CSharpTest/Diagnostics/RemoveInKeyword/RemoveInKeywordCodeFixProviderTests.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.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveInKeyword; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveInKeyword { [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveInKeyword)] public class RemoveInKeywordCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveInKeywordCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new RemoveInKeywordCodeFixProvider()); [Fact] public async Task TestRemoveInKeyword() { await TestInRegularAndScript1Async( @"class Class { void M(int i) { } void N(int i) { M(in [|i|]); } }", @"class Class { void M(int i) { } void N(int i) { M(i); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments1() { await TestInRegularAndScript1Async( @"class Class { void M(int i, string s) { } void N(int i, string s) { M(in [|i|], s); } }", @"class Class { void M(int i, string s) { } void N(int i, string s) { M(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments2() { await TestInRegularAndScript1Async( @"class Class { void M(int i, int j) { } void N(int i, int j) { M(in [|i|], in j); } }", @"class Class { void M(int i, int j) { } void N(int i, int j) { M(i, in j); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArgumentsWithDifferentRefKinds() { await TestInRegularAndScript1Async( @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, in [|s|]); } }", @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, s); } }"); } [Fact] public async Task TestDontRemoveInKeyword() { await TestMissingInRegularAndScriptAsync( @"class Class { void M(in int i) { } void N(int i) { M(in [|i|]); } }"); } [Theory] [InlineData("in [|i|]", "i")] [InlineData(" in [|i|]", " i")] [InlineData("/* start */in [|i|]", "/* start */i")] [InlineData("/* start */ in [|i|]", "/* start */ i")] [InlineData( "/* start */ in [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */in /* middle */ [|i|] /* end */", "/* start */i /* end */")] public async Task TestRemoveInKeywordWithTrivia(string original, string expected) { await TestInRegularAndScript1Async( $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({original}); }} }}", $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({expected}); }} }}"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument1() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(i, s); } void N3(int i, string s) { M1(i); M2(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument2() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(in i, s); } void N3(int i, string s) { M1(i); M2(in i, s); } }"); } } }
// 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.CodeFixes; using Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveInKeyword; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveInKeyword { [Trait(Traits.Feature, Traits.Features.CodeActionsRemoveInKeyword)] public class RemoveInKeywordCodeFixProviderTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public RemoveInKeywordCodeFixProviderTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new RemoveInKeywordCodeFixProvider()); [Fact] public async Task TestRemoveInKeyword() { await TestInRegularAndScript1Async( @"class Class { void M(int i) { } void N(int i) { M(in [|i|]); } }", @"class Class { void M(int i) { } void N(int i) { M(i); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments1() { await TestInRegularAndScript1Async( @"class Class { void M(int i, string s) { } void N(int i, string s) { M(in [|i|], s); } }", @"class Class { void M(int i, string s) { } void N(int i, string s) { M(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArguments2() { await TestInRegularAndScript1Async( @"class Class { void M(int i, int j) { } void N(int i, int j) { M(in [|i|], in j); } }", @"class Class { void M(int i, int j) { } void N(int i, int j) { M(i, in j); } }"); } [Fact] public async Task TestRemoveInKeywordMultipleArgumentsWithDifferentRefKinds() { await TestInRegularAndScript1Async( @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, in [|s|]); } }", @"class Class { void M(in int i, string s) { } void N(int i, string s) { M(in i, s); } }"); } [Fact] public async Task TestDontRemoveInKeyword() { await TestMissingInRegularAndScriptAsync( @"class Class { void M(in int i) { } void N(int i) { M(in [|i|]); } }"); } [Theory] [InlineData("in [|i|]", "i")] [InlineData(" in [|i|]", " i")] [InlineData("/* start */in [|i|]", "/* start */i")] [InlineData("/* start */ in [|i|]", "/* start */ i")] [InlineData( "/* start */ in [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */ in /* middle */ [|i|] /* end */", "/* start */ i /* end */")] [InlineData( "/* start */in /* middle */ [|i|] /* end */", "/* start */i /* end */")] public async Task TestRemoveInKeywordWithTrivia(string original, string expected) { await TestInRegularAndScript1Async( $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({original}); }} }}", $@"class App {{ void M(int i) {{ }} void N(int i) {{ M({expected}); }} }}"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument1() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(i, s); } void N3(int i, string s) { M1(i); M2(i, s); } }"); } [Fact] public async Task TestRemoveInKeywordFixAllInDocument2() { await TestInRegularAndScript1Async( @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(in {|FixAllInDocument:i|}); } void N2(int i, string s) { M2(in i, in s); } void N3(int i, string s) { M1(in i); M2(in i, in s); } }", @"class Class { void M1(int i) { } void M2(in int i, string s) { } void N1(int i) { M1(i); } void N2(int i, string s) { M2(in i, s); } void N3(int i, string s) { M1(i); M2(in i, s); } }"); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Statements/ElseKeywordRecommender.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 Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Else" keyword for the statement context. ''' </summary> Friend Class ElseKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken Dim parent = targetToken.GetAncestor(Of SingleLineIfStatementSyntax)() If parent IsNot Nothing AndAlso Not parent.Statements.IsEmpty() Then If context.IsFollowingCompleteStatement(Of SingleLineIfStatementSyntax)(Function(ifStatement) ifStatement.Statements.Last()) Then Return ImmutableArray.Create(New RecommendedKeyword("Else", VBFeaturesResources.Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True)) End If End If If context.IsSingleLineStatementContext AndAlso IsDirectlyInIfOrElseIf(context) Then Return ImmutableArray.Create(New RecommendedKeyword("Else", VBFeaturesResources.Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True)) End If ' Determine whether we can offer "Else" after "Case" in a Select block. If targetToken.Kind = SyntaxKind.CaseKeyword AndAlso targetToken.Parent.IsKind(SyntaxKind.CaseStatement) Then ' Next, grab the parenting "Select" block and ensure that it doesn't have any Case Else statements Dim selectBlock = targetToken.GetAncestor(Of SelectBlockSyntax)() If selectBlock IsNot Nothing AndAlso Not selectBlock.CaseBlocks.Any(Function(cb) cb.CaseStatement.Kind = SyntaxKind.CaseElseStatement) Then ' Finally, ensure this case statement is the last one in the parenting "Select" block. If selectBlock.CaseBlocks.Last().CaseStatement Is targetToken.Parent Then Return ImmutableArray.Create(New RecommendedKeyword("Else", VBFeaturesResources.Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True)) End If End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function Private Shared Function IsDirectlyInIfOrElseIf(context As VisualBasicSyntaxContext) As Boolean ' Maybe we're after the Then keyword If context.TargetToken.IsKind(SyntaxKind.ThenKeyword) AndAlso context.TargetToken.Parent?.Parent.IsKind(SyntaxKind.MultiLineIfBlock, SyntaxKind.ElseIfBlock) Then Return True End If Dim statement = context.TargetToken.Parent.GetAncestor(Of StatementSyntax) Return If(statement?.Parent.IsKind(SyntaxKind.MultiLineIfBlock, SyntaxKind.ElseIfBlock), False) 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 Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Statements ''' <summary> ''' Recommends the "Else" keyword for the statement context. ''' </summary> Friend Class ElseKeywordRecommender Inherits AbstractKeywordRecommender Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword) Dim targetToken = context.TargetToken Dim parent = targetToken.GetAncestor(Of SingleLineIfStatementSyntax)() If parent IsNot Nothing AndAlso Not parent.Statements.IsEmpty() Then If context.IsFollowingCompleteStatement(Of SingleLineIfStatementSyntax)(Function(ifStatement) ifStatement.Statements.Last()) Then Return ImmutableArray.Create(New RecommendedKeyword("Else", VBFeaturesResources.Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True)) End If End If If context.IsSingleLineStatementContext AndAlso IsDirectlyInIfOrElseIf(context) Then Return ImmutableArray.Create(New RecommendedKeyword("Else", VBFeaturesResources.Introduces_a_group_of_statements_in_an_If_statement_that_is_executed_if_no_previous_condition_evaluates_to_True)) End If ' Determine whether we can offer "Else" after "Case" in a Select block. If targetToken.Kind = SyntaxKind.CaseKeyword AndAlso targetToken.Parent.IsKind(SyntaxKind.CaseStatement) Then ' Next, grab the parenting "Select" block and ensure that it doesn't have any Case Else statements Dim selectBlock = targetToken.GetAncestor(Of SelectBlockSyntax)() If selectBlock IsNot Nothing AndAlso Not selectBlock.CaseBlocks.Any(Function(cb) cb.CaseStatement.Kind = SyntaxKind.CaseElseStatement) Then ' Finally, ensure this case statement is the last one in the parenting "Select" block. If selectBlock.CaseBlocks.Last().CaseStatement Is targetToken.Parent Then Return ImmutableArray.Create(New RecommendedKeyword("Else", VBFeaturesResources.Introduces_the_statements_to_run_if_none_of_the_previous_cases_in_the_Select_Case_statement_returns_True)) End If End If End If Return ImmutableArray(Of RecommendedKeyword).Empty End Function Private Shared Function IsDirectlyInIfOrElseIf(context As VisualBasicSyntaxContext) As Boolean ' Maybe we're after the Then keyword If context.TargetToken.IsKind(SyntaxKind.ThenKeyword) AndAlso context.TargetToken.Parent?.Parent.IsKind(SyntaxKind.MultiLineIfBlock, SyntaxKind.ElseIfBlock) Then Return True End If Dim statement = context.TargetToken.Parent.GetAncestor(Of StatementSyntax) Return If(statement?.Parent.IsKind(SyntaxKind.MultiLineIfBlock, SyntaxKind.ElseIfBlock), False) End Function End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/CSharp/Portable/CodeFixes/RemoveNewModifier/RemoveNewModifierCodeFixProvider.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.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveNewModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveNew), Shared] internal class RemoveNewModifierCodeFixProvider : CodeFixProvider { private const string CS0109 = nameof(CS0109); // The member 'SomeClass.SomeMember' does not hide an accessible member. The new keyword is not required. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveNewModifierCodeFixProvider() { } public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0109); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var token = root.FindToken(diagnosticSpan.Start); var memberDeclarationSyntax = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclarationSyntax == null) return; var generator = context.Document.GetRequiredLanguageService<SyntaxGenerator>(); if (!generator.GetModifiers(memberDeclarationSyntax).IsNew) return; context.RegisterCodeFix( new MyCodeAction(ct => FixAsync(context.Document, generator, memberDeclarationSyntax, ct)), context.Diagnostics); } private static async Task<Document> FixAsync( Document document, SyntaxGenerator generator, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(root.ReplaceNode( memberDeclaration, generator.WithModifiers( memberDeclaration, generator.GetModifiers(memberDeclaration).WithIsNew(false)))); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Remove_new_modifier, createChangedDocument, CSharpFeaturesResources.Remove_new_modifier) { } } } }
// 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.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveNewModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveNew), Shared] internal class RemoveNewModifierCodeFixProvider : CodeFixProvider { private const string CS0109 = nameof(CS0109); // The member 'SomeClass.SomeMember' does not hide an accessible member. The new keyword is not required. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public RemoveNewModifierCodeFixProvider() { } public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0109); public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); var diagnostic = context.Diagnostics.First(); var diagnosticSpan = diagnostic.Location.SourceSpan; var token = root.FindToken(diagnosticSpan.Start); var memberDeclarationSyntax = token.GetAncestor<MemberDeclarationSyntax>(); if (memberDeclarationSyntax == null) return; var generator = context.Document.GetRequiredLanguageService<SyntaxGenerator>(); if (!generator.GetModifiers(memberDeclarationSyntax).IsNew) return; context.RegisterCodeFix( new MyCodeAction(ct => FixAsync(context.Document, generator, memberDeclarationSyntax, ct)), context.Diagnostics); } private static async Task<Document> FixAsync( Document document, SyntaxGenerator generator, MemberDeclarationSyntax memberDeclaration, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(root.ReplaceNode( memberDeclaration, generator.WithModifiers( memberDeclaration, generator.GetModifiers(memberDeclaration).WithIsNew(false)))); } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpFeaturesResources.Remove_new_modifier, createChangedDocument, CSharpFeaturesResources.Remove_new_modifier) { } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/VisualBasic/Portable/Structure/Providers/MultiLineIfBlockStructureProvider.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 MultiLineIfBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of MultiLineIfBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As MultiLineIfBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.IfStatement, autoCollapse:=False, type:=BlockTypes.Conditional, isCollapsible:=True)) 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 MultiLineIfBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of MultiLineIfBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As MultiLineIfBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.IfStatement, autoCollapse:=False, type:=BlockTypes.Conditional, isCollapsible:=True)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/CodeAnalysisTest/CorLibTypesTests.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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CorLibTypesAndConstantTests : TestBase { [Fact] public void IntegrityTest() { for (int i = 1; i <= (int)SpecialType.Count; i++) { string name = SpecialTypes.GetMetadataName((SpecialType)i); Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(name)); } for (int i = 0; i <= (int)SpecialType.Count; i++) { Cci.PrimitiveTypeCode code = SpecialTypes.GetTypeCode((SpecialType)i); if (code != Cci.PrimitiveTypeCode.NotPrimitive) { Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(code)); } } for (int i = 0; i <= (int)Cci.PrimitiveTypeCode.Invalid; i++) { SpecialType id = SpecialTypes.GetTypeFromMetadataName((Cci.PrimitiveTypeCode)i); if (id != SpecialType.None) { Assert.Equal((Cci.PrimitiveTypeCode)i, SpecialTypes.GetTypeCode(id)); } } Assert.Equal(SpecialType.System_Boolean, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Boolean)); Assert.Equal(SpecialType.System_Char, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Char)); Assert.Equal(SpecialType.System_Void, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Void)); Assert.Equal(SpecialType.System_String, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.String)); Assert.Equal(SpecialType.System_Int64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int64)); Assert.Equal(SpecialType.System_Int32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int32)); Assert.Equal(SpecialType.System_Int16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int16)); Assert.Equal(SpecialType.System_SByte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int8)); Assert.Equal(SpecialType.System_UInt64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt64)); Assert.Equal(SpecialType.System_UInt32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt32)); Assert.Equal(SpecialType.System_UInt16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt16)); Assert.Equal(SpecialType.System_Byte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt8)); Assert.Equal(SpecialType.System_Single, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float32)); Assert.Equal(SpecialType.System_Double, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float64)); Assert.Equal(SpecialType.System_IntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.IntPtr)); Assert.Equal(SpecialType.System_UIntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UIntPtr)); } [Fact] public void SpecialTypeIsValueType() { var comp = CSharp.CSharpCompilation.Create( "c", options: new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel), references: new[] { NetCoreApp.SystemRuntime }); var knownMissingTypes = new HashSet<SpecialType>() { }; for (var specialType = SpecialType.None + 1; specialType <= SpecialType.Count; specialType++) { var symbol = comp.GetSpecialType(specialType); if (knownMissingTypes.Contains(specialType)) { Assert.Equal(SymbolKind.ErrorType, symbol.Kind); } else { Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); Assert.Equal(symbol.IsValueType, specialType.IsValueType()); } } } [Fact] public void ConstantValueInvalidOperationTest01() { Assert.Throws<InvalidOperationException>(() => { ConstantValue.Create(null, ConstantValueTypeDiscriminator.Bad); }); var cv = ConstantValue.Create(1); Assert.Throws<InvalidOperationException>(() => { var c = cv.StringValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.CharValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.DateTimeValue; }); var cv1 = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Throws<InvalidOperationException>(() => { var c = cv1.BooleanValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DecimalValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DoubleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SingleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SByteValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.ByteValue; }); } [Fact] public void ConstantValuePropertiesTest01() { Assert.Equal(ConstantValue.Bad, ConstantValue.Default(ConstantValueTypeDiscriminator.Bad)); var cv1 = ConstantValue.Create((sbyte)-1); Assert.True(cv1.IsNegativeNumeric); var cv2 = ConstantValue.Create(-0.12345f); Assert.True(cv2.IsNegativeNumeric); var cv3 = ConstantValue.Create((double)-1.234); Assert.True(cv3.IsNegativeNumeric); var cv4 = ConstantValue.Create((decimal)-12345m); Assert.True(cv4.IsNegativeNumeric); Assert.False(cv4.IsDateTime); var cv5 = ConstantValue.Create(null); Assert.False(cv5.IsNumeric); Assert.False(cv5.IsBoolean); Assert.False(cv5.IsFloating); } [Fact] public void ConstantValueGetHashCodeTest01() { var cv11 = ConstantValue.Create((sbyte)-1); var cv12 = ConstantValue.Create((sbyte)-1); Assert.Equal(cv11.GetHashCode(), cv12.GetHashCode()); var cv21 = ConstantValue.Create((byte)255); var cv22 = ConstantValue.Create((byte)255); Assert.Equal(cv21.GetHashCode(), cv22.GetHashCode()); var cv31 = ConstantValue.Create((short)-32768); var cv32 = ConstantValue.Create((short)-32768); Assert.Equal(cv31.GetHashCode(), cv32.GetHashCode()); var cv41 = ConstantValue.Create((ushort)65535); var cv42 = ConstantValue.Create((ushort)65535); Assert.Equal(cv41.GetHashCode(), cv42.GetHashCode()); // int var cv51 = ConstantValue.Create(12345); var cv52 = ConstantValue.Create(12345); Assert.Equal(cv51.GetHashCode(), cv52.GetHashCode()); var cv61 = ConstantValue.Create(uint.MinValue); var cv62 = ConstantValue.Create(uint.MinValue); Assert.Equal(cv61.GetHashCode(), cv62.GetHashCode()); var cv71 = ConstantValue.Create(long.MaxValue); var cv72 = ConstantValue.Create(long.MaxValue); Assert.Equal(cv71.GetHashCode(), cv72.GetHashCode()); var cv81 = ConstantValue.Create((ulong)123456789); var cv82 = ConstantValue.Create((ulong)123456789); Assert.Equal(cv81.GetHashCode(), cv82.GetHashCode()); var cv91 = ConstantValue.Create(1.1m); var cv92 = ConstantValue.Create(1.1m); Assert.Equal(cv91.GetHashCode(), cv92.GetHashCode()); } // In general, different values are not required to have different hash codes. // But for perf reasons we want hash functions with a good distribution, // so we expect hash codes to differ if a single component is incremented. // But program correctness should be preserved even with a null hash function, // so we need a way to disable these tests during such correctness validation. #if !DISABLE_GOOD_HASH_TESTS [Fact] public void ConstantValueGetHashCodeTest02() { var cv1 = ConstantValue.Create("1"); var cv2 = ConstantValue.Create("2"); Assert.NotEqual(cv1.GetHashCode(), cv2.GetHashCode()); } #endif [Fact] public void ConstantValueToStringTest01() { var cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.String); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); // Never hit "ConstantValueString(null: Null)" var strVal = "QC"; cv = ConstantValue.Create(strVal); Assert.Equal(@"ConstantValueString(""QC"": String)", cv.ToString()); cv = ConstantValue.Create((sbyte)-128); Assert.Equal("ConstantValueI8(-128: SByte)", cv.ToString()); cv = ConstantValue.Create((ulong)123456789); Assert.Equal("ConstantValueI64(123456789: UInt64)", cv.ToString()); } } }
// 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CorLibTypesAndConstantTests : TestBase { [Fact] public void IntegrityTest() { for (int i = 1; i <= (int)SpecialType.Count; i++) { string name = SpecialTypes.GetMetadataName((SpecialType)i); Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(name)); } for (int i = 0; i <= (int)SpecialType.Count; i++) { Cci.PrimitiveTypeCode code = SpecialTypes.GetTypeCode((SpecialType)i); if (code != Cci.PrimitiveTypeCode.NotPrimitive) { Assert.Equal((SpecialType)i, SpecialTypes.GetTypeFromMetadataName(code)); } } for (int i = 0; i <= (int)Cci.PrimitiveTypeCode.Invalid; i++) { SpecialType id = SpecialTypes.GetTypeFromMetadataName((Cci.PrimitiveTypeCode)i); if (id != SpecialType.None) { Assert.Equal((Cci.PrimitiveTypeCode)i, SpecialTypes.GetTypeCode(id)); } } Assert.Equal(SpecialType.System_Boolean, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Boolean)); Assert.Equal(SpecialType.System_Char, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Char)); Assert.Equal(SpecialType.System_Void, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Void)); Assert.Equal(SpecialType.System_String, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.String)); Assert.Equal(SpecialType.System_Int64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int64)); Assert.Equal(SpecialType.System_Int32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int32)); Assert.Equal(SpecialType.System_Int16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int16)); Assert.Equal(SpecialType.System_SByte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Int8)); Assert.Equal(SpecialType.System_UInt64, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt64)); Assert.Equal(SpecialType.System_UInt32, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt32)); Assert.Equal(SpecialType.System_UInt16, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt16)); Assert.Equal(SpecialType.System_Byte, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UInt8)); Assert.Equal(SpecialType.System_Single, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float32)); Assert.Equal(SpecialType.System_Double, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.Float64)); Assert.Equal(SpecialType.System_IntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.IntPtr)); Assert.Equal(SpecialType.System_UIntPtr, SpecialTypes.GetTypeFromMetadataName(Cci.PrimitiveTypeCode.UIntPtr)); } [Fact] public void SpecialTypeIsValueType() { var comp = CSharp.CSharpCompilation.Create( "c", options: new CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel), references: new[] { NetCoreApp.SystemRuntime }); var knownMissingTypes = new HashSet<SpecialType>() { }; for (var specialType = SpecialType.None + 1; specialType <= SpecialType.Count; specialType++) { var symbol = comp.GetSpecialType(specialType); if (knownMissingTypes.Contains(specialType)) { Assert.Equal(SymbolKind.ErrorType, symbol.Kind); } else { Assert.NotEqual(SymbolKind.ErrorType, symbol.Kind); Assert.Equal(symbol.IsValueType, specialType.IsValueType()); } } } [Fact] public void ConstantValueInvalidOperationTest01() { Assert.Throws<InvalidOperationException>(() => { ConstantValue.Create(null, ConstantValueTypeDiscriminator.Bad); }); var cv = ConstantValue.Create(1); Assert.Throws<InvalidOperationException>(() => { var c = cv.StringValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.CharValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv.DateTimeValue; }); var cv1 = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Throws<InvalidOperationException>(() => { var c = cv1.BooleanValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DecimalValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.DoubleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SingleValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.SByteValue; }); Assert.Throws<InvalidOperationException>(() => { var c = cv1.ByteValue; }); } [Fact] public void ConstantValuePropertiesTest01() { Assert.Equal(ConstantValue.Bad, ConstantValue.Default(ConstantValueTypeDiscriminator.Bad)); var cv1 = ConstantValue.Create((sbyte)-1); Assert.True(cv1.IsNegativeNumeric); var cv2 = ConstantValue.Create(-0.12345f); Assert.True(cv2.IsNegativeNumeric); var cv3 = ConstantValue.Create((double)-1.234); Assert.True(cv3.IsNegativeNumeric); var cv4 = ConstantValue.Create((decimal)-12345m); Assert.True(cv4.IsNegativeNumeric); Assert.False(cv4.IsDateTime); var cv5 = ConstantValue.Create(null); Assert.False(cv5.IsNumeric); Assert.False(cv5.IsBoolean); Assert.False(cv5.IsFloating); } [Fact] public void ConstantValueGetHashCodeTest01() { var cv11 = ConstantValue.Create((sbyte)-1); var cv12 = ConstantValue.Create((sbyte)-1); Assert.Equal(cv11.GetHashCode(), cv12.GetHashCode()); var cv21 = ConstantValue.Create((byte)255); var cv22 = ConstantValue.Create((byte)255); Assert.Equal(cv21.GetHashCode(), cv22.GetHashCode()); var cv31 = ConstantValue.Create((short)-32768); var cv32 = ConstantValue.Create((short)-32768); Assert.Equal(cv31.GetHashCode(), cv32.GetHashCode()); var cv41 = ConstantValue.Create((ushort)65535); var cv42 = ConstantValue.Create((ushort)65535); Assert.Equal(cv41.GetHashCode(), cv42.GetHashCode()); // int var cv51 = ConstantValue.Create(12345); var cv52 = ConstantValue.Create(12345); Assert.Equal(cv51.GetHashCode(), cv52.GetHashCode()); var cv61 = ConstantValue.Create(uint.MinValue); var cv62 = ConstantValue.Create(uint.MinValue); Assert.Equal(cv61.GetHashCode(), cv62.GetHashCode()); var cv71 = ConstantValue.Create(long.MaxValue); var cv72 = ConstantValue.Create(long.MaxValue); Assert.Equal(cv71.GetHashCode(), cv72.GetHashCode()); var cv81 = ConstantValue.Create((ulong)123456789); var cv82 = ConstantValue.Create((ulong)123456789); Assert.Equal(cv81.GetHashCode(), cv82.GetHashCode()); var cv91 = ConstantValue.Create(1.1m); var cv92 = ConstantValue.Create(1.1m); Assert.Equal(cv91.GetHashCode(), cv92.GetHashCode()); } // In general, different values are not required to have different hash codes. // But for perf reasons we want hash functions with a good distribution, // so we expect hash codes to differ if a single component is incremented. // But program correctness should be preserved even with a null hash function, // so we need a way to disable these tests during such correctness validation. #if !DISABLE_GOOD_HASH_TESTS [Fact] public void ConstantValueGetHashCodeTest02() { var cv1 = ConstantValue.Create("1"); var cv2 = ConstantValue.Create("2"); Assert.NotEqual(cv1.GetHashCode(), cv2.GetHashCode()); } #endif [Fact] public void ConstantValueToStringTest01() { var cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.Null); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); cv = ConstantValue.Create(null, ConstantValueTypeDiscriminator.String); Assert.Equal("ConstantValueNull(null: Null)", cv.ToString()); // Never hit "ConstantValueString(null: Null)" var strVal = "QC"; cv = ConstantValue.Create(strVal); Assert.Equal(@"ConstantValueString(""QC"": String)", cv.ToString()); cv = ConstantValue.Create((sbyte)-128); Assert.Equal("ConstantValueI8(-128: SByte)", cv.ToString()); cv = ConstantValue.Create((ulong)123456789); Assert.Equal("ConstantValueI64(123456789: UInt64)", cv.ToString()); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/Extensions/CastExpressionSyntaxExtensions.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.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module CastExpressionSyntaxExtensions <Extension> Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function <Extension> Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax Dim resultNode = innerNode.WithTriviaFrom(castNode) resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode) Return resultNode 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 System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Friend Module CastExpressionSyntaxExtensions <Extension> Public Function Uncast(cast As CastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function <Extension> Public Function Uncast(cast As PredefinedCastExpressionSyntax) As ExpressionSyntax Return Uncast(cast, cast.Expression) End Function Private Function Uncast(castNode As ExpressionSyntax, innerNode As ExpressionSyntax) As ExpressionSyntax Dim resultNode = innerNode.WithTriviaFrom(castNode) resultNode = SimplificationHelpers.CopyAnnotations(castNode, resultNode) Return resultNode End Function End Module End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/VisualBasic/Portable/Structure/Providers/WithBlockStructureProvider.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 WithBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of WithBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As WithBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.WithStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) 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 WithBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of WithBlockSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As WithBlockSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.WithStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_FindReferences_Current.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { // This file contains the current FindReferences APIs. The current APIs allow for OOP // implementation and will defer to the oop server if it is available. If not, it will // compute the results in process. public static partial class SymbolFinder { internal static async Task FindReferencesAsync( ISymbol symbol, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.FindReference, cancellationToken)) { if (SerializableSymbolAndProjectId.TryCreate(symbol, solution, cancellationToken, out var serializedSymbol)) { var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false); if (client != null) { // Create a callback that we can pass to the server process to hear about the // results as it finds them. When we hear about results we'll forward them to // the 'progress' parameter which will then update the UI. var serverCallback = new FindReferencesServerCallback(solution, progress); var documentIds = documents?.SelectAsArray(d => d.Id) ?? default; await client.TryInvokeAsync<IRemoteSymbolFinderService>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.FindReferencesAsync(solutionInfo, callbackId, serializedSymbol, documentIds, options, cancellationToken), serverCallback, cancellationToken).ConfigureAwait(false); return; } } // Couldn't effectively search in OOP. Perform the search in-proc. await FindReferencesInCurrentProcessAsync( symbol, solution, progress, documents, options, cancellationToken).ConfigureAwait(false); } } internal static Task FindReferencesInCurrentProcessAsync( ISymbol symbol, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var finders = ReferenceFinders.DefaultReferenceFinders; progress ??= NoOpStreamingFindReferencesProgress.Instance; var engine = new FindReferencesSearchEngine( solution, documents, finders, progress, options); return engine.FindReferencesAsync(symbol, 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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols.Finders; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols { // This file contains the current FindReferences APIs. The current APIs allow for OOP // implementation and will defer to the oop server if it is available. If not, it will // compute the results in process. public static partial class SymbolFinder { internal static async Task FindReferencesAsync( ISymbol symbol, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.FindReference, cancellationToken)) { if (SerializableSymbolAndProjectId.TryCreate(symbol, solution, cancellationToken, out var serializedSymbol)) { var client = await RemoteHostClient.TryGetClientAsync(solution.Workspace, cancellationToken).ConfigureAwait(false); if (client != null) { // Create a callback that we can pass to the server process to hear about the // results as it finds them. When we hear about results we'll forward them to // the 'progress' parameter which will then update the UI. var serverCallback = new FindReferencesServerCallback(solution, progress); var documentIds = documents?.SelectAsArray(d => d.Id) ?? default; await client.TryInvokeAsync<IRemoteSymbolFinderService>( solution, (service, solutionInfo, callbackId, cancellationToken) => service.FindReferencesAsync(solutionInfo, callbackId, serializedSymbol, documentIds, options, cancellationToken), serverCallback, cancellationToken).ConfigureAwait(false); return; } } // Couldn't effectively search in OOP. Perform the search in-proc. await FindReferencesInCurrentProcessAsync( symbol, solution, progress, documents, options, cancellationToken).ConfigureAwait(false); } } internal static Task FindReferencesInCurrentProcessAsync( ISymbol symbol, Solution solution, IStreamingFindReferencesProgress progress, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var finders = ReferenceFinders.DefaultReferenceFinders; progress ??= NoOpStreamingFindReferencesProgress.Instance; var engine = new FindReferencesSearchEngine( solution, documents, finders, progress, options); return engine.FindReferencesAsync(symbol, cancellationToken); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_IPropertyReferenceExpression.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.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation), WorkItem(21769, "https://github.com/dotnet/roslyn/issues/21769")> <Fact()> Public Sub PropertyReferenceExpression_PropertyReferenceInWithDerivedTypeUsesDerivedTypeAsInstanceType_LValue() Dim source = <![CDATA[ Option Strict On Module M1 Sub Method1() Dim c2 As C2 = New C2 With {.P1 = New Object}'BIND:"P1" End Sub Class C1 Public Overridable Property P1 As Object End Class Class C2 Inherits C1 End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: M1.C2, IsImplicit) (Syntax: 'New C2 With ... New Object}') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation), WorkItem(21769, "https://github.com/dotnet/roslyn/issues/21769")> <Fact()> Public Sub PropertyReferenceExpression_PropertyReferenceInWithDerivedTypeUsesDerivedTypeAsInstanceType_RValue() Dim source = <![CDATA[ Option Strict On Module M1 Sub Method1() Dim c2 As C2 = New C2 With {.P2 = .P1}'BIND:".P1" c2.P1 = Nothing End Sub Class C1 Public Overridable Property P1 As Object Public Property P2 As Object End Class Class C2 Inherits C1 End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: '.P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: M1.C2, IsImplicit) (Syntax: 'New C2 With {.P2 = .P1}') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_SharedPropertyWithInstanceReceiver() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Property P1 As Integer Shared Sub S2() Dim c1Instance As New C1 Dim i1 As Integer = c1Instance.P1'BIND:"c1Instance.P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c1Instance.P1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim i1 As Integer = c1Instance.P1'BIND:"c1Instance.P1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_SharedPropertyAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Property P1 As Integer Shared Sub S2() Dim i1 As Integer = C1.P1'BIND:"C1.P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'C1.P1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_InstancePropertyAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Property P1 As Integer Shared Sub S2() Dim i1 As Integer = C1.P1'BIND:"C1.P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'C1.P1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. Dim i1 As Integer = C1.P1'BIND:"C1.P1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_SharedProperty() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Property P1 As Integer Shared Sub S2() Dim i1 = P1'BIND:"P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_NoControlFlow() ' Verify mix of property references with implicit/explicit/null instance in lvalue/rvalue contexts. ' Also verifies property with arguments. Dim source = <![CDATA[ Imports System Friend Class C Private Property P1 As Integer Private Shared Property P2 As Integer Private ReadOnly Property P3(i As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c As C, i As Integer)'BIND:"Public Sub M(c As C, i As Integer)" P1 = C.P2 + c.P3(i) P2 = Me.P1 + c.P1 End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'P1 = C.P2 + c.P3(i)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Void, IsImplicit) (Syntax: 'P1 = C.P2 + c.P3(i)') Left: IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'P1') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'C.P2 + c.P3(i)') Left: IPropertyReferenceOperation: Property C.P2 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'C.P2') Instance Receiver: null Right: IPropertyReferenceOperation: ReadOnly Property C.P3(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P3(i)') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'P2 = Me.P1 + c.P1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Void, IsImplicit) (Syntax: 'P2 = Me.P1 + c.P1') Left: IPropertyReferenceOperation: Property C.P2 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P2') Instance Receiver: null Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'Me.P1 + c.P1') Left: IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Me.P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Right: IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInReceiver() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c1 As C, c2 As C, i As Integer, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, i As Integer, p As Integer)" p = If(c1, c2).P1(i) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(c1, c2).P1(i)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If(c1, c2).P1(i)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2).P1(i)') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInReceiver_StaticProperty() Dim source = <![CDATA[ Imports System Friend Class C Public Shared ReadOnly Property P1 As Integer Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)" p1 = c1.P1 p2 = If(c1, c2).P1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p1 = c1.P1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p1 = c1.P1') Left: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') Right: IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c1.P1') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p2 = If(c1, c2).P1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p2 = If(c1, c2).P1') Left: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p2') Right: IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2).P1') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p1 = c1.P1 ~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p2 = If(c1, c2).P1 ~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInFirstArgument() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)'BIND:"Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)" p = c.P1(If(i1, i2), i3) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = c.P1(If(i1, i2), i3)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = c.P1(If(i1, i2), i3)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1(If(i1, i2), i3)') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'i3') IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInSecondArgument() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)'BIND:"Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)" p = c.P1(i3, If(i1, i2)) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3') Value: IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = c.P1(i3, If(i1, i2))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = c.P1(i3, If(i1, i2))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1(i3, If(i1, i2))') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'i3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInReceiverAndArguments() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c1 As C, c2 As C, i1 As Integer?, i2 As Integer, i3 As Integer?, i4 As Integer, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, i1 As Integer?, i2 As Integer, i3 As Integer?, i4 As Integer, p As Integer)" p = If(c1, c2).P1(If(i1, i2), If(i3, i4)) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] [6] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { CaptureIds: [5] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3') Value: IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i3') Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i3') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i3') Leaving: {R4} Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i3') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i3') Arguments(0) Next (Regular) Block[B11] Leaving: {R4} } Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i4') Value: IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(c1, ... If(i3, i4))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If(c1, ... If(i3, i4))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2). ... If(i3, i4))') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'If(i3, i4)') IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i3, i4)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B12] Leaving: {R1} } Block[B12] - Exit Predecessors: [B11] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) 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 Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Partial Public Class IOperationTests Inherits SemanticModelTestBase <CompilerTrait(CompilerFeature.IOperation), WorkItem(21769, "https://github.com/dotnet/roslyn/issues/21769")> <Fact()> Public Sub PropertyReferenceExpression_PropertyReferenceInWithDerivedTypeUsesDerivedTypeAsInstanceType_LValue() Dim source = <![CDATA[ Option Strict On Module M1 Sub Method1() Dim c2 As C2 = New C2 With {.P1 = New Object}'BIND:"P1" End Sub Class C1 Public Overridable Property P1 As Object End Class Class C2 Inherits C1 End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: 'P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: M1.C2, IsImplicit) (Syntax: 'New C2 With ... New Object}') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation), WorkItem(21769, "https://github.com/dotnet/roslyn/issues/21769")> <Fact()> Public Sub PropertyReferenceExpression_PropertyReferenceInWithDerivedTypeUsesDerivedTypeAsInstanceType_RValue() Dim source = <![CDATA[ Option Strict On Module M1 Sub Method1() Dim c2 As C2 = New C2 With {.P2 = .P1}'BIND:".P1" c2.P1 = Nothing End Sub Class C1 Public Overridable Property P1 As Object Public Property P2 As Object End Class Class C2 Inherits C1 End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Object (OperationKind.PropertyReference, Type: System.Object) (Syntax: '.P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: M1.C2, IsImplicit) (Syntax: 'New C2 With {.P2 = .P1}') ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_SharedPropertyWithInstanceReceiver() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Property P1 As Integer Shared Sub S2() Dim c1Instance As New C1 Dim i1 As Integer = c1Instance.P1'BIND:"c1Instance.P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c1Instance.P1') Instance Receiver: ILocalReferenceOperation: c1Instance (OperationKind.LocalReference, Type: M1.C1) (Syntax: 'c1Instance') ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. Dim i1 As Integer = c1Instance.P1'BIND:"c1Instance.P1" ~~~~~~~~~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_SharedPropertyAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Property P1 As Integer Shared Sub S2() Dim i1 As Integer = C1.P1'BIND:"C1.P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'C1.P1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_InstancePropertyAccessOnClass() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Property P1 As Integer Shared Sub S2() Dim i1 As Integer = C1.P1'BIND:"C1.P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'C1.P1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC30469: Reference to a non-shared member requires an object reference. Dim i1 As Integer = C1.P1'BIND:"C1.P1" ~~~~~ ]]>.Value VerifyOperationTreeAndDiagnosticsForTest(Of MemberAccessExpressionSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation)> <Fact()> Public Sub IPropertyReference_SharedProperty() Dim source = <![CDATA[ Option Strict On Imports System Module M1 Class C1 Shared Property P1 As Integer Shared Sub S2() Dim i1 = P1'BIND:"P1" End Sub End Class End Module]]>.Value Dim expectedOperationTree = <![CDATA[ IPropertyReferenceOperation: Property M1.C1.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P1') Instance Receiver: null ]]>.Value Dim expectedDiagnostics = String.Empty VerifyOperationTreeAndDiagnosticsForTest(Of IdentifierNameSyntax)(source, expectedOperationTree, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_NoControlFlow() ' Verify mix of property references with implicit/explicit/null instance in lvalue/rvalue contexts. ' Also verifies property with arguments. Dim source = <![CDATA[ Imports System Friend Class C Private Property P1 As Integer Private Shared Property P2 As Integer Private ReadOnly Property P3(i As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c As C, i As Integer)'BIND:"Public Sub M(c As C, i As Integer)" P1 = C.P2 + c.P3(i) P2 = Me.P1 + c.P1 End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'P1 = C.P2 + c.P3(i)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Void, IsImplicit) (Syntax: 'P1 = C.P2 + c.P3(i)') Left: IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'P1') Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'C.P2 + c.P3(i)') Left: IPropertyReferenceOperation: Property C.P2 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'C.P2') Instance Receiver: null Right: IPropertyReferenceOperation: ReadOnly Property C.P3(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P3(i)') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'P2 = Me.P1 + c.P1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Void, IsImplicit) (Syntax: 'P2 = Me.P1 + c.P1') Left: IPropertyReferenceOperation: Property C.P2 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'P2') Instance Receiver: null Right: IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: 'Me.P1 + c.P1') Left: IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Me.P1') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'Me') Right: IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1') Instance Receiver: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInReceiver() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c1 As C, c2 As C, i As Integer, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, i As Integer, p As Integer)" p = If(c1, c2).P1(i) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(c1, c2).P1(i)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If(c1, c2).P1(i)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2).P1(i)') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null) (Syntax: 'i') IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInReceiver_StaticProperty() Dim source = <![CDATA[ Imports System Friend Class C Public Shared ReadOnly Property P1 As Integer Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, p1 As Integer, p2 As Integer)" p1 = c1.P1 p2 = If(c1, c2).P1 End Sub End Class ]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p1 = c1.P1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p1 = c1.P1') Left: IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p1') Right: IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c1.P1') Instance Receiver: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p2 = If(c1, c2).P1') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p2 = If(c1, c2).P1') Left: IParameterReferenceOperation: p2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p2') Right: IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2).P1') Instance Receiver: null Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) ]]>.Value Dim expectedDiagnostics = <![CDATA[ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p1 = c1.P1 ~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. p2 = If(c1, c2).P1 ~~~~~~~~~~~~~ ]]>.Value VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInFirstArgument() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)'BIND:"Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)" p = c.P1(If(i1, i2), i3) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [3] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = c.P1(If(i1, i2), i3)') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = c.P1(If(i1, i2), i3)') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1(If(i1, i2), i3)') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)') IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'i3') IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInSecondArgument() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)'BIND:"Public Sub M(c As C, i1 As Integer?, i2 As Integer, i3 As Integer, p As Integer)" p = c.P1(i3, If(i1, i2)) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [1] [2] [4] Block[B1] - Block Predecessors: [B0] Statements (3) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3') Value: IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [3] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B5] Leaving: {R2} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B5] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = c.P1(i3, If(i1, i2))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = c.P1(i3, If(i1, i2))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'c.P1(i3, If(i1, i2))') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'i3') IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B6] Leaving: {R1} } Block[B6] - Exit Predecessors: [B5] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub <CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)> <Fact> Public Sub PropertyReference_ControlFlowInReceiverAndArguments() Dim source = <![CDATA[ Imports System Friend Class C Public ReadOnly Property P1(i1 As Integer, i2 As Integer) As Integer Get Return 0 End Get End Property Public Sub M(c1 As C, c2 As C, i1 As Integer?, i2 As Integer, i3 As Integer?, i4 As Integer, p As Integer)'BIND:"Public Sub M(c1 As C, c2 As C, i1 As Integer?, i2 As Integer, i3 As Integer?, i4 As Integer, p As Integer)" p = If(c1, c2).P1(If(i1, i2), If(i3, i4)) End Sub End Class]]>.Value Dim expectedFlowGraph = <![CDATA[ Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { CaptureIds: [0] [2] [4] [6] Block[B1] - Block Predecessors: [B0] Statements (1) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'p') Value: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'p') Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [1] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1') Jump if True (Regular) to Block[B4] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Leaving: {R2} Next (Regular) Block[B3] Block[B3] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B5] Leaving: {R2} Entering: {R3} } Block[B4] - Block Predecessors: [B2] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C) (Syntax: 'c2') Next (Regular) Block[B5] Entering: {R3} .locals {R3} { CaptureIds: [3] Block[B5] - Block Predecessors: [B3] [B4] Statements (1) IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i1') Jump if True (Regular) to Block[B7] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i1') Operand: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Leaving: {R3} Next (Regular) Block[B6] Block[B6] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i1') Instance Receiver: IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i1') Arguments(0) Next (Regular) Block[B8] Leaving: {R3} Entering: {R4} } Block[B7] - Block Predecessors: [B5] Statements (1) IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2') Value: IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2') Next (Regular) Block[B8] Entering: {R4} .locals {R4} { CaptureIds: [5] Block[B8] - Block Predecessors: [B6] [B7] Statements (1) IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3') Value: IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'i3') Jump if True (Regular) to Block[B10] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i3') Operand: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i3') Leaving: {R4} Next (Regular) Block[B9] Block[B9] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3') Value: IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i3') Instance Receiver: IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'i3') Arguments(0) Next (Regular) Block[B11] Leaving: {R4} } Block[B10] - Block Predecessors: [B8] Statements (1) IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i4') Value: IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4') Next (Regular) Block[B11] Block[B11] - Block Predecessors: [B9] [B10] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'p = If(c1, ... If(i3, i4))') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'p = If(c1, ... If(i3, i4))') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'p') Right: IPropertyReferenceOperation: ReadOnly Property C.P1(i1 As System.Int32, i2 As System.Int32) As System.Int32 (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'If(c1, c2). ... If(i3, i4))') Instance Receiver: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'If(c1, c2)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i1) (OperationKind.Argument, Type: null) (Syntax: 'If(i1, i2)') IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i1, i2)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i2) (OperationKind.Argument, Type: null) (Syntax: 'If(i3, i4)') IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(i3, i4)') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B12] Leaving: {R1} } Block[B12] - Exit Predecessors: [B11] Statements (0) ]]>.Value Dim expectedDiagnostics = String.Empty VerifyFlowGraphAndDiagnosticsForTest(Of MethodBlockSyntax)(source, expectedFlowGraph, expectedDiagnostics) End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A container synthesized for a lambda, iterator method, async method, or dynamic-sites. /// </summary> internal abstract class SynthesizedContainer : NamedTypeSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters; protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid) { Debug.Assert(name != null); Name = name; TypeMap = TypeMap.Empty; _typeParameters = CreateTypeParameters(parameterCount, returnsVoid); _constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>); } protected SynthesizedContainer(string name, MethodSymbol containingMethod) { Debug.Assert(name != null); Name = name; if (containingMethod == null) { TypeMap = TypeMap.Empty; _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); } } protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap) { Debug.Assert(name != null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(typeMap != null); Name = name; _typeParameters = typeParameters; TypeMap = typeMap; } private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } internal TypeMap TypeMap { get; } internal virtual MethodSymbol Constructor => null; internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol.Kind == SymbolKind.NamedType && ContainingSymbol.IsImplicitlyDeclared) { return; } var compilation = ContainingSymbol.DeclaringCompilation; // this can only happen if frame is not nested in a source type/namespace (so far we do not do this) // if this happens for whatever reason, we do not need "CompilerGenerated" anyways Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?"); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; /// <summary> /// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/> /// </summary> internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters; public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters; public sealed override string Name { get; } public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>(); public override NamedTypeSymbol ConstructedFrom => this; public override bool IsSealed => true; public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal sealed override bool IsInterpolatedStringHandlerType => false; public override ImmutableArray<Symbol> GetMembers() { Symbol constructor = this.Constructor; return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor); } public override ImmutableArray<Symbol> GetMembers(string name) { var ctor = Constructor; return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: yield return (FieldSymbol)m; break; } } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name); public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.Private; public override bool IsStatic => false; public sealed override bool IsRefLikeType => false; public sealed override bool IsReadOnly => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit(); internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object); internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved); public override bool MightContainExtensionMethods => false; public override int Arity => TypeParameters.Length; internal override bool MangleName => Arity > 0; public override bool IsImplicitlyDeclared => true; internal override bool ShouldAddWinRTMembers => false; internal override bool IsWindowsRuntimeImport => false; internal override bool IsComImport => false; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override bool HasDeclarativeSecurity => false; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; public override bool IsSerializable => false; internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo); internal override TypeLayout Layout => default(TypeLayout); internal override bool HasSpecialName => false; internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A container synthesized for a lambda, iterator method, async method, or dynamic-sites. /// </summary> internal abstract class SynthesizedContainer : NamedTypeSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters; protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid) { Debug.Assert(name != null); Name = name; TypeMap = TypeMap.Empty; _typeParameters = CreateTypeParameters(parameterCount, returnsVoid); _constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>); } protected SynthesizedContainer(string name, MethodSymbol containingMethod) { Debug.Assert(name != null); Name = name; if (containingMethod == null) { TypeMap = TypeMap.Empty; _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); } } protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap) { Debug.Assert(name != null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(typeMap != null); Name = name; _typeParameters = typeParameters; TypeMap = typeMap; } private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } internal TypeMap TypeMap { get; } internal virtual MethodSymbol Constructor => null; internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol.Kind == SymbolKind.NamedType && ContainingSymbol.IsImplicitlyDeclared) { return; } var compilation = ContainingSymbol.DeclaringCompilation; // this can only happen if frame is not nested in a source type/namespace (so far we do not do this) // if this happens for whatever reason, we do not need "CompilerGenerated" anyways Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?"); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; /// <summary> /// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/> /// </summary> internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters; public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters; public sealed override string Name { get; } public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>(); public override NamedTypeSymbol ConstructedFrom => this; public override bool IsSealed => true; public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal sealed override bool IsInterpolatedStringHandlerType => false; public override ImmutableArray<Symbol> GetMembers() { Symbol constructor = this.Constructor; return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor); } public override ImmutableArray<Symbol> GetMembers(string name) { var ctor = Constructor; return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: yield return (FieldSymbol)m; break; } } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name); public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.Private; public override bool IsStatic => false; public sealed override bool IsRefLikeType => false; public sealed override bool IsReadOnly => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit(); internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object); internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved); public override bool MightContainExtensionMethods => false; public override int Arity => TypeParameters.Length; internal override bool MangleName => Arity > 0; public override bool IsImplicitlyDeclared => true; internal override bool ShouldAddWinRTMembers => false; internal override bool IsWindowsRuntimeImport => false; internal override bool IsComImport => false; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override bool HasDeclarativeSecurity => false; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; public override bool IsSerializable => false; internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo); internal override TypeLayout Layout => default(TypeLayout); internal override bool HasSpecialName => false; internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Workspace/Solution/SourceGeneratedDocument.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; namespace Microsoft.CodeAnalysis { /// <summary> /// A <see cref="Document"/> that was generated by an <see cref="ISourceGenerator" />. /// </summary> public sealed class SourceGeneratedDocument : Document { internal SourceGeneratedDocument(Project project, SourceGeneratedDocumentState state) : base(project, state) { } private new SourceGeneratedDocumentState State => (SourceGeneratedDocumentState)base.State; // TODO: make this public. Tracked by https://github.com/dotnet/roslyn/issues/50546 internal string SourceGeneratorAssemblyName => Identity.GeneratorAssemblyName; internal string SourceGeneratorTypeName => Identity.GeneratorTypeName; public string HintName => State.HintName; internal SourceGeneratedDocumentIdentity Identity => State.Identity; internal override Document WithFrozenPartialSemantics(CancellationToken cancellationToken) { // For us to implement frozen partial semantics here with a source generated document, // we'd need to potentially deal with the combination where that happens on a snapshot that was already // forked; rather than trying to deal with that combo we'll just fall back to not doing anything special // which is allowed. return this; } } }
// 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; namespace Microsoft.CodeAnalysis { /// <summary> /// A <see cref="Document"/> that was generated by an <see cref="ISourceGenerator" />. /// </summary> public sealed class SourceGeneratedDocument : Document { internal SourceGeneratedDocument(Project project, SourceGeneratedDocumentState state) : base(project, state) { } private new SourceGeneratedDocumentState State => (SourceGeneratedDocumentState)base.State; // TODO: make this public. Tracked by https://github.com/dotnet/roslyn/issues/50546 internal string SourceGeneratorAssemblyName => Identity.GeneratorAssemblyName; internal string SourceGeneratorTypeName => Identity.GeneratorTypeName; public string HintName => State.HintName; internal SourceGeneratedDocumentIdentity Identity => State.Identity; internal override Document WithFrozenPartialSemantics(CancellationToken cancellationToken) { // For us to implement frozen partial semantics here with a source generated document, // we'd need to potentially deal with the combination where that happens on a snapshot that was already // forked; rather than trying to deal with that combo we'll just fall back to not doing anything special // which is allowed. return this; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Options/OptionServiceFactory.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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { [ExportWorkspaceServiceFactory(typeof(IOptionService)), Shared] internal class OptionServiceFactory : IWorkspaceServiceFactory { private readonly IGlobalOptionService _globalOptionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OptionServiceFactory(IGlobalOptionService globalOptionService) => _globalOptionService = globalOptionService; public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new OptionService(_globalOptionService, workspaceServices); /// <summary> /// Wraps an underlying <see cref="IGlobalOptionService"/> and exposes its data to workspace /// clients. Also takes the <see cref="IGlobalOptionService.OptionChanged"/> notifications /// and forwards them along using the same <see cref="TaskQueue"/> used by the /// <see cref="Workspace"/> this is connected to. i.e. instead of synchronously just passing /// along the underlying events, these will be enqueued onto the workspace's eventing queue. /// </summary> internal sealed class OptionService : IWorkspaceOptionService { private readonly IGlobalOptionService _globalOptionService; private readonly TaskQueue _taskQueue; /// <summary> /// Gate guarding <see cref="_eventHandlers"/> and <see cref="_documentOptionsProviders"/>. /// </summary> private readonly object _gate = new(); private ImmutableArray<EventHandler<OptionChangedEventArgs>> _eventHandlers = ImmutableArray<EventHandler<OptionChangedEventArgs>>.Empty; private ImmutableArray<IDocumentOptionsProvider> _documentOptionsProviders = ImmutableArray<IDocumentOptionsProvider>.Empty; public OptionService( IGlobalOptionService globalOptionService, HostWorkspaceServices workspaceServices) { _globalOptionService = globalOptionService; var schedulerProvider = workspaceServices.GetRequiredService<ITaskSchedulerProvider>(); var listenerProvider = workspaceServices.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), schedulerProvider.CurrentContextScheduler); _globalOptionService.OptionChanged += OnGlobalOptionServiceOptionChanged; } public void OnWorkspaceDisposed(Workspace workspace) { // Disconnect us from the underlying global service. That way it doesn't // keep us around (and all the event handlers we're holding onto) forever. _globalOptionService.OptionChanged -= OnGlobalOptionServiceOptionChanged; } private void OnGlobalOptionServiceOptionChanged(object? sender, OptionChangedEventArgs e) { _taskQueue.ScheduleTask(nameof(OptionService) + "." + nameof(OnGlobalOptionServiceOptionChanged), () => { // Ensure we grab the event handlers inside the scheduled task to prevent a race of people unsubscribing // but getting the event later on the UI thread var eventHandlers = GetEventHandlers(); foreach (var handler in eventHandlers) { handler(this, e); } }, CancellationToken.None); } private ImmutableArray<EventHandler<OptionChangedEventArgs>> GetEventHandlers() { lock (_gate) { return _eventHandlers; } } public event EventHandler<OptionChangedEventArgs> OptionChanged { add { lock (_gate) { _eventHandlers = _eventHandlers.Add(value); } } remove { lock (_gate) { _eventHandlers = _eventHandlers.Remove(value); } } } // Simple forwarding functions. public SerializableOptionSet GetOptions() => GetSerializableOptionsSnapshot(ImmutableHashSet<string>.Empty); public SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages) => _globalOptionService.GetSerializableOptionsSnapshot(languages, this); public object? GetOption(OptionKey optionKey) => _globalOptionService.GetOption(optionKey); public T? GetOption<T>(Option<T> option) => _globalOptionService.GetOption(option); public T? GetOption<T>(Option2<T> option) => _globalOptionService.GetOption(option); public T? GetOption<T>(PerLanguageOption<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName); public T? GetOption<T>(PerLanguageOption2<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName); public IEnumerable<IOption> GetRegisteredOptions() => _globalOptionService.GetRegisteredOptions(); public bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey) => _globalOptionService.TryMapEditorConfigKeyToOption(key, language, out storageLocation, out optionKey); public ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages) => _globalOptionService.GetRegisteredSerializableOptions(languages); public void SetOptions(OptionSet optionSet) => _globalOptionService.SetOptions(optionSet); public void RegisterWorkspace(Workspace workspace) => _globalOptionService.RegisterWorkspace(workspace); public void UnregisterWorkspace(Workspace workspace) => _globalOptionService.UnregisterWorkspace(workspace); public void RegisterDocumentOptionsProvider(IDocumentOptionsProvider documentOptionsProvider) { if (documentOptionsProvider == null) { throw new ArgumentNullException(nameof(documentOptionsProvider)); } lock (_gate) { _documentOptionsProviders = _documentOptionsProviders.Add(documentOptionsProvider); } } public async Task<OptionSet> GetUpdatedOptionSetForDocumentAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken) { ImmutableArray<IDocumentOptionsProvider> documentOptionsProviders; lock (_gate) { documentOptionsProviders = _documentOptionsProviders; } var realizedDocumentOptions = new List<IDocumentOptions>(); foreach (var provider in documentOptionsProviders) { cancellationToken.ThrowIfCancellationRequested(); var documentOption = await provider.GetOptionsForDocumentAsync(document, cancellationToken).ConfigureAwait(false); if (documentOption != null) { realizedDocumentOptions.Add(documentOption); } } return new DocumentSpecificOptionSet(realizedDocumentOptions, optionSet); } private class DocumentSpecificOptionSet : OptionSet { private readonly OptionSet _underlyingOptions; private readonly List<IDocumentOptions> _documentOptions; private ImmutableDictionary<OptionKey, object?> _values; public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions) : this(documentOptions, underlyingOptions, ImmutableDictionary<OptionKey, object?>.Empty) { } public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions, ImmutableDictionary<OptionKey, object?> values) { _documentOptions = documentOptions; _underlyingOptions = underlyingOptions; _values = values; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)] private protected override object? GetOptionCore(OptionKey optionKey) { // If we already know the document specific value, we're done if (_values.TryGetValue(optionKey, out var value)) { return value; } foreach (var documentOptionSource in _documentOptions) { if (documentOptionSource.TryGetDocumentOption(optionKey, out value)) { // Cache and return return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value); } } // We don't have a document specific value, so forward return _underlyingOptions.GetOption(optionKey); } public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => new DocumentSpecificOptionSet(_documentOptions, _underlyingOptions, _values.SetItem(optionAndLanguage, value)); internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) { // GetChangedOptions only needs to be supported for OptionSets that need to be compared during application, // but that's already enforced it must be a full SerializableOptionSet. throw new NotSupportedException(); } } } } }
// 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Options { [ExportWorkspaceServiceFactory(typeof(IOptionService)), Shared] internal class OptionServiceFactory : IWorkspaceServiceFactory { private readonly IGlobalOptionService _globalOptionService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OptionServiceFactory(IGlobalOptionService globalOptionService) => _globalOptionService = globalOptionService; public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => new OptionService(_globalOptionService, workspaceServices); /// <summary> /// Wraps an underlying <see cref="IGlobalOptionService"/> and exposes its data to workspace /// clients. Also takes the <see cref="IGlobalOptionService.OptionChanged"/> notifications /// and forwards them along using the same <see cref="TaskQueue"/> used by the /// <see cref="Workspace"/> this is connected to. i.e. instead of synchronously just passing /// along the underlying events, these will be enqueued onto the workspace's eventing queue. /// </summary> internal sealed class OptionService : IWorkspaceOptionService { private readonly IGlobalOptionService _globalOptionService; private readonly TaskQueue _taskQueue; /// <summary> /// Gate guarding <see cref="_eventHandlers"/> and <see cref="_documentOptionsProviders"/>. /// </summary> private readonly object _gate = new(); private ImmutableArray<EventHandler<OptionChangedEventArgs>> _eventHandlers = ImmutableArray<EventHandler<OptionChangedEventArgs>>.Empty; private ImmutableArray<IDocumentOptionsProvider> _documentOptionsProviders = ImmutableArray<IDocumentOptionsProvider>.Empty; public OptionService( IGlobalOptionService globalOptionService, HostWorkspaceServices workspaceServices) { _globalOptionService = globalOptionService; var schedulerProvider = workspaceServices.GetRequiredService<ITaskSchedulerProvider>(); var listenerProvider = workspaceServices.GetRequiredService<IWorkspaceAsynchronousOperationListenerProvider>(); _taskQueue = new TaskQueue(listenerProvider.GetListener(), schedulerProvider.CurrentContextScheduler); _globalOptionService.OptionChanged += OnGlobalOptionServiceOptionChanged; } public void OnWorkspaceDisposed(Workspace workspace) { // Disconnect us from the underlying global service. That way it doesn't // keep us around (and all the event handlers we're holding onto) forever. _globalOptionService.OptionChanged -= OnGlobalOptionServiceOptionChanged; } private void OnGlobalOptionServiceOptionChanged(object? sender, OptionChangedEventArgs e) { _taskQueue.ScheduleTask(nameof(OptionService) + "." + nameof(OnGlobalOptionServiceOptionChanged), () => { // Ensure we grab the event handlers inside the scheduled task to prevent a race of people unsubscribing // but getting the event later on the UI thread var eventHandlers = GetEventHandlers(); foreach (var handler in eventHandlers) { handler(this, e); } }, CancellationToken.None); } private ImmutableArray<EventHandler<OptionChangedEventArgs>> GetEventHandlers() { lock (_gate) { return _eventHandlers; } } public event EventHandler<OptionChangedEventArgs> OptionChanged { add { lock (_gate) { _eventHandlers = _eventHandlers.Add(value); } } remove { lock (_gate) { _eventHandlers = _eventHandlers.Remove(value); } } } // Simple forwarding functions. public SerializableOptionSet GetOptions() => GetSerializableOptionsSnapshot(ImmutableHashSet<string>.Empty); public SerializableOptionSet GetSerializableOptionsSnapshot(ImmutableHashSet<string> languages) => _globalOptionService.GetSerializableOptionsSnapshot(languages, this); public object? GetOption(OptionKey optionKey) => _globalOptionService.GetOption(optionKey); public T? GetOption<T>(Option<T> option) => _globalOptionService.GetOption(option); public T? GetOption<T>(Option2<T> option) => _globalOptionService.GetOption(option); public T? GetOption<T>(PerLanguageOption<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName); public T? GetOption<T>(PerLanguageOption2<T> option, string? languageName) => _globalOptionService.GetOption(option, languageName); public IEnumerable<IOption> GetRegisteredOptions() => _globalOptionService.GetRegisteredOptions(); public bool TryMapEditorConfigKeyToOption(string key, string? language, [NotNullWhen(true)] out IEditorConfigStorageLocation2? storageLocation, out OptionKey optionKey) => _globalOptionService.TryMapEditorConfigKeyToOption(key, language, out storageLocation, out optionKey); public ImmutableHashSet<IOption> GetRegisteredSerializableOptions(ImmutableHashSet<string> languages) => _globalOptionService.GetRegisteredSerializableOptions(languages); public void SetOptions(OptionSet optionSet) => _globalOptionService.SetOptions(optionSet); public void RegisterWorkspace(Workspace workspace) => _globalOptionService.RegisterWorkspace(workspace); public void UnregisterWorkspace(Workspace workspace) => _globalOptionService.UnregisterWorkspace(workspace); public void RegisterDocumentOptionsProvider(IDocumentOptionsProvider documentOptionsProvider) { if (documentOptionsProvider == null) { throw new ArgumentNullException(nameof(documentOptionsProvider)); } lock (_gate) { _documentOptionsProviders = _documentOptionsProviders.Add(documentOptionsProvider); } } public async Task<OptionSet> GetUpdatedOptionSetForDocumentAsync(Document document, OptionSet optionSet, CancellationToken cancellationToken) { ImmutableArray<IDocumentOptionsProvider> documentOptionsProviders; lock (_gate) { documentOptionsProviders = _documentOptionsProviders; } var realizedDocumentOptions = new List<IDocumentOptions>(); foreach (var provider in documentOptionsProviders) { cancellationToken.ThrowIfCancellationRequested(); var documentOption = await provider.GetOptionsForDocumentAsync(document, cancellationToken).ConfigureAwait(false); if (documentOption != null) { realizedDocumentOptions.Add(documentOption); } } return new DocumentSpecificOptionSet(realizedDocumentOptions, optionSet); } private class DocumentSpecificOptionSet : OptionSet { private readonly OptionSet _underlyingOptions; private readonly List<IDocumentOptions> _documentOptions; private ImmutableDictionary<OptionKey, object?> _values; public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions) : this(documentOptions, underlyingOptions, ImmutableDictionary<OptionKey, object?>.Empty) { } public DocumentSpecificOptionSet(List<IDocumentOptions> documentOptions, OptionSet underlyingOptions, ImmutableDictionary<OptionKey, object?> values) { _documentOptions = documentOptions; _underlyingOptions = underlyingOptions; _values = values; } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowLocks = false)] private protected override object? GetOptionCore(OptionKey optionKey) { // If we already know the document specific value, we're done if (_values.TryGetValue(optionKey, out var value)) { return value; } foreach (var documentOptionSource in _documentOptions) { if (documentOptionSource.TryGetDocumentOption(optionKey, out value)) { // Cache and return return ImmutableInterlocked.GetOrAdd(ref _values, optionKey, value); } } // We don't have a document specific value, so forward return _underlyingOptions.GetOption(optionKey); } public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => new DocumentSpecificOptionSet(_documentOptions, _underlyingOptions, _values.SetItem(optionAndLanguage, value)); internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) { // GetChangedOptions only needs to be supported for OptionSets that need to be compared during application, // but that's already enforced it must be a full SerializableOptionSet. throw new NotSupportedException(); } } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/Common/TaggedTextStyle.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; namespace Microsoft.CodeAnalysis { [Flags] internal enum TaggedTextStyle { None = 0, Strong = 1 << 0, Emphasis = 1 << 1, Underline = 1 << 2, Code = 1 << 3, PreserveWhitespace = 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. using System; namespace Microsoft.CodeAnalysis { [Flags] internal enum TaggedTextStyle { None = 0, Strong = 1 << 0, Emphasis = 1 << 1, Underline = 1 << 2, Code = 1 << 3, PreserveWhitespace = 1 << 4, } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/BoundTree/BoundUnaryOperator.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundUnaryOperator Public Sub New( syntax As SyntaxNode, operatorKind As UnaryOperatorKind, operand As BoundExpression, checked As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False ) Me.New(syntax, operatorKind, operand, checked, constantValueOpt:=Nothing, type:=type, hasErrors:=hasErrors OrElse operand.HasErrors()) End Sub #If DEBUG Then Private Sub Validate() ValidateConstantValue() Operand.AssertRValue() Debug.Assert(HasErrors OrElse Type.IsSameTypeIgnoringAll(Operand.Type)) End Sub #End If Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get If (OperatorKind And UnaryOperatorKind.Error) = 0 Then Dim opName As String = OverloadResolution.TryGetOperatorName(OperatorKind) If opName IsNot Nothing Then Dim op As UnaryOperatorKind = (OperatorKind And UnaryOperatorKind.OpMask) Dim operandType = DirectCast(Operand.Type.GetNullableUnderlyingTypeOrSelf(), NamedTypeSymbol) Return New SynthesizedIntrinsicOperatorSymbol(operandType, opName, Type.GetNullableUnderlyingTypeOrSelf(), Checked AndAlso operandType.IsIntegralType() AndAlso op = UnaryOperatorKind.Minus) End If End If Return Nothing 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundUnaryOperator Public Sub New( syntax As SyntaxNode, operatorKind As UnaryOperatorKind, operand As BoundExpression, checked As Boolean, type As TypeSymbol, Optional hasErrors As Boolean = False ) Me.New(syntax, operatorKind, operand, checked, constantValueOpt:=Nothing, type:=type, hasErrors:=hasErrors OrElse operand.HasErrors()) End Sub #If DEBUG Then Private Sub Validate() ValidateConstantValue() Operand.AssertRValue() Debug.Assert(HasErrors OrElse Type.IsSameTypeIgnoringAll(Operand.Type)) End Sub #End If Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get If (OperatorKind And UnaryOperatorKind.Error) = 0 Then Dim opName As String = OverloadResolution.TryGetOperatorName(OperatorKind) If opName IsNot Nothing Then Dim op As UnaryOperatorKind = (OperatorKind And UnaryOperatorKind.OpMask) Dim operandType = DirectCast(Operand.Type.GetNullableUnderlyingTypeOrSelf(), NamedTypeSymbol) Return New SynthesizedIntrinsicOperatorSymbol(operandType, opName, Type.GetNullableUnderlyingTypeOrSelf(), Checked AndAlso operandType.IsIntegralType() AndAlso op = UnaryOperatorKind.Minus) End If End If Return Nothing End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core/Undo/NoOpGlobalUndoServiceFactory.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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// This factory will create a service that provides workspace global undo service. /// </summary> [ExportWorkspaceServiceFactory(typeof(IGlobalUndoService), ServiceLayer.Default), Shared] internal class NoOpGlobalUndoServiceFactory : IWorkspaceServiceFactory { public static readonly IWorkspaceGlobalUndoTransaction Transaction = new NoOpUndoTransaction(); private readonly NoOpGlobalUndoService _singleton = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NoOpGlobalUndoServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _singleton; private class NoOpGlobalUndoService : IGlobalUndoService { public bool IsGlobalTransactionOpen(Workspace workspace) { // TODO: this is technically wrong -- Transaction shouldn't be a singleton. return false; } public bool CanUndo(Workspace workspace) { // by default, undo is not supported return false; } public IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description) => Transaction; } /// <summary> /// null object that doesn't do anything /// </summary> private class NoOpUndoTransaction : IWorkspaceGlobalUndoTransaction { public void Commit() { } public void Dispose() { } public void AddDocument(DocumentId id) { } } } }
// 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.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.Undo { /// <summary> /// This factory will create a service that provides workspace global undo service. /// </summary> [ExportWorkspaceServiceFactory(typeof(IGlobalUndoService), ServiceLayer.Default), Shared] internal class NoOpGlobalUndoServiceFactory : IWorkspaceServiceFactory { public static readonly IWorkspaceGlobalUndoTransaction Transaction = new NoOpUndoTransaction(); private readonly NoOpGlobalUndoService _singleton = new(); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NoOpGlobalUndoServiceFactory() { } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) => _singleton; private class NoOpGlobalUndoService : IGlobalUndoService { public bool IsGlobalTransactionOpen(Workspace workspace) { // TODO: this is technically wrong -- Transaction shouldn't be a singleton. return false; } public bool CanUndo(Workspace workspace) { // by default, undo is not supported return false; } public IWorkspaceGlobalUndoTransaction OpenGlobalUndoTransaction(Workspace workspace, string description) => Transaction; } /// <summary> /// null object that doesn't do anything /// </summary> private class NoOpUndoTransaction : IWorkspaceGlobalUndoTransaction { public void Commit() { } public void Dispose() { } public void AddDocument(DocumentId id) { } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Analyzers/VisualBasic/Tests/RemoveUnusedParametersAndValues/RemoveUnusedValuesTestsBase.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Public MustInherit Class RemoveUnusedValuesTestsBase Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), New VisualBasicRemoveUnusedValuesCodeFixProvider()) End Function Private Protected MustOverride ReadOnly Property PreferNone As OptionsCollection Private Protected MustOverride ReadOnly Property PreferDiscard As OptionsCollection Private Protected MustOverride ReadOnly Property PreferUnusedLocal As OptionsCollection Private Protected Overloads Function TestMissingInRegularAndScriptAsync(initialMarkup As String, options As OptionsCollection) As Task Return TestMissingInRegularAndScriptAsync(initialMarkup, New TestParameters(options:=options)) 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.RemoveUnusedParametersAndValues Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.RemoveUnusedParametersAndValues Public MustInherit Class RemoveUnusedValuesTestsBase Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicRemoveUnusedParametersAndValuesDiagnosticAnalyzer(), New VisualBasicRemoveUnusedValuesCodeFixProvider()) End Function Private Protected MustOverride ReadOnly Property PreferNone As OptionsCollection Private Protected MustOverride ReadOnly Property PreferDiscard As OptionsCollection Private Protected MustOverride ReadOnly Property PreferUnusedLocal As OptionsCollection Private Protected Overloads Function TestMissingInRegularAndScriptAsync(initialMarkup As String, options As OptionsCollection) As Task Return TestMissingInRegularAndScriptAsync(initialMarkup, New TestParameters(options:=options)) End Function End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Impl/CodeModel/Collections/NodeSnapshot.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.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class NodeSnapshot : Snapshot { private readonly CodeModelState _state; private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNode _parentNode; private readonly AbstractCodeElement _parentElement; private readonly ImmutableArray<SyntaxNode> _nodes; public NodeSnapshot( CodeModelState state, ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel, SyntaxNode parentNode, AbstractCodeElement parentElement, ImmutableArray<SyntaxNode> nodes) { _state = state; _fileCodeModel = fileCodeModel; _parentNode = parentNode; _parentElement = parentElement; _nodes = nodes; } private ICodeModelService CodeModelService { get { return _state.CodeModelService; } } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node) { this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node) { var name = this.CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node) { this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal); } private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node) { Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!"); var name = this.CodeModelService.GetParameterName(node); return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name); } public override int Count { get { return _nodes.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _nodes.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } var node = _nodes[index]; if (this.CodeModelService.IsOptionNode(node)) { return CreateCodeOptionsStatement(node); } else if (this.CodeModelService.IsImportNode(node)) { return CreateCodeImport(node); } else if (this.CodeModelService.IsAttributeNode(node)) { return CreateCodeAttribute(node); } else if (this.CodeModelService.IsParameterNode(node)) { return CreateCodeParameter(node); } // The node must be something that the FileCodeModel can create. return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class NodeSnapshot : Snapshot { private readonly CodeModelState _state; private readonly ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel; private readonly SyntaxNode _parentNode; private readonly AbstractCodeElement _parentElement; private readonly ImmutableArray<SyntaxNode> _nodes; public NodeSnapshot( CodeModelState state, ComHandle<EnvDTE.FileCodeModel, FileCodeModel> fileCodeModel, SyntaxNode parentNode, AbstractCodeElement parentElement, ImmutableArray<SyntaxNode> nodes) { _state = state; _fileCodeModel = fileCodeModel; _parentNode = parentNode; _parentElement = parentElement; _nodes = nodes; } private ICodeModelService CodeModelService { get { return _state.CodeModelService; } } private FileCodeModel FileCodeModel { get { return _fileCodeModel.Object; } } private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node) { this.CodeModelService.GetOptionNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return CodeOptionsStatement.Create(_state, this.FileCodeModel, name, ordinal); } private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node) { var name = this.CodeModelService.GetImportNamespaceOrType(node); return CodeImport.Create(_state, this.FileCodeModel, _parentElement, name); } private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node) { this.CodeModelService.GetAttributeNameAndOrdinal(_parentNode, node, out var name, out var ordinal); return (EnvDTE.CodeElement)CodeAttribute.Create(_state, this.FileCodeModel, _parentElement, name, ordinal); } private EnvDTE.CodeElement CreateCodeParameter(SyntaxNode node) { Debug.Assert(_parentElement is AbstractCodeMember, "Parameters should always have an associated member!"); var name = this.CodeModelService.GetParameterName(node); return (EnvDTE.CodeElement)CodeParameter.Create(_state, (AbstractCodeMember)_parentElement, name); } public override int Count { get { return _nodes.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _nodes.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } var node = _nodes[index]; if (this.CodeModelService.IsOptionNode(node)) { return CreateCodeOptionsStatement(node); } else if (this.CodeModelService.IsImportNode(node)) { return CreateCodeImport(node); } else if (this.CodeModelService.IsAttributeNode(node)) { return CreateCodeAttribute(node); } else if (this.CodeModelService.IsParameterNode(node)) { return CreateCodeParameter(node); } // The node must be something that the FileCodeModel can create. return this.FileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(node); } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/MetadataDecoder.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.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Helper class to resolve metadata tokens and signatures. ''' </summary> Friend Class MetadataDecoder Inherits MetadataDecoder(Of PEModuleSymbol, TypeSymbol, MethodSymbol, FieldSymbol, Symbol) ''' <summary> ''' Type context for resolving generic type arguments. ''' </summary> Private ReadOnly _typeContextOpt As PENamedTypeSymbol ''' <summary> ''' Method context for resolving generic method type arguments. ''' </summary> Private ReadOnly _methodContextOpt As PEMethodSymbol Public Sub New( moduleSymbol As PEModuleSymbol, context As PENamedTypeSymbol ) Me.New(moduleSymbol, context, Nothing) End Sub Public Sub New( moduleSymbol As PEModuleSymbol, context As PEMethodSymbol ) Me.New(moduleSymbol, DirectCast(context.ContainingType, PENamedTypeSymbol), context) End Sub Public Sub New( moduleSymbol As PEModuleSymbol ) Me.New(moduleSymbol, Nothing, Nothing) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, typeContextOpt As PENamedTypeSymbol, methodContextOpt As PEMethodSymbol ) ' TODO (tomat): if the containing assembly is a source assembly and we are about to decode assembly level attributes, we run into a cycle, ' so for now ignore the assembly identity. MyBase.New(moduleSymbol.Module, If(TypeOf moduleSymbol.ContainingAssembly Is PEAssemblySymbol, moduleSymbol.ContainingAssembly.Identity, Nothing), SymbolFactory.Instance, moduleSymbol) Debug.Assert(moduleSymbol IsNot Nothing) _typeContextOpt = typeContextOpt _methodContextOpt = methodContextOpt End Sub Friend Shadows ReadOnly Property ModuleSymbol As PEModuleSymbol Get Return MyBase.moduleSymbol End Get End Property Protected Overrides Function GetGenericMethodTypeParamSymbol(position As Integer) As TypeSymbol If _methodContextOpt Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Dim typeParameters = _methodContextOpt.TypeParameters If typeParameters.Length <= position Then Return New UnsupportedMetadataTypeSymbol() End If Return typeParameters(position) End Function Protected Overrides Function GetGenericTypeParamSymbol(position As Integer) As TypeSymbol Dim type As PENamedTypeSymbol = _typeContextOpt While type IsNot Nothing AndAlso (type.MetadataArity - type.Arity) > position type = TryCast(type.ContainingSymbol, PENamedTypeSymbol) End While If type Is Nothing OrElse type.MetadataArity <= position Then Return New UnsupportedMetadataTypeSymbol() End If position -= (type.MetadataArity - type.Arity) Debug.Assert(position >= 0 AndAlso position < type.Arity) Return type.TypeParameters(position) End Function Protected Overrides Function GetTypeHandleToTypeMap() As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) Return moduleSymbol.TypeHandleToTypeMap End Function Protected Overrides Function GetTypeRefHandleToTypeMap() As ConcurrentDictionary(Of TypeReferenceHandle, TypeSymbol) Return moduleSymbol.TypeRefHandleToTypeMap End Function Protected Overrides Function LookupNestedTypeDefSymbol( container As TypeSymbol, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim result = container.LookupMetadataType(emittedName) Debug.Assert(result IsNot Nothing) Return result End Function ''' <summary> ''' Lookup a type defined in referenced assembly. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol( referencedAssemblyIndex As Integer, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim assembly As AssemblySymbol = ModuleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex) If assembly Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Try Return assembly.LookupTopLevelMetadataType(emittedName, digThroughForwardedTypes:=True) Catch e As Exception When FatalError.ReportAndPropagate(e) ' Trying to get more useful Watson dumps. Throw ExceptionUtilities.Unreachable End Try End Function ''' <summary> ''' Lookup a type defined in a module of a multi-module assembly. ''' </summary> Protected Overrides Function LookupTopLevelTypeDefSymbol(moduleName As String, ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol For Each m As ModuleSymbol In moduleSymbol.ContainingAssembly.Modules If String.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase) Then If m Is moduleSymbol Then Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) Else isNoPiaLocalType = False Return m.LookupTopLevelMetadataType(emittedName) End If End If Next isNoPiaLocalType = False Return New MissingMetadataTypeSymbol.TopLevel(New MissingModuleSymbolWithName(moduleSymbol.ContainingAssembly, moduleName), emittedName, SpecialType.None) End Function ''' <summary> ''' Lookup a type defined in this module. ''' This method will be called only if the type we are ''' looking for hasn't been loaded yet. Otherwise, MetadataDecoder ''' would have found the type in TypeDefRowIdToTypeMap based on its ''' TypeDef row id. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol(ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) End Function Protected Overrides Function GetIndexOfReferencedAssembly(identity As AssemblyIdentity) As Integer ' Go through all assemblies referenced by the current module And ' find the one which *exactly* matches the given identity. ' No unification will be performed Dim assemblies = ModuleSymbol.GetReferencedAssemblies() For i = 0 To assemblies.Length - 1 If identity.Equals(assemblies(i)) Then Return i End If Next Return -1 End Function ''' <summary> ''' Perform a check whether the type or at least one of its generic arguments ''' is defined in the specified assemblies. The check is performed recursively. ''' </summary> Public Shared Function IsOrClosedOverATypeFromAssemblies(this As TypeSymbol, assemblies As ImmutableArray(Of AssemblySymbol)) As Boolean Select Case this.Kind Case SymbolKind.TypeParameter Return False Case SymbolKind.ArrayType Return IsOrClosedOverATypeFromAssemblies(DirectCast(this, ArrayTypeSymbol).ElementType, assemblies) Case SymbolKind.NamedType, SymbolKind.ErrorType Dim symbol = DirectCast(this, NamedTypeSymbol) Dim containingAssembly As AssemblySymbol = symbol.OriginalDefinition.ContainingAssembly If containingAssembly IsNot Nothing Then For i = 0 To assemblies.Length - 1 Step 1 If containingAssembly Is assemblies(i) Then Return True End If Next End If Do If symbol.IsTupleType Then Return IsOrClosedOverATypeFromAssemblies(symbol.TupleUnderlyingType, assemblies) End If For Each typeArgument In symbol.TypeArgumentsNoUseSiteDiagnostics If IsOrClosedOverATypeFromAssemblies(typeArgument, assemblies) Then Return True End If Next symbol = symbol.ContainingType Loop While symbol IsNot Nothing Return False Case Else Throw ExceptionUtilities.UnexpectedValue(this.Kind) End Select End Function Protected Overrides Function SubstituteNoPiaLocalType( typeDef As TypeDefinitionHandle, ByRef name As MetadataTypeName, interfaceGuid As String, scope As String, identifier As String ) As TypeSymbol Dim result As TypeSymbol Try Dim isInterface As Boolean = Me.Module.IsInterfaceOrThrow(typeDef) Dim baseType As TypeSymbol = Nothing If Not isInterface Then Dim baseToken As EntityHandle = Me.Module.GetBaseTypeOfTypeOrThrow(typeDef) If Not baseToken.IsNil() Then baseType = GetTypeOfToken(baseToken) End If End If result = SubstituteNoPiaLocalType( name, isInterface, baseType, interfaceGuid, scope, identifier, moduleSymbol.ContainingAssembly) Catch mrEx As BadImageFormatException result = GetUnsupportedMetadataTypeSymbol(mrEx) End Try Debug.Assert(result IsNot Nothing) Dim cache As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) = GetTypeHandleToTypeMap() Debug.Assert(cache IsNot Nothing) Dim newresult As TypeSymbol = cache.GetOrAdd(typeDef, result) Debug.Assert(newresult Is result OrElse (newresult.Kind = SymbolKind.ErrorType)) Return newresult End Function ''' <summary> ''' Find canonical type for NoPia embedded type. ''' </summary> ''' <returns> ''' Symbol for the canonical type or an ErrorTypeSymbol. Never returns null. ''' </returns> Friend Overloads Shared Function SubstituteNoPiaLocalType( ByRef fullEmittedName As MetadataTypeName, isInterface As Boolean, baseType As TypeSymbol, interfaceGuid As String, scope As String, identifier As String, referringAssembly As AssemblySymbol ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing Dim interfaceGuidValue As Guid = New Guid() Dim haveInterfaceGuidValue As Boolean = False Dim scopeGuidValue As Guid = New Guid() Dim haveScopeGuidValue As Boolean = False If isInterface AndAlso interfaceGuid IsNot Nothing Then haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, interfaceGuidValue) If haveInterfaceGuidValue Then ' To have consistent errors. scope = Nothing identifier = Nothing End If End If If scope IsNot Nothing Then haveScopeGuidValue = Guid.TryParse(scope, scopeGuidValue) End If For Each assembly As AssemblySymbol In referringAssembly.GetNoPiaResolutionAssemblies() Debug.Assert(assembly IsNot Nothing) If assembly Is referringAssembly Then Continue For End If Dim candidate As NamedTypeSymbol = assembly.LookupTopLevelMetadataType(fullEmittedName, digThroughForwardedTypes:=False) Debug.Assert(Not candidate.IsGenericType) ' Ignore type forwarders, error symbols and non-public types If candidate.Kind = SymbolKind.ErrorType OrElse candidate.ContainingAssembly IsNot assembly OrElse candidate.DeclaredAccessibility <> Accessibility.Public Then Continue For End If ' Ignore NoPia local types. ' If candidate is coming from metadata, we don't need to do any special check, ' because we do not create symbols for local types. However, local types defined in source ' is another story. However, if compilation explicitly defines a local type, it should be ' represented by a retargeting assembly, which is supposed to hide the local type. Debug.Assert((Not TypeOf assembly Is SourceAssemblySymbol) OrElse Not DirectCast(assembly, SourceAssemblySymbol).SourceModule.MightContainNoPiaLocalTypes()) Dim candidateGuid As String = Nothing Dim haveCandidateGuidValue As Boolean = False Dim candidateGuidValue As Guid = New Guid() ' The type must be of the same kind (interface, struct, delegate or enum). Select Case candidate.TypeKind Case TypeKind.Interface If Not isInterface Then Continue For End If ' Get candidate's Guid If candidate.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If Case TypeKind.Delegate, TypeKind.Enum, TypeKind.Structure If isInterface Then Continue For End If ' Let's use a trick. To make sure the kind is the same, make sure ' base type is the same. Dim baseSpecialType As SpecialType = If(candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType, SpecialType.None) If baseSpecialType = SpecialType.None OrElse baseSpecialType <> If(baseType?.SpecialType, SpecialType.None) Then Continue For End If Case Else Continue For End Select If haveInterfaceGuidValue OrElse haveCandidateGuidValue Then If Not haveInterfaceGuidValue OrElse Not haveCandidateGuidValue OrElse candidateGuidValue <> interfaceGuidValue Then Continue For End If Else If Not haveScopeGuidValue OrElse identifier Is Nothing OrElse Not String.Equals(identifier, fullEmittedName.FullName, StringComparison.Ordinal) Then Continue For End If ' Scope guid must match candidate's assembly guid. haveCandidateGuidValue = False If assembly.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If If Not haveCandidateGuidValue OrElse scopeGuidValue <> candidateGuidValue Then Continue For End If End If ' OK. It looks like we found canonical type definition. If result IsNot Nothing Then ' Ambiguity result = New NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate) Exit For End If result = candidate Next If result Is Nothing Then result = New NoPiaMissingCanonicalTypeSymbol( referringAssembly, fullEmittedName.FullName, interfaceGuid, scope, identifier) End If Return result End Function Protected Overrides Function FindMethodSymbolInType(typeSymbol As TypeSymbol, targetMethodDef As MethodDefinitionHandle) As MethodSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim method As PEMethodSymbol = TryCast(member, PEMethodSymbol) If method IsNot Nothing AndAlso method.Handle = targetMethodDef Then Return method End If Next Return Nothing End Function Protected Overrides Function FindFieldSymbolInType(typeSymbol As TypeSymbol, fieldDef As FieldDefinitionHandle) As FieldSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim field As PEFieldSymbol = TryCast(member, PEFieldSymbol) If field IsNot Nothing AndAlso field.Handle = fieldDef Then Return field End If Next Return Nothing End Function Friend Overrides Function GetSymbolForMemberRef(memberRef As MemberReferenceHandle, Optional scope As TypeSymbol = Nothing, Optional methodsOnly As Boolean = False) As Symbol Dim targetTypeSymbol As TypeSymbol = GetMemberRefTypeSymbol(memberRef) If targetTypeSymbol Is Nothing Then Return Nothing End If Debug.Assert(Not targetTypeSymbol.IsTupleType) If scope IsNot Nothing AndAlso Not TypeSymbol.Equals(targetTypeSymbol, scope, TypeCompareKind.ConsiderEverything) AndAlso Not targetTypeSymbol.IsBaseTypeOrInterfaceOf(scope, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Return Nothing End If If Not targetTypeSymbol.IsTupleCompatible() Then targetTypeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(targetTypeSymbol, elementNames:=Nothing) End If ' We're going to use a special decoder that can generate usable symbols for type parameters without full context. ' (We're not just using a different type - we're also changing the type context.) Dim memberRefDecoder = New MemberRefMetadataDecoder(moduleSymbol, targetTypeSymbol.OriginalDefinition) Dim definition = memberRefDecoder.FindMember(memberRef, methodsOnly) If definition IsNot Nothing AndAlso Not targetTypeSymbol.IsDefinition Then Return definition.AsMember(DirectCast(targetTypeSymbol, NamedTypeSymbol)) End If Return definition End Function Protected Overrides Sub EnqueueTypeSymbolInterfacesAndBaseTypes(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) For Each iface In typeSymbol.InterfacesNoUseSiteDiagnostics EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, iface) Next EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, typeSymbol.BaseTypeNoUseSiteDiagnostics) End Sub Protected Overrides Sub EnqueueTypeSymbol(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) If typeSymbol IsNot Nothing Then Dim peTypeSymbol As PENamedTypeSymbol = TryCast(typeSymbol, PENamedTypeSymbol) If peTypeSymbol IsNot Nothing AndAlso peTypeSymbol.ContainingPEModule Is moduleSymbol Then typeDefsToSearch.Enqueue(peTypeSymbol.Handle) Else typeSymbolsToSearch.Enqueue(typeSymbol) End If End If End Sub Protected Overrides Function GetMethodHandle(method As MethodSymbol) As MethodDefinitionHandle Dim peMethod As PEMethodSymbol = TryCast(method, PEMethodSymbol) If peMethod IsNot Nothing AndAlso peMethod.ContainingModule Is moduleSymbol Then Return peMethod.Handle End If Return Nothing 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.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' Helper class to resolve metadata tokens and signatures. ''' </summary> Friend Class MetadataDecoder Inherits MetadataDecoder(Of PEModuleSymbol, TypeSymbol, MethodSymbol, FieldSymbol, Symbol) ''' <summary> ''' Type context for resolving generic type arguments. ''' </summary> Private ReadOnly _typeContextOpt As PENamedTypeSymbol ''' <summary> ''' Method context for resolving generic method type arguments. ''' </summary> Private ReadOnly _methodContextOpt As PEMethodSymbol Public Sub New( moduleSymbol As PEModuleSymbol, context As PENamedTypeSymbol ) Me.New(moduleSymbol, context, Nothing) End Sub Public Sub New( moduleSymbol As PEModuleSymbol, context As PEMethodSymbol ) Me.New(moduleSymbol, DirectCast(context.ContainingType, PENamedTypeSymbol), context) End Sub Public Sub New( moduleSymbol As PEModuleSymbol ) Me.New(moduleSymbol, Nothing, Nothing) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, typeContextOpt As PENamedTypeSymbol, methodContextOpt As PEMethodSymbol ) ' TODO (tomat): if the containing assembly is a source assembly and we are about to decode assembly level attributes, we run into a cycle, ' so for now ignore the assembly identity. MyBase.New(moduleSymbol.Module, If(TypeOf moduleSymbol.ContainingAssembly Is PEAssemblySymbol, moduleSymbol.ContainingAssembly.Identity, Nothing), SymbolFactory.Instance, moduleSymbol) Debug.Assert(moduleSymbol IsNot Nothing) _typeContextOpt = typeContextOpt _methodContextOpt = methodContextOpt End Sub Friend Shadows ReadOnly Property ModuleSymbol As PEModuleSymbol Get Return MyBase.moduleSymbol End Get End Property Protected Overrides Function GetGenericMethodTypeParamSymbol(position As Integer) As TypeSymbol If _methodContextOpt Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Dim typeParameters = _methodContextOpt.TypeParameters If typeParameters.Length <= position Then Return New UnsupportedMetadataTypeSymbol() End If Return typeParameters(position) End Function Protected Overrides Function GetGenericTypeParamSymbol(position As Integer) As TypeSymbol Dim type As PENamedTypeSymbol = _typeContextOpt While type IsNot Nothing AndAlso (type.MetadataArity - type.Arity) > position type = TryCast(type.ContainingSymbol, PENamedTypeSymbol) End While If type Is Nothing OrElse type.MetadataArity <= position Then Return New UnsupportedMetadataTypeSymbol() End If position -= (type.MetadataArity - type.Arity) Debug.Assert(position >= 0 AndAlso position < type.Arity) Return type.TypeParameters(position) End Function Protected Overrides Function GetTypeHandleToTypeMap() As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) Return moduleSymbol.TypeHandleToTypeMap End Function Protected Overrides Function GetTypeRefHandleToTypeMap() As ConcurrentDictionary(Of TypeReferenceHandle, TypeSymbol) Return moduleSymbol.TypeRefHandleToTypeMap End Function Protected Overrides Function LookupNestedTypeDefSymbol( container As TypeSymbol, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim result = container.LookupMetadataType(emittedName) Debug.Assert(result IsNot Nothing) Return result End Function ''' <summary> ''' Lookup a type defined in referenced assembly. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol( referencedAssemblyIndex As Integer, ByRef emittedName As MetadataTypeName ) As TypeSymbol Dim assembly As AssemblySymbol = ModuleSymbol.GetReferencedAssemblySymbol(referencedAssemblyIndex) If assembly Is Nothing Then Return New UnsupportedMetadataTypeSymbol() End If Try Return assembly.LookupTopLevelMetadataType(emittedName, digThroughForwardedTypes:=True) Catch e As Exception When FatalError.ReportAndPropagate(e) ' Trying to get more useful Watson dumps. Throw ExceptionUtilities.Unreachable End Try End Function ''' <summary> ''' Lookup a type defined in a module of a multi-module assembly. ''' </summary> Protected Overrides Function LookupTopLevelTypeDefSymbol(moduleName As String, ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol For Each m As ModuleSymbol In moduleSymbol.ContainingAssembly.Modules If String.Equals(m.Name, moduleName, StringComparison.OrdinalIgnoreCase) Then If m Is moduleSymbol Then Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) Else isNoPiaLocalType = False Return m.LookupTopLevelMetadataType(emittedName) End If End If Next isNoPiaLocalType = False Return New MissingMetadataTypeSymbol.TopLevel(New MissingModuleSymbolWithName(moduleSymbol.ContainingAssembly, moduleName), emittedName, SpecialType.None) End Function ''' <summary> ''' Lookup a type defined in this module. ''' This method will be called only if the type we are ''' looking for hasn't been loaded yet. Otherwise, MetadataDecoder ''' would have found the type in TypeDefRowIdToTypeMap based on its ''' TypeDef row id. ''' </summary> Protected Overloads Overrides Function LookupTopLevelTypeDefSymbol(ByRef emittedName As MetadataTypeName, <Out> ByRef isNoPiaLocalType As Boolean) As TypeSymbol Return moduleSymbol.LookupTopLevelMetadataType(emittedName, isNoPiaLocalType) End Function Protected Overrides Function GetIndexOfReferencedAssembly(identity As AssemblyIdentity) As Integer ' Go through all assemblies referenced by the current module And ' find the one which *exactly* matches the given identity. ' No unification will be performed Dim assemblies = ModuleSymbol.GetReferencedAssemblies() For i = 0 To assemblies.Length - 1 If identity.Equals(assemblies(i)) Then Return i End If Next Return -1 End Function ''' <summary> ''' Perform a check whether the type or at least one of its generic arguments ''' is defined in the specified assemblies. The check is performed recursively. ''' </summary> Public Shared Function IsOrClosedOverATypeFromAssemblies(this As TypeSymbol, assemblies As ImmutableArray(Of AssemblySymbol)) As Boolean Select Case this.Kind Case SymbolKind.TypeParameter Return False Case SymbolKind.ArrayType Return IsOrClosedOverATypeFromAssemblies(DirectCast(this, ArrayTypeSymbol).ElementType, assemblies) Case SymbolKind.NamedType, SymbolKind.ErrorType Dim symbol = DirectCast(this, NamedTypeSymbol) Dim containingAssembly As AssemblySymbol = symbol.OriginalDefinition.ContainingAssembly If containingAssembly IsNot Nothing Then For i = 0 To assemblies.Length - 1 Step 1 If containingAssembly Is assemblies(i) Then Return True End If Next End If Do If symbol.IsTupleType Then Return IsOrClosedOverATypeFromAssemblies(symbol.TupleUnderlyingType, assemblies) End If For Each typeArgument In symbol.TypeArgumentsNoUseSiteDiagnostics If IsOrClosedOverATypeFromAssemblies(typeArgument, assemblies) Then Return True End If Next symbol = symbol.ContainingType Loop While symbol IsNot Nothing Return False Case Else Throw ExceptionUtilities.UnexpectedValue(this.Kind) End Select End Function Protected Overrides Function SubstituteNoPiaLocalType( typeDef As TypeDefinitionHandle, ByRef name As MetadataTypeName, interfaceGuid As String, scope As String, identifier As String ) As TypeSymbol Dim result As TypeSymbol Try Dim isInterface As Boolean = Me.Module.IsInterfaceOrThrow(typeDef) Dim baseType As TypeSymbol = Nothing If Not isInterface Then Dim baseToken As EntityHandle = Me.Module.GetBaseTypeOfTypeOrThrow(typeDef) If Not baseToken.IsNil() Then baseType = GetTypeOfToken(baseToken) End If End If result = SubstituteNoPiaLocalType( name, isInterface, baseType, interfaceGuid, scope, identifier, moduleSymbol.ContainingAssembly) Catch mrEx As BadImageFormatException result = GetUnsupportedMetadataTypeSymbol(mrEx) End Try Debug.Assert(result IsNot Nothing) Dim cache As ConcurrentDictionary(Of TypeDefinitionHandle, TypeSymbol) = GetTypeHandleToTypeMap() Debug.Assert(cache IsNot Nothing) Dim newresult As TypeSymbol = cache.GetOrAdd(typeDef, result) Debug.Assert(newresult Is result OrElse (newresult.Kind = SymbolKind.ErrorType)) Return newresult End Function ''' <summary> ''' Find canonical type for NoPia embedded type. ''' </summary> ''' <returns> ''' Symbol for the canonical type or an ErrorTypeSymbol. Never returns null. ''' </returns> Friend Overloads Shared Function SubstituteNoPiaLocalType( ByRef fullEmittedName As MetadataTypeName, isInterface As Boolean, baseType As TypeSymbol, interfaceGuid As String, scope As String, identifier As String, referringAssembly As AssemblySymbol ) As NamedTypeSymbol Dim result As NamedTypeSymbol = Nothing Dim interfaceGuidValue As Guid = New Guid() Dim haveInterfaceGuidValue As Boolean = False Dim scopeGuidValue As Guid = New Guid() Dim haveScopeGuidValue As Boolean = False If isInterface AndAlso interfaceGuid IsNot Nothing Then haveInterfaceGuidValue = Guid.TryParse(interfaceGuid, interfaceGuidValue) If haveInterfaceGuidValue Then ' To have consistent errors. scope = Nothing identifier = Nothing End If End If If scope IsNot Nothing Then haveScopeGuidValue = Guid.TryParse(scope, scopeGuidValue) End If For Each assembly As AssemblySymbol In referringAssembly.GetNoPiaResolutionAssemblies() Debug.Assert(assembly IsNot Nothing) If assembly Is referringAssembly Then Continue For End If Dim candidate As NamedTypeSymbol = assembly.LookupTopLevelMetadataType(fullEmittedName, digThroughForwardedTypes:=False) Debug.Assert(Not candidate.IsGenericType) ' Ignore type forwarders, error symbols and non-public types If candidate.Kind = SymbolKind.ErrorType OrElse candidate.ContainingAssembly IsNot assembly OrElse candidate.DeclaredAccessibility <> Accessibility.Public Then Continue For End If ' Ignore NoPia local types. ' If candidate is coming from metadata, we don't need to do any special check, ' because we do not create symbols for local types. However, local types defined in source ' is another story. However, if compilation explicitly defines a local type, it should be ' represented by a retargeting assembly, which is supposed to hide the local type. Debug.Assert((Not TypeOf assembly Is SourceAssemblySymbol) OrElse Not DirectCast(assembly, SourceAssemblySymbol).SourceModule.MightContainNoPiaLocalTypes()) Dim candidateGuid As String = Nothing Dim haveCandidateGuidValue As Boolean = False Dim candidateGuidValue As Guid = New Guid() ' The type must be of the same kind (interface, struct, delegate or enum). Select Case candidate.TypeKind Case TypeKind.Interface If Not isInterface Then Continue For End If ' Get candidate's Guid If candidate.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If Case TypeKind.Delegate, TypeKind.Enum, TypeKind.Structure If isInterface Then Continue For End If ' Let's use a trick. To make sure the kind is the same, make sure ' base type is the same. Dim baseSpecialType As SpecialType = If(candidate.BaseTypeNoUseSiteDiagnostics?.SpecialType, SpecialType.None) If baseSpecialType = SpecialType.None OrElse baseSpecialType <> If(baseType?.SpecialType, SpecialType.None) Then Continue For End If Case Else Continue For End Select If haveInterfaceGuidValue OrElse haveCandidateGuidValue Then If Not haveInterfaceGuidValue OrElse Not haveCandidateGuidValue OrElse candidateGuidValue <> interfaceGuidValue Then Continue For End If Else If Not haveScopeGuidValue OrElse identifier Is Nothing OrElse Not String.Equals(identifier, fullEmittedName.FullName, StringComparison.Ordinal) Then Continue For End If ' Scope guid must match candidate's assembly guid. haveCandidateGuidValue = False If assembly.GetGuidString(candidateGuid) AndAlso candidateGuid IsNot Nothing Then haveCandidateGuidValue = Guid.TryParse(candidateGuid, candidateGuidValue) End If If Not haveCandidateGuidValue OrElse scopeGuidValue <> candidateGuidValue Then Continue For End If End If ' OK. It looks like we found canonical type definition. If result IsNot Nothing Then ' Ambiguity result = New NoPiaAmbiguousCanonicalTypeSymbol(referringAssembly, result, candidate) Exit For End If result = candidate Next If result Is Nothing Then result = New NoPiaMissingCanonicalTypeSymbol( referringAssembly, fullEmittedName.FullName, interfaceGuid, scope, identifier) End If Return result End Function Protected Overrides Function FindMethodSymbolInType(typeSymbol As TypeSymbol, targetMethodDef As MethodDefinitionHandle) As MethodSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim method As PEMethodSymbol = TryCast(member, PEMethodSymbol) If method IsNot Nothing AndAlso method.Handle = targetMethodDef Then Return method End If Next Return Nothing End Function Protected Overrides Function FindFieldSymbolInType(typeSymbol As TypeSymbol, fieldDef As FieldDefinitionHandle) As FieldSymbol Debug.Assert(TypeOf typeSymbol Is PENamedTypeSymbol OrElse TypeOf typeSymbol Is ErrorTypeSymbol) For Each member In typeSymbol.GetMembersUnordered() Dim field As PEFieldSymbol = TryCast(member, PEFieldSymbol) If field IsNot Nothing AndAlso field.Handle = fieldDef Then Return field End If Next Return Nothing End Function Friend Overrides Function GetSymbolForMemberRef(memberRef As MemberReferenceHandle, Optional scope As TypeSymbol = Nothing, Optional methodsOnly As Boolean = False) As Symbol Dim targetTypeSymbol As TypeSymbol = GetMemberRefTypeSymbol(memberRef) If targetTypeSymbol Is Nothing Then Return Nothing End If Debug.Assert(Not targetTypeSymbol.IsTupleType) If scope IsNot Nothing AndAlso Not TypeSymbol.Equals(targetTypeSymbol, scope, TypeCompareKind.ConsiderEverything) AndAlso Not targetTypeSymbol.IsBaseTypeOrInterfaceOf(scope, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Return Nothing End If If Not targetTypeSymbol.IsTupleCompatible() Then targetTypeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(targetTypeSymbol, elementNames:=Nothing) End If ' We're going to use a special decoder that can generate usable symbols for type parameters without full context. ' (We're not just using a different type - we're also changing the type context.) Dim memberRefDecoder = New MemberRefMetadataDecoder(moduleSymbol, targetTypeSymbol.OriginalDefinition) Dim definition = memberRefDecoder.FindMember(memberRef, methodsOnly) If definition IsNot Nothing AndAlso Not targetTypeSymbol.IsDefinition Then Return definition.AsMember(DirectCast(targetTypeSymbol, NamedTypeSymbol)) End If Return definition End Function Protected Overrides Sub EnqueueTypeSymbolInterfacesAndBaseTypes(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) For Each iface In typeSymbol.InterfacesNoUseSiteDiagnostics EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, iface) Next EnqueueTypeSymbol(typeDefsToSearch, typeSymbolsToSearch, typeSymbol.BaseTypeNoUseSiteDiagnostics) End Sub Protected Overrides Sub EnqueueTypeSymbol(typeDefsToSearch As Queue(Of TypeDefinitionHandle), typeSymbolsToSearch As Queue(Of TypeSymbol), typeSymbol As TypeSymbol) If typeSymbol IsNot Nothing Then Dim peTypeSymbol As PENamedTypeSymbol = TryCast(typeSymbol, PENamedTypeSymbol) If peTypeSymbol IsNot Nothing AndAlso peTypeSymbol.ContainingPEModule Is moduleSymbol Then typeDefsToSearch.Enqueue(peTypeSymbol.Handle) Else typeSymbolsToSearch.Enqueue(typeSymbol) End If End If End Sub Protected Overrides Function GetMethodHandle(method As MethodSymbol) As MethodDefinitionHandle Dim peMethod As PEMethodSymbol = TryCast(method, PEMethodSymbol) If peMethod IsNot Nothing AndAlso peMethod.ContainingModule Is moduleSymbol Then Return peMethod.Handle End If Return Nothing End Function End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/StackAllocKeywordRecommender.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 StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public StackAllocKeywordRecommender() : base(SyntaxKind.StackAllocKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // Beginning with C# 8.0, stackalloc expression can be used inside other expressions // whenever a Span<T> or ReadOnlySpan<T> variable is allowed. return (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) || 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 StackAllocKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public StackAllocKeywordRecommender() : base(SyntaxKind.StackAllocKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { // Beginning with C# 8.0, stackalloc expression can be used inside other expressions // whenever a Span<T> or ReadOnlySpan<T> variable is allowed. return (context.IsAnyExpressionContext && !context.IsConstantExpressionContext) || context.IsStatementContext || context.IsGlobalStatementContext; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/AddPackage/InstallPackageDirectlyCodeActionOperation.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 Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.AddPackage { /// <summary> /// Operation responsible purely for installing a nuget package with a specific /// version, or a the latest version of a nuget package. Is not responsible /// for adding an import to user code. /// </summary> internal class InstallPackageDirectlyCodeActionOperation : CodeActionOperation { private readonly Document _document; private readonly IPackageInstallerService _installerService; private readonly string _source; private readonly string _packageName; private readonly string _versionOpt; private readonly bool _includePrerelease; private readonly bool _isLocal; private readonly List<string> _projectsWithMatchingVersion; public InstallPackageDirectlyCodeActionOperation( IPackageInstallerService installerService, Document document, string source, string packageName, string versionOpt, bool includePrerelease, bool isLocal) { _installerService = installerService; _document = document; _source = source; _packageName = packageName; _versionOpt = versionOpt; _includePrerelease = includePrerelease; _isLocal = isLocal; if (versionOpt != null) { const int projectsToShow = 5; var otherProjects = installerService.GetProjectsWithInstalledPackage( _document.Project.Solution, packageName, versionOpt).ToList(); _projectsWithMatchingVersion = otherProjects.Take(projectsToShow).Select(p => p.Name).ToList(); if (otherProjects.Count > projectsToShow) { _projectsWithMatchingVersion.Add("..."); } } } public override string Title => _versionOpt == null ? string.Format(FeaturesResources.Find_and_install_latest_version_of_0, _packageName) : _isLocal ? string.Format(FeaturesResources.Use_locally_installed_0_version_1_This_version_used_in_colon_2, _packageName, _versionOpt, string.Join(", ", _projectsWithMatchingVersion)) : string.Format(FeaturesResources.Install_0_1, _packageName, _versionOpt); internal override bool ApplyDuringTests => true; internal override bool TryApply( Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { return _installerService.TryInstallPackage( workspace, _document.Id, _source, _packageName, _versionOpt, _includePrerelease, progressTracker, 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.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.AddPackage { /// <summary> /// Operation responsible purely for installing a nuget package with a specific /// version, or a the latest version of a nuget package. Is not responsible /// for adding an import to user code. /// </summary> internal class InstallPackageDirectlyCodeActionOperation : CodeActionOperation { private readonly Document _document; private readonly IPackageInstallerService _installerService; private readonly string _source; private readonly string _packageName; private readonly string _versionOpt; private readonly bool _includePrerelease; private readonly bool _isLocal; private readonly List<string> _projectsWithMatchingVersion; public InstallPackageDirectlyCodeActionOperation( IPackageInstallerService installerService, Document document, string source, string packageName, string versionOpt, bool includePrerelease, bool isLocal) { _installerService = installerService; _document = document; _source = source; _packageName = packageName; _versionOpt = versionOpt; _includePrerelease = includePrerelease; _isLocal = isLocal; if (versionOpt != null) { const int projectsToShow = 5; var otherProjects = installerService.GetProjectsWithInstalledPackage( _document.Project.Solution, packageName, versionOpt).ToList(); _projectsWithMatchingVersion = otherProjects.Take(projectsToShow).Select(p => p.Name).ToList(); if (otherProjects.Count > projectsToShow) { _projectsWithMatchingVersion.Add("..."); } } } public override string Title => _versionOpt == null ? string.Format(FeaturesResources.Find_and_install_latest_version_of_0, _packageName) : _isLocal ? string.Format(FeaturesResources.Use_locally_installed_0_version_1_This_version_used_in_colon_2, _packageName, _versionOpt, string.Join(", ", _projectsWithMatchingVersion)) : string.Format(FeaturesResources.Install_0_1, _packageName, _versionOpt); internal override bool ApplyDuringTests => true; internal override bool TryApply( Workspace workspace, IProgressTracker progressTracker, CancellationToken cancellationToken) { return _installerService.TryInstallPackage( workspace, _document.Id, _source, _packageName, _versionOpt, _includePrerelease, progressTracker, cancellationToken); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrCastExpressionOptions.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger.Clr { public enum DkmClrCastExpressionOptions { None = 0, ConditionalCast = 1, ParenthesizeArgument = 2, ParenthesizeEntireExpression = 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion namespace Microsoft.VisualStudio.Debugger.Clr { public enum DkmClrCastExpressionOptions { None = 0, ConditionalCast = 1, ParenthesizeArgument = 2, ParenthesizeEntireExpression = 4 } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/CSharpTest/CSharpCommandLineParserServiceTests.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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public sealed class CSharpCommandLineParserServiceTests { private static readonly string s_directory = Path.GetTempPath(); private readonly CSharpCommandLineParserService _parser = new CSharpCommandLineParserService(); private CSharpCommandLineArguments GetArguments(params string[] args) => (CSharpCommandLineArguments)_parser.Parse(args, baseDirectory: s_directory, isInteractive: false, sdkDirectory: s_directory); private CSharpParseOptions GetParseOptions(params string[] args) => GetArguments(args).ParseOptions; [Fact] public void FeaturesSingle() { var options = GetParseOptions("/features:test"); Assert.Equal("true", options.Features["test"]); } [Fact] public void FeaturesSingleWithValue() { var options = GetParseOptions("/features:test=dog"); Assert.Equal("dog", options.Features["test"]); } [Fact] public void FeaturesMultiple() { var options = GetParseOptions("/features:test1", "/features:test2"); Assert.Equal("true", options.Features["test1"]); Assert.Equal("true", options.Features["test2"]); } [Fact] public void FeaturesMultipleWithValue() { var options = GetParseOptions("/features:test1=dog", "/features:test2=cat"); Assert.Equal("dog", options.Features["test1"]); Assert.Equal("cat", options.Features["test2"]); } } }
// 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public sealed class CSharpCommandLineParserServiceTests { private static readonly string s_directory = Path.GetTempPath(); private readonly CSharpCommandLineParserService _parser = new CSharpCommandLineParserService(); private CSharpCommandLineArguments GetArguments(params string[] args) => (CSharpCommandLineArguments)_parser.Parse(args, baseDirectory: s_directory, isInteractive: false, sdkDirectory: s_directory); private CSharpParseOptions GetParseOptions(params string[] args) => GetArguments(args).ParseOptions; [Fact] public void FeaturesSingle() { var options = GetParseOptions("/features:test"); Assert.Equal("true", options.Features["test"]); } [Fact] public void FeaturesSingleWithValue() { var options = GetParseOptions("/features:test=dog"); Assert.Equal("dog", options.Features["test"]); } [Fact] public void FeaturesMultiple() { var options = GetParseOptions("/features:test1", "/features:test2"); Assert.Equal("true", options.Features["test1"]); Assert.Equal("true", options.Features["test2"]); } [Fact] public void FeaturesMultipleWithValue() { var options = GetParseOptions("/features:test1=dog", "/features:test2=cat"); Assert.Equal("dog", options.Features["test1"]); Assert.Equal("cat", options.Features["test2"]); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState_Checksum.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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { public bool TryGetStateChecksums([NotNullWhen(true)] out SolutionStateChecksums? stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public bool TryGetStateChecksums(ProjectId projectId, out (SerializableOptionSet options, SolutionStateChecksums checksums) result) { (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums) value; lock (_lazyProjectChecksums) { if (!_lazyProjectChecksums.TryGetValue(projectId, out value) || value.checksums == null) { result = default; return false; } } if (!value.checksums.TryGetValue(out var stateChecksums)) { result = default; return false; } result = (value.options, stateChecksums); return true; } public Task<SolutionStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { var collection = await GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); return collection.Checksum; } /// <summary>Gets the checksum for only the requested project (and any project it depends on)</summary> public async Task<SolutionStateChecksums> GetStateChecksumsAsync( ProjectId projectId, CancellationToken cancellationToken) { Contract.ThrowIfNull(projectId); (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums) value; lock (_lazyProjectChecksums) { if (!_lazyProjectChecksums.TryGetValue(projectId, out value)) { value = Compute(projectId); _lazyProjectChecksums.Add(projectId, value); } } var collection = await value.checksums.GetValueAsync(cancellationToken).ConfigureAwait(false); return collection; // Extracted as a local function to prevent delegate allocations when not needed. (SerializableOptionSet, ValueSource<SolutionStateChecksums>) Compute(ProjectId projectId) { var projectsToInclude = new HashSet<ProjectId>(); AddReferencedProjects(projectsToInclude, projectId); // we're syncing a subset of projects, so only sync the options for the particular languages // we're syncing over. var languages = projectsToInclude.Select(id => ProjectStates[id].Language) .Where(s => RemoteSupportedLanguages.IsSupported(s)) .ToImmutableHashSet(); var options = this.Options.WithLanguages(languages); return (options, new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude, options, c), cacheResult: true)); } void AddReferencedProjects(HashSet<ProjectId> result, ProjectId projectId) { if (!result.Add(projectId)) return; var projectState = this.GetProjectState(projectId); if (projectState == null) return; foreach (var refProject in projectState.ProjectReferences) AddReferencedProjects(result, refProject.ProjectId); } } /// <summary>Gets the checksum for only the requested project (and any project it depends on)</summary> public async Task<Checksum> GetChecksumAsync(ProjectId projectId, CancellationToken cancellationToken) { var checksums = await GetStateChecksumsAsync(projectId, cancellationToken).ConfigureAwait(false); return checksums.Checksum; } /// <param name="projectsToInclude">Cone of projects to compute a checksum for. Pass in <see langword="null"/> /// to get a checksum for the entire solution</param> private async Task<SolutionStateChecksums> ComputeChecksumsAsync( HashSet<ProjectId>? projectsToInclude, SerializableOptionSet options, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.SolutionState_ComputeChecksumsAsync, FilePath, cancellationToken)) { // get states by id order to have deterministic checksum. Limit to the requested set of projects // if applicable. var orderedProjectIds = ChecksumCache.GetOrCreate(ProjectIds, _ => ProjectIds.OrderBy(id => id.Id).ToImmutableArray()); var projectChecksumTasks = orderedProjectIds.Where(id => projectsToInclude == null || projectsToInclude.Contains(id)) .Select(id => ProjectStates[id]) .Where(s => RemoteSupportedLanguages.IsSupported(s.Language)) .Select(s => s.GetChecksumAsync(cancellationToken)) .ToArray(); var serializer = _solutionServices.Workspace.Services.GetRequiredService<ISerializerService>(); var attributesChecksum = serializer.CreateChecksum(SolutionAttributes, cancellationToken); var optionsChecksum = serializer.CreateChecksum(options, cancellationToken); var frozenSourceGeneratedDocumentIdentityChecksum = Checksum.Null; var frozenSourceGeneratedDocumentTextChecksum = Checksum.Null; if (FrozenSourceGeneratedDocumentState != null) { frozenSourceGeneratedDocumentIdentityChecksum = serializer.CreateChecksum(FrozenSourceGeneratedDocumentState.Identity, cancellationToken); frozenSourceGeneratedDocumentTextChecksum = (await FrozenSourceGeneratedDocumentState.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; } var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var projectChecksums = await Task.WhenAll(projectChecksumTasks).ConfigureAwait(false); return new SolutionStateChecksums(attributesChecksum, optionsChecksum, new ChecksumCollection(projectChecksums), analyzerReferenceChecksums, frozenSourceGeneratedDocumentIdentityChecksum, frozenSourceGeneratedDocumentTextChecksum); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
// 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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Serialization; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { public bool TryGetStateChecksums([NotNullWhen(true)] out SolutionStateChecksums? stateChecksums) => _lazyChecksums.TryGetValue(out stateChecksums); public bool TryGetStateChecksums(ProjectId projectId, out (SerializableOptionSet options, SolutionStateChecksums checksums) result) { (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums) value; lock (_lazyProjectChecksums) { if (!_lazyProjectChecksums.TryGetValue(projectId, out value) || value.checksums == null) { result = default; return false; } } if (!value.checksums.TryGetValue(out var stateChecksums)) { result = default; return false; } result = (value.options, stateChecksums); return true; } public Task<SolutionStateChecksums> GetStateChecksumsAsync(CancellationToken cancellationToken) => _lazyChecksums.GetValueAsync(cancellationToken); public async Task<Checksum> GetChecksumAsync(CancellationToken cancellationToken) { var collection = await GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); return collection.Checksum; } /// <summary>Gets the checksum for only the requested project (and any project it depends on)</summary> public async Task<SolutionStateChecksums> GetStateChecksumsAsync( ProjectId projectId, CancellationToken cancellationToken) { Contract.ThrowIfNull(projectId); (SerializableOptionSet options, ValueSource<SolutionStateChecksums> checksums) value; lock (_lazyProjectChecksums) { if (!_lazyProjectChecksums.TryGetValue(projectId, out value)) { value = Compute(projectId); _lazyProjectChecksums.Add(projectId, value); } } var collection = await value.checksums.GetValueAsync(cancellationToken).ConfigureAwait(false); return collection; // Extracted as a local function to prevent delegate allocations when not needed. (SerializableOptionSet, ValueSource<SolutionStateChecksums>) Compute(ProjectId projectId) { var projectsToInclude = new HashSet<ProjectId>(); AddReferencedProjects(projectsToInclude, projectId); // we're syncing a subset of projects, so only sync the options for the particular languages // we're syncing over. var languages = projectsToInclude.Select(id => ProjectStates[id].Language) .Where(s => RemoteSupportedLanguages.IsSupported(s)) .ToImmutableHashSet(); var options = this.Options.WithLanguages(languages); return (options, new AsyncLazy<SolutionStateChecksums>( c => ComputeChecksumsAsync(projectsToInclude, options, c), cacheResult: true)); } void AddReferencedProjects(HashSet<ProjectId> result, ProjectId projectId) { if (!result.Add(projectId)) return; var projectState = this.GetProjectState(projectId); if (projectState == null) return; foreach (var refProject in projectState.ProjectReferences) AddReferencedProjects(result, refProject.ProjectId); } } /// <summary>Gets the checksum for only the requested project (and any project it depends on)</summary> public async Task<Checksum> GetChecksumAsync(ProjectId projectId, CancellationToken cancellationToken) { var checksums = await GetStateChecksumsAsync(projectId, cancellationToken).ConfigureAwait(false); return checksums.Checksum; } /// <param name="projectsToInclude">Cone of projects to compute a checksum for. Pass in <see langword="null"/> /// to get a checksum for the entire solution</param> private async Task<SolutionStateChecksums> ComputeChecksumsAsync( HashSet<ProjectId>? projectsToInclude, SerializableOptionSet options, CancellationToken cancellationToken) { try { using (Logger.LogBlock(FunctionId.SolutionState_ComputeChecksumsAsync, FilePath, cancellationToken)) { // get states by id order to have deterministic checksum. Limit to the requested set of projects // if applicable. var orderedProjectIds = ChecksumCache.GetOrCreate(ProjectIds, _ => ProjectIds.OrderBy(id => id.Id).ToImmutableArray()); var projectChecksumTasks = orderedProjectIds.Where(id => projectsToInclude == null || projectsToInclude.Contains(id)) .Select(id => ProjectStates[id]) .Where(s => RemoteSupportedLanguages.IsSupported(s.Language)) .Select(s => s.GetChecksumAsync(cancellationToken)) .ToArray(); var serializer = _solutionServices.Workspace.Services.GetRequiredService<ISerializerService>(); var attributesChecksum = serializer.CreateChecksum(SolutionAttributes, cancellationToken); var optionsChecksum = serializer.CreateChecksum(options, cancellationToken); var frozenSourceGeneratedDocumentIdentityChecksum = Checksum.Null; var frozenSourceGeneratedDocumentTextChecksum = Checksum.Null; if (FrozenSourceGeneratedDocumentState != null) { frozenSourceGeneratedDocumentIdentityChecksum = serializer.CreateChecksum(FrozenSourceGeneratedDocumentState.Identity, cancellationToken); frozenSourceGeneratedDocumentTextChecksum = (await FrozenSourceGeneratedDocumentState.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; } var analyzerReferenceChecksums = ChecksumCache.GetOrCreate<ChecksumCollection>(AnalyzerReferences, _ => new ChecksumCollection(AnalyzerReferences.Select(r => serializer.CreateChecksum(r, cancellationToken)).ToArray())); var projectChecksums = await Task.WhenAll(projectChecksumTasks).ConfigureAwait(false); return new SolutionStateChecksums(attributesChecksum, optionsChecksum, new ChecksumCollection(projectChecksums), analyzerReferenceChecksums, frozenSourceGeneratedDocumentIdentityChecksum, frozenSourceGeneratedDocumentTextChecksum); } } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Compilation_WellKnownMembers.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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpCompilation { internal readonly WellKnownMembersSignatureComparer WellKnownMemberSignatureComparer; /// <summary> /// An array of cached well known types available for use in this Compilation. /// Lazily filled by GetWellKnownType method. /// </summary> private NamedTypeSymbol?[]? _lazyWellKnownTypes; /// <summary> /// Lazy cache of well known members. /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol?[]? _lazyWellKnownTypeMembers; private bool _usesNullableAttributes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return (EmbeddableAttributes)_needsGeneratedAttributes; } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal bool GetUsesNullableAttributes() { _needsGeneratedAttributes_IsFrozen = true; return _usesNullableAttributes; } private void SetUsesNullableAttributes() { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); _usesNullableAttributes = true; } /// <summary> /// Lookup member declaration in well known type used by this Compilation. /// </summary> /// <remarks> /// If a well-known member of a generic type instantiation is needed use this method to get the corresponding generic definition and /// <see cref="MethodSymbol.AsMember"/> to construct an instantiation. /// </remarks> internal Symbol? GetWellKnownTypeMember(WellKnownMember member) { Debug.Assert(member >= 0 && member < WellKnownMember.Count); // Test hook: if a member is marked missing, then return null. if (IsMemberMissing(member)) return null; if (_lazyWellKnownTypeMembers == null || ReferenceEquals(_lazyWellKnownTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazyWellKnownTypeMembers == null) { var wellKnownTypeMembers = new Symbol[(int)WellKnownMember.Count]; for (int i = 0; i < wellKnownTypeMembers.Length; i++) { wellKnownTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers, wellKnownTypeMembers, null); } MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); NamedTypeSymbol type = descriptor.DeclaringTypeId <= (int)SpecialType.Count ? this.GetSpecialType((SpecialType)descriptor.DeclaringTypeId) : this.GetWellKnownType((WellKnownType)descriptor.DeclaringTypeId); Symbol? result = null; if (!type.IsErrorType()) { result = GetRuntimeMember(type, descriptor, WellKnownMemberSignatureComparer, accessWithinOpt: this.Assembly); } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazyWellKnownTypeMembers[(int)member]; } /// <summary> /// This method handles duplicate types in a few different ways: /// - for types before C# 7, the first candidate is returned with a warning /// - for types after C# 7, the type is considered missing /// - in both cases, when BinderFlags.IgnoreCorLibraryDuplicatedTypes is set, type from corlib will not count as a duplicate /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type) { Debug.Assert(type.IsValid()); bool ignoreCorLibraryDuplicatedTypes = this.Options.TopLevelBinderFlags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes); int index = (int)type - (int)WellKnownType.First; if (_lazyWellKnownTypes == null || _lazyWellKnownTypes[index] is null) { if (_lazyWellKnownTypes == null) { Interlocked.CompareExchange(ref _lazyWellKnownTypes, new NamedTypeSymbol[(int)WellKnownTypes.Count], null); } string mdName = type.GetMetadataName(); var warnings = DiagnosticBag.GetInstance(); NamedTypeSymbol? result; (AssemblySymbol, AssemblySymbol) conflicts = default; if (IsTypeMissing(type)) { result = null; } else { // well-known types introduced before CSharp7 allow lookup ambiguity and report a warning DiagnosticBag? legacyWarnings = (type <= WellKnownType.CSharp7Sentinel) ? warnings : null; result = this.Assembly.GetTypeByMetadataName( mdName, includeReferences: true, useCLSCompliantNameArityEncoding: true, isWellKnownType: true, conflicts: out conflicts, warnings: legacyWarnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); } if (result is null) { // TODO: should GetTypeByMetadataName rather return a missing symbol? MetadataTypeName emittedName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding: true); if (type.IsValueTupleType()) { CSDiagnosticInfo errorInfo; if (conflicts.Item1 is null) { Debug.Assert(conflicts.Item2 is null); errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, emittedName.FullName); } else { errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, emittedName.FullName, conflicts.Item1, conflicts.Item2); } result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type, errorInfo); } else { result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type); } } if (Interlocked.CompareExchange(ref _lazyWellKnownTypes[index], result, null) is object) { Debug.Assert( TypeSymbol.Equals(result, _lazyWellKnownTypes[index], TypeCompareKind.ConsiderEverything2) || (_lazyWellKnownTypes[index]!.IsErrorType() && result.IsErrorType()) ); } else { AdditionalCodegenWarnings.AddRange(warnings); } warnings.Free(); } return _lazyWellKnownTypes[index]!; } internal bool IsAttributeType(TypeSymbol type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Attribute, ref discardedUseSiteInfo); } internal override bool IsAttributeType(ITypeSymbol type) { return IsAttributeType(type.EnsureCSharpSymbolOrNull(nameof(type))); } internal bool IsExceptionType(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Exception, ref useSiteInfo); } internal bool IsReadOnlySpanType(TypeSymbol type) { return TypeSymbol.Equals(type.OriginalDefinition, GetWellKnownType(WellKnownType.System_ReadOnlySpan_T), TypeCompareKind.ConsiderEverything2); } internal bool IsEqualOrDerivedFromWellKnownClass(TypeSymbol type, WellKnownType wellKnownType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(wellKnownType == WellKnownType.System_Attribute || wellKnownType == WellKnownType.System_Exception); if (type.Kind != SymbolKind.NamedType || type.TypeKind != TypeKind.Class) { return false; } var wkType = GetWellKnownType(wellKnownType); return type.Equals(wkType, TypeCompareKind.ConsiderEverything) || type.IsDerivedFrom(wkType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo); } internal override bool IsSystemTypeReference(ITypeSymbolInternal type) { return TypeSymbol.Equals((TypeSymbol)type, GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything2); } internal override ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member) { return GetWellKnownTypeMember(member); } internal override ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType) { return GetWellKnownType(wellknownType); } internal static Symbol? GetRuntimeMember(NamedTypeSymbol declaringType, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { var members = declaringType.GetMembers(descriptor.Name); return GetRuntimeMember(members, descriptor, comparer, accessWithinOpt); } internal static Symbol? GetRuntimeMember(ImmutableArray<Symbol> members, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { SymbolKind targetSymbolKind; MethodKind targetMethodKind = MethodKind.Ordinary; bool isStatic = (descriptor.Flags & MemberFlags.Static) != 0; Symbol? result = null; switch (descriptor.Flags & MemberFlags.KindMask) { case MemberFlags.Constructor: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.Constructor; // static constructors are never called explicitly Debug.Assert(!isStatic); break; case MemberFlags.Method: targetSymbolKind = SymbolKind.Method; break; case MemberFlags.PropertyGet: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.PropertyGet; break; case MemberFlags.Field: targetSymbolKind = SymbolKind.Field; break; case MemberFlags.Property: targetSymbolKind = SymbolKind.Property; break; default: throw ExceptionUtilities.UnexpectedValue(descriptor.Flags); } foreach (var member in members) { if (!member.Name.Equals(descriptor.Name)) { continue; } if (member.Kind != targetSymbolKind || member.IsStatic != isStatic || !(member.DeclaredAccessibility == Accessibility.Public || (accessWithinOpt is object && Symbol.IsSymbolAccessible(member, accessWithinOpt)))) { continue; } switch (targetSymbolKind) { case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; MethodKind methodKind = method.MethodKind; // Treat user-defined conversions and operators as ordinary methods for the purpose // of matching them here. if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator) { methodKind = MethodKind.Ordinary; } if (method.Arity != descriptor.Arity || methodKind != targetMethodKind || ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract)) { continue; } if (!comparer.MatchMethodSignature(method, descriptor.Signature)) { continue; } } break; case SymbolKind.Property: { PropertySymbol property = (PropertySymbol)member; if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract)) { continue; } if (!comparer.MatchPropertySignature(property, descriptor.Signature)) { continue; } } break; case SymbolKind.Field: if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature)) { continue; } break; default: throw ExceptionUtilities.UnexpectedValue(targetSymbolKind); } // ambiguity if (result is object) { result = null; break; } result = member; } return result; } /// <summary> /// Synthesizes a custom attribute. /// Returns null if the <paramref name="constructor"/> symbol is missing, /// or any of the members in <paramref name="namedArguments" /> are missing. /// The attribute is synthesized only if present. /// </summary> /// <param name="constructor"> /// Constructor of the attribute. If it doesn't exist, the attribute is not created. /// </param> /// <param name="arguments">Arguments to the attribute constructor.</param> /// <param name="namedArguments"> /// Takes a list of pairs of well-known members and constants. The constants /// will be passed to the field/property referenced by the well-known member. /// If the well-known member does not exist in the compilation then no attribute /// will be synthesized. /// </param> /// <param name="isOptionalUse"> /// Indicates if this particular attribute application should be considered optional. /// </param> internal SynthesizedAttributeData? TrySynthesizeAttribute( WellKnownMember constructor, ImmutableArray<TypedConstant> arguments = default, ImmutableArray<KeyValuePair<WellKnownMember, TypedConstant>> namedArguments = default, bool isOptionalUse = false) { UseSiteInfo<AssemblySymbol> info; var ctorSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(this, constructor, out info, isOptional: true); if ((object)ctorSymbol == null) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(isOptionalUse || WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } if (arguments.IsDefault) { arguments = ImmutableArray<TypedConstant>.Empty; } ImmutableArray<KeyValuePair<string, TypedConstant>> namedStringArguments; if (namedArguments.IsDefault) { namedStringArguments = ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } else { var builder = new ArrayBuilder<KeyValuePair<string, TypedConstant>>(namedArguments.Length); foreach (var arg in namedArguments) { var wellKnownMember = Binder.GetWellKnownTypeMember(this, arg.Key, out info, isOptional: true); if (wellKnownMember == null || wellKnownMember is ErrorTypeSymbol) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } else { builder.Add(new KeyValuePair<string, TypedConstant>( wellKnownMember.Name, arg.Value)); } } namedStringArguments = builder.ToImmutableAndFree(); } return new SynthesizedAttributeData(ctorSymbol, arguments, namedStringArguments); } internal SynthesizedAttributeData? TrySynthesizeAttribute( SpecialMember constructor, bool isOptionalUse = false) { var ctorSymbol = (MethodSymbol)this.GetSpecialTypeMember(constructor); if ((object)ctorSymbol == null) { Debug.Assert(isOptionalUse); return null; } return new SynthesizedAttributeData( ctorSymbol, arguments: ImmutableArray<TypedConstant>.Empty, namedArguments: ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } internal SynthesizedAttributeData? SynthesizeDecimalConstantAttribute(decimal value) { bool isNegative; byte scale; uint low, mid, high; value.GetBits(out isNegative, out scale, out low, out mid, out high); var systemByte = GetSpecialType(SpecialType.System_Byte); Debug.Assert(!systemByte.HasUseSiteError); var systemUnit32 = GetSpecialType(SpecialType.System_UInt32); Debug.Assert(!systemUnit32.HasUseSiteError); return TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, ImmutableArray.Create( new TypedConstant(systemByte, TypedConstantKind.Primitive, scale), new TypedConstant(systemByte, TypedConstantKind.Primitive, (byte)(isNegative ? 128 : 0)), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, high), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, mid), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, low) )); } internal SynthesizedAttributeData? SynthesizeDebuggerBrowsableNeverAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(new TypedConstant( GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState), TypedConstantKind.Enum, DebuggerBrowsableState.Never))); } internal SynthesizedAttributeData? SynthesizeDebuggerStepThroughAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { Debug.Assert(!modifyCompilation || !_needsGeneratedAttributes_IsFrozen); if (CheckIfAttributeShouldBeEmbedded(attribute, diagnostics, location) && modifyCompilation) { SetNeedsGeneratedAttributes(attribute); } if ((attribute & (EmbeddableAttributes.NullableAttribute | EmbeddableAttributes.NullableContextAttribute)) != 0 && modifyCompilation) { SetUsesNullableAttributes(); } } internal void EnsureIsReadOnlyAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsByRefLikeAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsByRefLikeAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsUnmanagedAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableContextAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNativeIntegerAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute, diagnostics, location, modifyCompilation); } internal bool CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnosticsOpt, Location locationOpt) { switch (attribute) { case EmbeddableAttributes.IsReadOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); case EmbeddableAttributes.IsByRefLikeAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); case EmbeddableAttributes.IsUnmanagedAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); case EmbeddableAttributes.NullableAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags); case EmbeddableAttributes.NullableContextAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor); case EmbeddableAttributes.NullablePublicOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor); case EmbeddableAttributes.NativeIntegerAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags); default: throw ExceptionUtilities.UnexpectedValue(attribute); } } private bool CheckIfAttributeShouldBeEmbedded(BindingDiagnosticBag? diagnosticsOpt, Location? locationOpt, WellKnownType attributeType, WellKnownMember attributeCtor, WellKnownMember? secondAttributeCtor = null) { var userDefinedAttribute = GetWellKnownType(attributeType); if (userDefinedAttribute is MissingMetadataTypeSymbol) { if (Options.OutputKind == OutputKind.NetModule) { if (diagnosticsOpt != null) { var errorReported = Binder.ReportUseSite(userDefinedAttribute, diagnosticsOpt, locationOpt); Debug.Assert(errorReported); } } else { return true; } } else if (diagnosticsOpt != null) { // This should produce diagnostics if the member is missing or bad var member = Binder.GetWellKnownTypeMember(this, attributeCtor, diagnosticsOpt, locationOpt); if (member != null && secondAttributeCtor != null) { Binder.GetWellKnownTypeMember(this, secondAttributeCtor.Value, diagnosticsOpt, locationOpt); } } return false; } internal SynthesizedAttributeData? SynthesizeDebuggableAttribute() { TypeSymbol debuggableAttribute = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute); Debug.Assert((object)debuggableAttribute != null, "GetWellKnownType unexpectedly returned null"); if (debuggableAttribute is MissingMetadataTypeSymbol) { return null; } TypeSymbol debuggingModesType = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); RoslynDebug.Assert((object)debuggingModesType != null, "GetWellKnownType unexpectedly returned null"); if (debuggingModesType is MissingMetadataTypeSymbol) { return null; } // IgnoreSymbolStoreDebuggingMode flag is checked by the CLR, it is not referred to by the debugger. // It tells the JIT that it doesn't need to load the PDB at the time it generates jitted code. // The PDB would still be used by a debugger, or even by the runtime for putting source line information // on exception stack traces. We always set this flag to avoid overhead of JIT loading the PDB. // The theoretical scenario for not setting it would be a language compiler that wants their sequence points // at specific places, but those places don't match what CLR's heuristics calculate when scanning the IL. var ignoreSymbolStoreDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints); if (ignoreSymbolStoreDebuggingMode is null || !ignoreSymbolStoreDebuggingMode.HasConstantValue) { return null; } int constantVal = ignoreSymbolStoreDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; // Since .NET 2.0 the combinations of None, Default and DisableOptimizations have the following effect: // // None JIT optimizations enabled // Default JIT optimizations enabled // DisableOptimizations JIT optimizations enabled // Default | DisableOptimizations JIT optimizations disabled if (_options.OptimizationLevel == OptimizationLevel.Debug) { var defaultDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__Default); if (defaultDebuggingMode is null || !defaultDebuggingMode.HasConstantValue) { return null; } var disableOptimizationsDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations); if (disableOptimizationsDebuggingMode is null || !disableOptimizationsDebuggingMode.HasConstantValue) { return null; } constantVal |= defaultDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; constantVal |= disableOptimizationsDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } if (_options.EnableEditAndContinue) { var enableEncDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue); if (enableEncDebuggingMode is null || !enableEncDebuggingMode.HasConstantValue) { return null; } constantVal |= enableEncDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } var typedConstantDebugMode = new TypedConstant(debuggingModesType, TypedConstantKind.Enum, constantVal); return TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, ImmutableArray.Create(typedConstantDebugMode)); } /// <summary> /// Given a type <paramref name="type"/>, which is either dynamic type OR is a constructed type with dynamic type present in it's type argument tree, /// returns a synthesized DynamicAttribute with encoded dynamic transforms array. /// </summary> /// <remarks>This method is port of AttrBind::CompileDynamicAttr from the native C# compiler.</remarks> internal SynthesizedAttributeData? SynthesizeDynamicAttribute(TypeSymbol type, int customModifiersCount, RefKind refKindOpt = RefKind.None) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsDynamic()); if (type.IsDynamic() && refKindOpt == RefKind.None && customModifiersCount == 0) { return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor); } else { NamedTypeSymbol booleanType = GetSpecialType(SpecialType.System_Boolean); RoslynDebug.Assert((object)booleanType != null); var transformFlags = DynamicTransformsEncoder.Encode(type, refKindOpt, customModifiersCount, booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, arguments); } } internal SynthesizedAttributeData? SynthesizeTupleNamesAttribute(TypeSymbol type) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsTuple()); var stringType = GetSpecialType(SpecialType.System_String); RoslynDebug.Assert((object)stringType != null); var names = TupleNamesEncoder.Encode(type, stringType); Debug.Assert(!names.IsDefault, "should not need the attribute when no tuple names"); var stringArray = ArrayTypeSymbol.CreateSZArray(stringType.ContainingAssembly, TypeWithAnnotations.Create(stringType)); var args = ImmutableArray.Create(new TypedConstant(stringArray, names)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args); } internal SynthesizedAttributeData? SynthesizeAttributeUsageAttribute(AttributeTargets targets, bool allowMultiple, bool inherited) { var attributeTargetsType = GetWellKnownType(WellKnownType.System_AttributeTargets); var boolType = GetSpecialType(SpecialType.System_Boolean); var arguments = ImmutableArray.Create( new TypedConstant(attributeTargetsType, TypedConstantKind.Enum, targets)); var namedArguments = ImmutableArray.Create( new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, new TypedConstant(boolType, TypedConstantKind.Primitive, allowMultiple)), new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__Inherited, new TypedConstant(boolType, TypedConstantKind.Primitive, inherited))); return TrySynthesizeAttribute(WellKnownMember.System_AttributeUsageAttribute__ctor, arguments, namedArguments); } internal static class TupleNamesEncoder { public static ImmutableArray<string?> Encode(TypeSymbol type) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } return namesBuilder.ToImmutableAndFree(); } public static ImmutableArray<TypedConstant> Encode(TypeSymbol type, TypeSymbol stringType) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } var names = namesBuilder.SelectAsArray((name, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, name), stringType); namesBuilder.Free(); return names; } internal static bool TryGetNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { type.VisitType((t, builder, _ignore) => AddNames(t, builder), namesBuilder); return namesBuilder.Any(name => name != null); } private static bool AddNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { if (type.IsTupleType) { if (type.TupleElementNames.IsDefaultOrEmpty) { // If none of the tuple elements have names, put // null placeholders in. // TODO(https://github.com/dotnet/roslyn/issues/12347): // A possible optimization could be to emit an empty attribute // if all the names are missing, but that has to be true // recursively. namesBuilder.AddMany(null, type.TupleElementTypesWithAnnotations.Length); } else { namesBuilder.AddRange(type.TupleElementNames); } } // Always recur into nested types return false; } } /// <summary> /// Used to generate the dynamic attributes for the required typesymbol. /// </summary> internal static class DynamicTransformsEncoder { internal static ImmutableArray<TypedConstant> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount, TypeSymbol booleanType) { var flagsBuilder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, flagsBuilder, addCustomModifierFlags: true); Debug.Assert(flagsBuilder.Any()); Debug.Assert(flagsBuilder.Contains(true)); var result = flagsBuilder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); flagsBuilder.Free(); return result; } internal static ImmutableArray<bool> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, builder, addCustomModifierFlags: true); return builder.ToImmutableAndFree(); } internal static ImmutableArray<bool> EncodeWithoutCustomModifierFlags(TypeSymbol type, RefKind refKind) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, -1, refKind, builder, addCustomModifierFlags: false); return builder.ToImmutableAndFree(); } internal static void Encode(TypeSymbol type, int customModifiersCount, RefKind refKind, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Debug.Assert(!transformFlagsBuilder.Any()); if (refKind != RefKind.None) { // Native compiler encodes an extra transform flag, always false, for ref/out parameters. transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { // Native compiler encodes an extra transform flag, always false, for each custom modifier. HandleCustomModifiers(customModifiersCount, transformFlagsBuilder); type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: true), transformFlagsBuilder); } else { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: false), transformFlagsBuilder); } } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> transformFlagsBuilder, bool isNestedNamedType, bool addCustomModifierFlags) { // Encode transforms flag for this type and its custom modifiers (if any). switch (type.TypeKind) { case TypeKind.Dynamic: transformFlagsBuilder.Add(true); break; case TypeKind.Array: if (addCustomModifierFlags) { HandleCustomModifiers(((ArrayTypeSymbol)type).ElementTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.Pointer: if (addCustomModifierFlags) { HandleCustomModifiers(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.FunctionPointer: Debug.Assert(!isNestedNamedType); handleFunctionPointerType((FunctionPointerTypeSymbol)type, transformFlagsBuilder, addCustomModifierFlags); // Function pointer types have nested custom modifiers and refkinds in line with types, and visit all their nested types // as part of this call. // We need a different way to indicate that we should not recurse for this type, but should continue walking for other // types. https://github.com/dotnet/roslyn/issues/44160 return true; default: // Encode transforms flag for this type. // For nested named types, a single flag (false) is encoded for the entire type name, followed by flags for all of the type arguments. // For example, for type "A<T>.B<dynamic>", encoded transform flags are: // { // false, // Type "A.B" // false, // Type parameter "T" // true, // Type parameter "dynamic" // } if (!isNestedNamedType) { transformFlagsBuilder.Add(false); } break; } // Continue walking types return false; static void handleFunctionPointerType(FunctionPointerTypeSymbol funcPtr, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Func<TypeSymbol, (ArrayBuilder<bool>, bool), bool, bool> visitor = (TypeSymbol type, (ArrayBuilder<bool> builder, bool addCustomModifierFlags) param, bool isNestedNamedType) => AddFlags(type, param.builder, isNestedNamedType, param.addCustomModifierFlags); // The function pointer type itself gets a false transformFlagsBuilder.Add(false); var sig = funcPtr.Signature; handle(sig.RefKind, sig.RefCustomModifiers, sig.ReturnTypeWithAnnotations); foreach (var param in sig.Parameters) { handle(param.RefKind, param.RefCustomModifiers, param.TypeWithAnnotations); } void handle(RefKind refKind, ImmutableArray<CustomModifier> customModifiers, TypeWithAnnotations twa) { if (addCustomModifierFlags) { HandleCustomModifiers(customModifiers.Length, transformFlagsBuilder); } if (refKind != RefKind.None) { transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { HandleCustomModifiers(twa.CustomModifiers.Length, transformFlagsBuilder); } twa.Type.VisitType(visitor, (transformFlagsBuilder, addCustomModifierFlags)); } } } private static void HandleCustomModifiers(int customModifiersCount, ArrayBuilder<bool> transformFlagsBuilder) { // Native compiler encodes an extra transforms flag, always false, for each custom modifier. transformFlagsBuilder.AddMany(false, customModifiersCount); } } internal static class NativeIntegerTransformsEncoder { internal static void Encode(ArrayBuilder<bool> builder, TypeSymbol type) { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder), builder); } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> builder) { switch (type.SpecialType) { case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: builder.Add(type.IsNativeIntegerType); break; } // Continue walking types return false; } } internal class SpecialMembersSignatureComparer : SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> { // Fields public static readonly SpecialMembersSignatureComparer Instance = new SpecialMembersSignatureComparer(); // Methods protected SpecialMembersSignatureComparer() { } protected override TypeSymbol? GetMDArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (array.IsSZArray) { return null; } return array.ElementType; } protected override TypeSymbol GetFieldType(FieldSymbol field) { return field.Type; } protected override TypeSymbol GetPropertyType(PropertySymbol property) { return property.Type; } protected override TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if (named.Arity <= argumentIndex) { return null; } if ((object)named.ContainingType != null) { return null; } return named.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[argumentIndex].Type; } protected override TypeSymbol? GetGenericTypeDefinition(TypeSymbol type) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if ((object)named.ContainingType != null) { return null; } if (named.Arity == 0) { return null; } return (NamedTypeSymbol)named.OriginalDefinition; } protected override ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method) { return method.Parameters; } protected override ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property) { return property.Parameters; } protected override TypeSymbol GetParamType(ParameterSymbol parameter) { return parameter.Type; } protected override TypeSymbol? GetPointedToType(TypeSymbol type) { return type.Kind == SymbolKind.PointerType ? ((PointerTypeSymbol)type).PointedAtType : null; } protected override TypeSymbol GetReturnType(MethodSymbol method) { return method.ReturnType; } protected override TypeSymbol? GetSZArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (!array.IsSZArray) { return null; } return array.ElementType; } protected override bool IsByRefParam(ParameterSymbol parameter) { return parameter.RefKind != RefKind.None; } protected override bool IsByRefMethod(MethodSymbol method) { return method.RefKind != RefKind.None; } protected override bool IsByRefProperty(PropertySymbol property) { return property.RefKind != RefKind.None; } protected override bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.Method) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool IsGenericTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.NamedType) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool MatchArrayRank(TypeSymbol type, int countOfDimensions) { if (type.Kind != SymbolKind.ArrayType) { return false; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; return (array.Rank == countOfDimensions); } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { if ((int)type.OriginalDefinition.SpecialType == typeId) { if (type.IsDefinition) { return true; } return type.Equals(type.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return false; } } internal sealed class WellKnownMembersSignatureComparer : SpecialMembersSignatureComparer { private readonly CSharpCompilation _compilation; public WellKnownMembersSignatureComparer(CSharpCompilation compilation) { _compilation = compilation; } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { WellKnownType wellKnownId = (WellKnownType)typeId; if (wellKnownId.IsWellKnownType()) { return type.Equals(_compilation.GetWellKnownType(wellKnownId), TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return base.MatchTypeToTypeId(type, typeId); } } } }
// 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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.RuntimeMembers; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public partial class CSharpCompilation { internal readonly WellKnownMembersSignatureComparer WellKnownMemberSignatureComparer; /// <summary> /// An array of cached well known types available for use in this Compilation. /// Lazily filled by GetWellKnownType method. /// </summary> private NamedTypeSymbol?[]? _lazyWellKnownTypes; /// <summary> /// Lazy cache of well known members. /// Not yet known value is represented by ErrorTypeSymbol.UnknownResultType /// </summary> private Symbol?[]? _lazyWellKnownTypeMembers; private bool _usesNullableAttributes; private int _needsGeneratedAttributes; private bool _needsGeneratedAttributes_IsFrozen; /// <summary> /// Returns a value indicating which embedded attributes should be generated during emit phase. /// The value is set during binding the symbols that need those attributes, and is frozen on first trial to get it. /// Freezing is needed to make sure that nothing tries to modify the value after the value is read. /// </summary> internal EmbeddableAttributes GetNeedsGeneratedAttributes() { _needsGeneratedAttributes_IsFrozen = true; return (EmbeddableAttributes)_needsGeneratedAttributes; } private void SetNeedsGeneratedAttributes(EmbeddableAttributes attributes) { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); ThreadSafeFlagOperations.Set(ref _needsGeneratedAttributes, (int)attributes); } internal bool GetUsesNullableAttributes() { _needsGeneratedAttributes_IsFrozen = true; return _usesNullableAttributes; } private void SetUsesNullableAttributes() { Debug.Assert(!_needsGeneratedAttributes_IsFrozen); _usesNullableAttributes = true; } /// <summary> /// Lookup member declaration in well known type used by this Compilation. /// </summary> /// <remarks> /// If a well-known member of a generic type instantiation is needed use this method to get the corresponding generic definition and /// <see cref="MethodSymbol.AsMember"/> to construct an instantiation. /// </remarks> internal Symbol? GetWellKnownTypeMember(WellKnownMember member) { Debug.Assert(member >= 0 && member < WellKnownMember.Count); // Test hook: if a member is marked missing, then return null. if (IsMemberMissing(member)) return null; if (_lazyWellKnownTypeMembers == null || ReferenceEquals(_lazyWellKnownTypeMembers[(int)member], ErrorTypeSymbol.UnknownResultType)) { if (_lazyWellKnownTypeMembers == null) { var wellKnownTypeMembers = new Symbol[(int)WellKnownMember.Count]; for (int i = 0; i < wellKnownTypeMembers.Length; i++) { wellKnownTypeMembers[i] = ErrorTypeSymbol.UnknownResultType; } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers, wellKnownTypeMembers, null); } MemberDescriptor descriptor = WellKnownMembers.GetDescriptor(member); NamedTypeSymbol type = descriptor.DeclaringTypeId <= (int)SpecialType.Count ? this.GetSpecialType((SpecialType)descriptor.DeclaringTypeId) : this.GetWellKnownType((WellKnownType)descriptor.DeclaringTypeId); Symbol? result = null; if (!type.IsErrorType()) { result = GetRuntimeMember(type, descriptor, WellKnownMemberSignatureComparer, accessWithinOpt: this.Assembly); } Interlocked.CompareExchange(ref _lazyWellKnownTypeMembers[(int)member], result, ErrorTypeSymbol.UnknownResultType); } return _lazyWellKnownTypeMembers[(int)member]; } /// <summary> /// This method handles duplicate types in a few different ways: /// - for types before C# 7, the first candidate is returned with a warning /// - for types after C# 7, the type is considered missing /// - in both cases, when BinderFlags.IgnoreCorLibraryDuplicatedTypes is set, type from corlib will not count as a duplicate /// </summary> internal NamedTypeSymbol GetWellKnownType(WellKnownType type) { Debug.Assert(type.IsValid()); bool ignoreCorLibraryDuplicatedTypes = this.Options.TopLevelBinderFlags.Includes(BinderFlags.IgnoreCorLibraryDuplicatedTypes); int index = (int)type - (int)WellKnownType.First; if (_lazyWellKnownTypes == null || _lazyWellKnownTypes[index] is null) { if (_lazyWellKnownTypes == null) { Interlocked.CompareExchange(ref _lazyWellKnownTypes, new NamedTypeSymbol[(int)WellKnownTypes.Count], null); } string mdName = type.GetMetadataName(); var warnings = DiagnosticBag.GetInstance(); NamedTypeSymbol? result; (AssemblySymbol, AssemblySymbol) conflicts = default; if (IsTypeMissing(type)) { result = null; } else { // well-known types introduced before CSharp7 allow lookup ambiguity and report a warning DiagnosticBag? legacyWarnings = (type <= WellKnownType.CSharp7Sentinel) ? warnings : null; result = this.Assembly.GetTypeByMetadataName( mdName, includeReferences: true, useCLSCompliantNameArityEncoding: true, isWellKnownType: true, conflicts: out conflicts, warnings: legacyWarnings, ignoreCorLibraryDuplicatedTypes: ignoreCorLibraryDuplicatedTypes); } if (result is null) { // TODO: should GetTypeByMetadataName rather return a missing symbol? MetadataTypeName emittedName = MetadataTypeName.FromFullName(mdName, useCLSCompliantNameArityEncoding: true); if (type.IsValueTupleType()) { CSDiagnosticInfo errorInfo; if (conflicts.Item1 is null) { Debug.Assert(conflicts.Item2 is null); errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, emittedName.FullName); } else { errorInfo = new CSDiagnosticInfo(ErrorCode.ERR_PredefinedValueTupleTypeAmbiguous3, emittedName.FullName, conflicts.Item1, conflicts.Item2); } result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type, errorInfo); } else { result = new MissingMetadataTypeSymbol.TopLevel(this.Assembly.Modules[0], ref emittedName, type); } } if (Interlocked.CompareExchange(ref _lazyWellKnownTypes[index], result, null) is object) { Debug.Assert( TypeSymbol.Equals(result, _lazyWellKnownTypes[index], TypeCompareKind.ConsiderEverything2) || (_lazyWellKnownTypes[index]!.IsErrorType() && result.IsErrorType()) ); } else { AdditionalCodegenWarnings.AddRange(warnings); } warnings.Free(); } return _lazyWellKnownTypes[index]!; } internal bool IsAttributeType(TypeSymbol type) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Attribute, ref discardedUseSiteInfo); } internal override bool IsAttributeType(ITypeSymbol type) { return IsAttributeType(type.EnsureCSharpSymbolOrNull(nameof(type))); } internal bool IsExceptionType(TypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return IsEqualOrDerivedFromWellKnownClass(type, WellKnownType.System_Exception, ref useSiteInfo); } internal bool IsReadOnlySpanType(TypeSymbol type) { return TypeSymbol.Equals(type.OriginalDefinition, GetWellKnownType(WellKnownType.System_ReadOnlySpan_T), TypeCompareKind.ConsiderEverything2); } internal bool IsEqualOrDerivedFromWellKnownClass(TypeSymbol type, WellKnownType wellKnownType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(wellKnownType == WellKnownType.System_Attribute || wellKnownType == WellKnownType.System_Exception); if (type.Kind != SymbolKind.NamedType || type.TypeKind != TypeKind.Class) { return false; } var wkType = GetWellKnownType(wellKnownType); return type.Equals(wkType, TypeCompareKind.ConsiderEverything) || type.IsDerivedFrom(wkType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref useSiteInfo); } internal override bool IsSystemTypeReference(ITypeSymbolInternal type) { return TypeSymbol.Equals((TypeSymbol)type, GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything2); } internal override ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member) { return GetWellKnownTypeMember(member); } internal override ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType) { return GetWellKnownType(wellknownType); } internal static Symbol? GetRuntimeMember(NamedTypeSymbol declaringType, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { var members = declaringType.GetMembers(descriptor.Name); return GetRuntimeMember(members, descriptor, comparer, accessWithinOpt); } internal static Symbol? GetRuntimeMember(ImmutableArray<Symbol> members, in MemberDescriptor descriptor, SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> comparer, AssemblySymbol? accessWithinOpt) { SymbolKind targetSymbolKind; MethodKind targetMethodKind = MethodKind.Ordinary; bool isStatic = (descriptor.Flags & MemberFlags.Static) != 0; Symbol? result = null; switch (descriptor.Flags & MemberFlags.KindMask) { case MemberFlags.Constructor: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.Constructor; // static constructors are never called explicitly Debug.Assert(!isStatic); break; case MemberFlags.Method: targetSymbolKind = SymbolKind.Method; break; case MemberFlags.PropertyGet: targetSymbolKind = SymbolKind.Method; targetMethodKind = MethodKind.PropertyGet; break; case MemberFlags.Field: targetSymbolKind = SymbolKind.Field; break; case MemberFlags.Property: targetSymbolKind = SymbolKind.Property; break; default: throw ExceptionUtilities.UnexpectedValue(descriptor.Flags); } foreach (var member in members) { if (!member.Name.Equals(descriptor.Name)) { continue; } if (member.Kind != targetSymbolKind || member.IsStatic != isStatic || !(member.DeclaredAccessibility == Accessibility.Public || (accessWithinOpt is object && Symbol.IsSymbolAccessible(member, accessWithinOpt)))) { continue; } switch (targetSymbolKind) { case SymbolKind.Method: { MethodSymbol method = (MethodSymbol)member; MethodKind methodKind = method.MethodKind; // Treat user-defined conversions and operators as ordinary methods for the purpose // of matching them here. if (methodKind == MethodKind.Conversion || methodKind == MethodKind.UserDefinedOperator) { methodKind = MethodKind.Ordinary; } if (method.Arity != descriptor.Arity || methodKind != targetMethodKind || ((descriptor.Flags & MemberFlags.Virtual) != 0) != (method.IsVirtual || method.IsOverride || method.IsAbstract)) { continue; } if (!comparer.MatchMethodSignature(method, descriptor.Signature)) { continue; } } break; case SymbolKind.Property: { PropertySymbol property = (PropertySymbol)member; if (((descriptor.Flags & MemberFlags.Virtual) != 0) != (property.IsVirtual || property.IsOverride || property.IsAbstract)) { continue; } if (!comparer.MatchPropertySignature(property, descriptor.Signature)) { continue; } } break; case SymbolKind.Field: if (!comparer.MatchFieldSignature((FieldSymbol)member, descriptor.Signature)) { continue; } break; default: throw ExceptionUtilities.UnexpectedValue(targetSymbolKind); } // ambiguity if (result is object) { result = null; break; } result = member; } return result; } /// <summary> /// Synthesizes a custom attribute. /// Returns null if the <paramref name="constructor"/> symbol is missing, /// or any of the members in <paramref name="namedArguments" /> are missing. /// The attribute is synthesized only if present. /// </summary> /// <param name="constructor"> /// Constructor of the attribute. If it doesn't exist, the attribute is not created. /// </param> /// <param name="arguments">Arguments to the attribute constructor.</param> /// <param name="namedArguments"> /// Takes a list of pairs of well-known members and constants. The constants /// will be passed to the field/property referenced by the well-known member. /// If the well-known member does not exist in the compilation then no attribute /// will be synthesized. /// </param> /// <param name="isOptionalUse"> /// Indicates if this particular attribute application should be considered optional. /// </param> internal SynthesizedAttributeData? TrySynthesizeAttribute( WellKnownMember constructor, ImmutableArray<TypedConstant> arguments = default, ImmutableArray<KeyValuePair<WellKnownMember, TypedConstant>> namedArguments = default, bool isOptionalUse = false) { UseSiteInfo<AssemblySymbol> info; var ctorSymbol = (MethodSymbol)Binder.GetWellKnownTypeMember(this, constructor, out info, isOptional: true); if ((object)ctorSymbol == null) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(isOptionalUse || WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } if (arguments.IsDefault) { arguments = ImmutableArray<TypedConstant>.Empty; } ImmutableArray<KeyValuePair<string, TypedConstant>> namedStringArguments; if (namedArguments.IsDefault) { namedStringArguments = ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty; } else { var builder = new ArrayBuilder<KeyValuePair<string, TypedConstant>>(namedArguments.Length); foreach (var arg in namedArguments) { var wellKnownMember = Binder.GetWellKnownTypeMember(this, arg.Key, out info, isOptional: true); if (wellKnownMember == null || wellKnownMember is ErrorTypeSymbol) { // if this assert fails, UseSiteErrors for "member" have not been checked before emitting ... Debug.Assert(WellKnownMembers.IsSynthesizedAttributeOptional(constructor)); return null; } else { builder.Add(new KeyValuePair<string, TypedConstant>( wellKnownMember.Name, arg.Value)); } } namedStringArguments = builder.ToImmutableAndFree(); } return new SynthesizedAttributeData(ctorSymbol, arguments, namedStringArguments); } internal SynthesizedAttributeData? TrySynthesizeAttribute( SpecialMember constructor, bool isOptionalUse = false) { var ctorSymbol = (MethodSymbol)this.GetSpecialTypeMember(constructor); if ((object)ctorSymbol == null) { Debug.Assert(isOptionalUse); return null; } return new SynthesizedAttributeData( ctorSymbol, arguments: ImmutableArray<TypedConstant>.Empty, namedArguments: ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty); } internal SynthesizedAttributeData? SynthesizeDecimalConstantAttribute(decimal value) { bool isNegative; byte scale; uint low, mid, high; value.GetBits(out isNegative, out scale, out low, out mid, out high); var systemByte = GetSpecialType(SpecialType.System_Byte); Debug.Assert(!systemByte.HasUseSiteError); var systemUnit32 = GetSpecialType(SpecialType.System_UInt32); Debug.Assert(!systemUnit32.HasUseSiteError); return TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, ImmutableArray.Create( new TypedConstant(systemByte, TypedConstantKind.Primitive, scale), new TypedConstant(systemByte, TypedConstantKind.Primitive, (byte)(isNegative ? 128 : 0)), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, high), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, mid), new TypedConstant(systemUnit32, TypedConstantKind.Primitive, low) )); } internal SynthesizedAttributeData? SynthesizeDebuggerBrowsableNeverAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerBrowsableAttribute__ctor, ImmutableArray.Create(new TypedConstant( GetWellKnownType(WellKnownType.System_Diagnostics_DebuggerBrowsableState), TypedConstantKind.Enum, DebuggerBrowsableState.Never))); } internal SynthesizedAttributeData? SynthesizeDebuggerStepThroughAttribute() { if (Options.OptimizationLevel != OptimizationLevel.Debug) { return null; } return TrySynthesizeAttribute(WellKnownMember.System_Diagnostics_DebuggerStepThroughAttribute__ctor); } private void EnsureEmbeddableAttributeExists(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { Debug.Assert(!modifyCompilation || !_needsGeneratedAttributes_IsFrozen); if (CheckIfAttributeShouldBeEmbedded(attribute, diagnostics, location) && modifyCompilation) { SetNeedsGeneratedAttributes(attribute); } if ((attribute & (EmbeddableAttributes.NullableAttribute | EmbeddableAttributes.NullableContextAttribute)) != 0 && modifyCompilation) { SetUsesNullableAttributes(); } } internal void EnsureIsReadOnlyAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsReadOnlyAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsByRefLikeAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsByRefLikeAttribute, diagnostics, location, modifyCompilation); } internal void EnsureIsUnmanagedAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.IsUnmanagedAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNullableContextAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NullableContextAttribute, diagnostics, location, modifyCompilation); } internal void EnsureNativeIntegerAttributeExists(BindingDiagnosticBag? diagnostics, Location location, bool modifyCompilation) { EnsureEmbeddableAttributeExists(EmbeddableAttributes.NativeIntegerAttribute, diagnostics, location, modifyCompilation); } internal bool CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes attribute, BindingDiagnosticBag? diagnosticsOpt, Location locationOpt) { switch (attribute) { case EmbeddableAttributes.IsReadOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_IsReadOnlyAttribute__ctor); case EmbeddableAttributes.IsByRefLikeAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsByRefLikeAttribute, WellKnownMember.System_Runtime_CompilerServices_IsByRefLikeAttribute__ctor); case EmbeddableAttributes.IsUnmanagedAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_IsUnmanagedAttribute, WellKnownMember.System_Runtime_CompilerServices_IsUnmanagedAttribute__ctor); case EmbeddableAttributes.NullableAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorByte, WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags); case EmbeddableAttributes.NullableContextAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullableContextAttribute, WellKnownMember.System_Runtime_CompilerServices_NullableContextAttribute__ctor); case EmbeddableAttributes.NullablePublicOnlyAttribute: return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NullablePublicOnlyAttribute, WellKnownMember.System_Runtime_CompilerServices_NullablePublicOnlyAttribute__ctor); case EmbeddableAttributes.NativeIntegerAttribute: // If the type exists, we'll check both constructors, regardless of which one(s) we'll eventually need. return CheckIfAttributeShouldBeEmbedded( diagnosticsOpt, locationOpt, WellKnownType.System_Runtime_CompilerServices_NativeIntegerAttribute, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctor, WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags); default: throw ExceptionUtilities.UnexpectedValue(attribute); } } private bool CheckIfAttributeShouldBeEmbedded(BindingDiagnosticBag? diagnosticsOpt, Location? locationOpt, WellKnownType attributeType, WellKnownMember attributeCtor, WellKnownMember? secondAttributeCtor = null) { var userDefinedAttribute = GetWellKnownType(attributeType); if (userDefinedAttribute is MissingMetadataTypeSymbol) { if (Options.OutputKind == OutputKind.NetModule) { if (diagnosticsOpt != null) { var errorReported = Binder.ReportUseSite(userDefinedAttribute, diagnosticsOpt, locationOpt); Debug.Assert(errorReported); } } else { return true; } } else if (diagnosticsOpt != null) { // This should produce diagnostics if the member is missing or bad var member = Binder.GetWellKnownTypeMember(this, attributeCtor, diagnosticsOpt, locationOpt); if (member != null && secondAttributeCtor != null) { Binder.GetWellKnownTypeMember(this, secondAttributeCtor.Value, diagnosticsOpt, locationOpt); } } return false; } internal SynthesizedAttributeData? SynthesizeDebuggableAttribute() { TypeSymbol debuggableAttribute = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute); Debug.Assert((object)debuggableAttribute != null, "GetWellKnownType unexpectedly returned null"); if (debuggableAttribute is MissingMetadataTypeSymbol) { return null; } TypeSymbol debuggingModesType = GetWellKnownType(WellKnownType.System_Diagnostics_DebuggableAttribute__DebuggingModes); RoslynDebug.Assert((object)debuggingModesType != null, "GetWellKnownType unexpectedly returned null"); if (debuggingModesType is MissingMetadataTypeSymbol) { return null; } // IgnoreSymbolStoreDebuggingMode flag is checked by the CLR, it is not referred to by the debugger. // It tells the JIT that it doesn't need to load the PDB at the time it generates jitted code. // The PDB would still be used by a debugger, or even by the runtime for putting source line information // on exception stack traces. We always set this flag to avoid overhead of JIT loading the PDB. // The theoretical scenario for not setting it would be a language compiler that wants their sequence points // at specific places, but those places don't match what CLR's heuristics calculate when scanning the IL. var ignoreSymbolStoreDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__IgnoreSymbolStoreSequencePoints); if (ignoreSymbolStoreDebuggingMode is null || !ignoreSymbolStoreDebuggingMode.HasConstantValue) { return null; } int constantVal = ignoreSymbolStoreDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; // Since .NET 2.0 the combinations of None, Default and DisableOptimizations have the following effect: // // None JIT optimizations enabled // Default JIT optimizations enabled // DisableOptimizations JIT optimizations enabled // Default | DisableOptimizations JIT optimizations disabled if (_options.OptimizationLevel == OptimizationLevel.Debug) { var defaultDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__Default); if (defaultDebuggingMode is null || !defaultDebuggingMode.HasConstantValue) { return null; } var disableOptimizationsDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__DisableOptimizations); if (disableOptimizationsDebuggingMode is null || !disableOptimizationsDebuggingMode.HasConstantValue) { return null; } constantVal |= defaultDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; constantVal |= disableOptimizationsDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } if (_options.EnableEditAndContinue) { var enableEncDebuggingMode = (FieldSymbol?)GetWellKnownTypeMember(WellKnownMember.System_Diagnostics_DebuggableAttribute_DebuggingModes__EnableEditAndContinue); if (enableEncDebuggingMode is null || !enableEncDebuggingMode.HasConstantValue) { return null; } constantVal |= enableEncDebuggingMode.GetConstantValue(ConstantFieldsInProgress.Empty, earlyDecodingWellKnownAttributes: false).Int32Value; } var typedConstantDebugMode = new TypedConstant(debuggingModesType, TypedConstantKind.Enum, constantVal); return TrySynthesizeAttribute( WellKnownMember.System_Diagnostics_DebuggableAttribute__ctorDebuggingModes, ImmutableArray.Create(typedConstantDebugMode)); } /// <summary> /// Given a type <paramref name="type"/>, which is either dynamic type OR is a constructed type with dynamic type present in it's type argument tree, /// returns a synthesized DynamicAttribute with encoded dynamic transforms array. /// </summary> /// <remarks>This method is port of AttrBind::CompileDynamicAttr from the native C# compiler.</remarks> internal SynthesizedAttributeData? SynthesizeDynamicAttribute(TypeSymbol type, int customModifiersCount, RefKind refKindOpt = RefKind.None) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsDynamic()); if (type.IsDynamic() && refKindOpt == RefKind.None && customModifiersCount == 0) { return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor); } else { NamedTypeSymbol booleanType = GetSpecialType(SpecialType.System_Boolean); RoslynDebug.Assert((object)booleanType != null); var transformFlags = DynamicTransformsEncoder.Encode(type, refKindOpt, customModifiersCount, booleanType); var boolArray = ArrayTypeSymbol.CreateSZArray(booleanType.ContainingAssembly, TypeWithAnnotations.Create(booleanType)); var arguments = ImmutableArray.Create(new TypedConstant(boolArray, transformFlags)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, arguments); } } internal SynthesizedAttributeData? SynthesizeTupleNamesAttribute(TypeSymbol type) { RoslynDebug.Assert((object)type != null); Debug.Assert(type.ContainsTuple()); var stringType = GetSpecialType(SpecialType.System_String); RoslynDebug.Assert((object)stringType != null); var names = TupleNamesEncoder.Encode(type, stringType); Debug.Assert(!names.IsDefault, "should not need the attribute when no tuple names"); var stringArray = ArrayTypeSymbol.CreateSZArray(stringType.ContainingAssembly, TypeWithAnnotations.Create(stringType)); var args = ImmutableArray.Create(new TypedConstant(stringArray, names)); return TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, args); } internal SynthesizedAttributeData? SynthesizeAttributeUsageAttribute(AttributeTargets targets, bool allowMultiple, bool inherited) { var attributeTargetsType = GetWellKnownType(WellKnownType.System_AttributeTargets); var boolType = GetSpecialType(SpecialType.System_Boolean); var arguments = ImmutableArray.Create( new TypedConstant(attributeTargetsType, TypedConstantKind.Enum, targets)); var namedArguments = ImmutableArray.Create( new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, new TypedConstant(boolType, TypedConstantKind.Primitive, allowMultiple)), new KeyValuePair<WellKnownMember, TypedConstant>(WellKnownMember.System_AttributeUsageAttribute__Inherited, new TypedConstant(boolType, TypedConstantKind.Primitive, inherited))); return TrySynthesizeAttribute(WellKnownMember.System_AttributeUsageAttribute__ctor, arguments, namedArguments); } internal static class TupleNamesEncoder { public static ImmutableArray<string?> Encode(TypeSymbol type) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } return namesBuilder.ToImmutableAndFree(); } public static ImmutableArray<TypedConstant> Encode(TypeSymbol type, TypeSymbol stringType) { var namesBuilder = ArrayBuilder<string?>.GetInstance(); if (!TryGetNames(type, namesBuilder)) { namesBuilder.Free(); return default; } var names = namesBuilder.SelectAsArray((name, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, name), stringType); namesBuilder.Free(); return names; } internal static bool TryGetNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { type.VisitType((t, builder, _ignore) => AddNames(t, builder), namesBuilder); return namesBuilder.Any(name => name != null); } private static bool AddNames(TypeSymbol type, ArrayBuilder<string?> namesBuilder) { if (type.IsTupleType) { if (type.TupleElementNames.IsDefaultOrEmpty) { // If none of the tuple elements have names, put // null placeholders in. // TODO(https://github.com/dotnet/roslyn/issues/12347): // A possible optimization could be to emit an empty attribute // if all the names are missing, but that has to be true // recursively. namesBuilder.AddMany(null, type.TupleElementTypesWithAnnotations.Length); } else { namesBuilder.AddRange(type.TupleElementNames); } } // Always recur into nested types return false; } } /// <summary> /// Used to generate the dynamic attributes for the required typesymbol. /// </summary> internal static class DynamicTransformsEncoder { internal static ImmutableArray<TypedConstant> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount, TypeSymbol booleanType) { var flagsBuilder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, flagsBuilder, addCustomModifierFlags: true); Debug.Assert(flagsBuilder.Any()); Debug.Assert(flagsBuilder.Contains(true)); var result = flagsBuilder.SelectAsArray((flag, constantType) => new TypedConstant(constantType, TypedConstantKind.Primitive, flag), booleanType); flagsBuilder.Free(); return result; } internal static ImmutableArray<bool> Encode(TypeSymbol type, RefKind refKind, int customModifiersCount) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, customModifiersCount, refKind, builder, addCustomModifierFlags: true); return builder.ToImmutableAndFree(); } internal static ImmutableArray<bool> EncodeWithoutCustomModifierFlags(TypeSymbol type, RefKind refKind) { var builder = ArrayBuilder<bool>.GetInstance(); Encode(type, -1, refKind, builder, addCustomModifierFlags: false); return builder.ToImmutableAndFree(); } internal static void Encode(TypeSymbol type, int customModifiersCount, RefKind refKind, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Debug.Assert(!transformFlagsBuilder.Any()); if (refKind != RefKind.None) { // Native compiler encodes an extra transform flag, always false, for ref/out parameters. transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { // Native compiler encodes an extra transform flag, always false, for each custom modifier. HandleCustomModifiers(customModifiersCount, transformFlagsBuilder); type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: true), transformFlagsBuilder); } else { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder, isNested, addCustomModifierFlags: false), transformFlagsBuilder); } } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> transformFlagsBuilder, bool isNestedNamedType, bool addCustomModifierFlags) { // Encode transforms flag for this type and its custom modifiers (if any). switch (type.TypeKind) { case TypeKind.Dynamic: transformFlagsBuilder.Add(true); break; case TypeKind.Array: if (addCustomModifierFlags) { HandleCustomModifiers(((ArrayTypeSymbol)type).ElementTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.Pointer: if (addCustomModifierFlags) { HandleCustomModifiers(((PointerTypeSymbol)type).PointedAtTypeWithAnnotations.CustomModifiers.Length, transformFlagsBuilder); } transformFlagsBuilder.Add(false); break; case TypeKind.FunctionPointer: Debug.Assert(!isNestedNamedType); handleFunctionPointerType((FunctionPointerTypeSymbol)type, transformFlagsBuilder, addCustomModifierFlags); // Function pointer types have nested custom modifiers and refkinds in line with types, and visit all their nested types // as part of this call. // We need a different way to indicate that we should not recurse for this type, but should continue walking for other // types. https://github.com/dotnet/roslyn/issues/44160 return true; default: // Encode transforms flag for this type. // For nested named types, a single flag (false) is encoded for the entire type name, followed by flags for all of the type arguments. // For example, for type "A<T>.B<dynamic>", encoded transform flags are: // { // false, // Type "A.B" // false, // Type parameter "T" // true, // Type parameter "dynamic" // } if (!isNestedNamedType) { transformFlagsBuilder.Add(false); } break; } // Continue walking types return false; static void handleFunctionPointerType(FunctionPointerTypeSymbol funcPtr, ArrayBuilder<bool> transformFlagsBuilder, bool addCustomModifierFlags) { Func<TypeSymbol, (ArrayBuilder<bool>, bool), bool, bool> visitor = (TypeSymbol type, (ArrayBuilder<bool> builder, bool addCustomModifierFlags) param, bool isNestedNamedType) => AddFlags(type, param.builder, isNestedNamedType, param.addCustomModifierFlags); // The function pointer type itself gets a false transformFlagsBuilder.Add(false); var sig = funcPtr.Signature; handle(sig.RefKind, sig.RefCustomModifiers, sig.ReturnTypeWithAnnotations); foreach (var param in sig.Parameters) { handle(param.RefKind, param.RefCustomModifiers, param.TypeWithAnnotations); } void handle(RefKind refKind, ImmutableArray<CustomModifier> customModifiers, TypeWithAnnotations twa) { if (addCustomModifierFlags) { HandleCustomModifiers(customModifiers.Length, transformFlagsBuilder); } if (refKind != RefKind.None) { transformFlagsBuilder.Add(false); } if (addCustomModifierFlags) { HandleCustomModifiers(twa.CustomModifiers.Length, transformFlagsBuilder); } twa.Type.VisitType(visitor, (transformFlagsBuilder, addCustomModifierFlags)); } } } private static void HandleCustomModifiers(int customModifiersCount, ArrayBuilder<bool> transformFlagsBuilder) { // Native compiler encodes an extra transforms flag, always false, for each custom modifier. transformFlagsBuilder.AddMany(false, customModifiersCount); } } internal static class NativeIntegerTransformsEncoder { internal static void Encode(ArrayBuilder<bool> builder, TypeSymbol type) { type.VisitType((typeSymbol, builder, isNested) => AddFlags(typeSymbol, builder), builder); } private static bool AddFlags(TypeSymbol type, ArrayBuilder<bool> builder) { switch (type.SpecialType) { case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: builder.Add(type.IsNativeIntegerType); break; } // Continue walking types return false; } } internal class SpecialMembersSignatureComparer : SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol> { // Fields public static readonly SpecialMembersSignatureComparer Instance = new SpecialMembersSignatureComparer(); // Methods protected SpecialMembersSignatureComparer() { } protected override TypeSymbol? GetMDArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (array.IsSZArray) { return null; } return array.ElementType; } protected override TypeSymbol GetFieldType(FieldSymbol field) { return field.Type; } protected override TypeSymbol GetPropertyType(PropertySymbol property) { return property.Type; } protected override TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if (named.Arity <= argumentIndex) { return null; } if ((object)named.ContainingType != null) { return null; } return named.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[argumentIndex].Type; } protected override TypeSymbol? GetGenericTypeDefinition(TypeSymbol type) { if (type.Kind != SymbolKind.NamedType) { return null; } NamedTypeSymbol named = (NamedTypeSymbol)type; if ((object)named.ContainingType != null) { return null; } if (named.Arity == 0) { return null; } return (NamedTypeSymbol)named.OriginalDefinition; } protected override ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method) { return method.Parameters; } protected override ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property) { return property.Parameters; } protected override TypeSymbol GetParamType(ParameterSymbol parameter) { return parameter.Type; } protected override TypeSymbol? GetPointedToType(TypeSymbol type) { return type.Kind == SymbolKind.PointerType ? ((PointerTypeSymbol)type).PointedAtType : null; } protected override TypeSymbol GetReturnType(MethodSymbol method) { return method.ReturnType; } protected override TypeSymbol? GetSZArrayElementType(TypeSymbol type) { if (type.Kind != SymbolKind.ArrayType) { return null; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; if (!array.IsSZArray) { return null; } return array.ElementType; } protected override bool IsByRefParam(ParameterSymbol parameter) { return parameter.RefKind != RefKind.None; } protected override bool IsByRefMethod(MethodSymbol method) { return method.RefKind != RefKind.None; } protected override bool IsByRefProperty(PropertySymbol property) { return property.RefKind != RefKind.None; } protected override bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.Method) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool IsGenericTypeParam(TypeSymbol type, int paramPosition) { if (type.Kind != SymbolKind.TypeParameter) { return false; } TypeParameterSymbol typeParam = (TypeParameterSymbol)type; if (typeParam.ContainingSymbol.Kind != SymbolKind.NamedType) { return false; } return (typeParam.Ordinal == paramPosition); } protected override bool MatchArrayRank(TypeSymbol type, int countOfDimensions) { if (type.Kind != SymbolKind.ArrayType) { return false; } ArrayTypeSymbol array = (ArrayTypeSymbol)type; return (array.Rank == countOfDimensions); } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { if ((int)type.OriginalDefinition.SpecialType == typeId) { if (type.IsDefinition) { return true; } return type.Equals(type.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return false; } } internal sealed class WellKnownMembersSignatureComparer : SpecialMembersSignatureComparer { private readonly CSharpCompilation _compilation; public WellKnownMembersSignatureComparer(CSharpCompilation compilation) { _compilation = compilation; } protected override bool MatchTypeToTypeId(TypeSymbol type, int typeId) { WellKnownType wellKnownId = (WellKnownType)typeId; if (wellKnownId.IsWellKnownType()) { return type.Equals(_compilation.GetWellKnownType(wellKnownId), TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } return base.MatchTypeToTypeId(type, typeId); } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Scripting/Core/Hosting/AssemblyLoader/InteractiveAssemblyLoaderException.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.Scripting.Hosting { internal sealed class InteractiveAssemblyLoaderException : NotSupportedException { internal InteractiveAssemblyLoaderException(string message) : base(message) { } } }
// 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.Scripting.Hosting { internal sealed class InteractiveAssemblyLoaderException : NotSupportedException { internal InteractiveAssemblyLoaderException(string message) : base(message) { } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ModifierKeywordRecommenderTests.InsideModuleDeclaration.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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideModuleDeclaration Inherits RecommenderTests <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DefaultNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Default") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Narrowing") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overloads") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overrides") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shadows") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shared") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Widening") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Partial") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterPrivateTest() VerifyRecommendationsContain(<ModuleDeclaration>Private |</ModuleDeclaration>, "Partial") 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations.ModifierKeywordRecommenderTests Public Class InsideModuleDeclaration Inherits RecommenderTests <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub DefaultNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Default") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NarrowingNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Narrowing") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverloadsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overloads") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub OverridesNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Overrides") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ShadowsNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shadows") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SharedNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Shared") End Sub <Fact> <WorkItem(544630, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544630")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WideningNotInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>|</ModuleDeclaration>, "Widening") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Partial") End Sub <Fact> <WorkItem(554103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554103")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub PartialAfterPrivateTest() VerifyRecommendationsContain(<ModuleDeclaration>Private |</ModuleDeclaration>, "Partial") End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core/TypeForwarders.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.Runtime.CompilerServices; // Microsoft.CodeAnalysis.Editor.ContentTypeNames has been moved to Microsoft.CodeAnalysis.Editor.Text.dll [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Editor.ContentTypeNames))]
// 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.Runtime.CompilerServices; // Microsoft.CodeAnalysis.Editor.ContentTypeNames has been moved to Microsoft.CodeAnalysis.Editor.Text.dll [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Editor.ContentTypeNames))]
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/TestUtilities/TextEditorFactoryExtensions.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.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal static class TextEditorFactoryExtensions { public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory) => new DisposableTextView(textEditorFactory.CreateTextView()); public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory, ITextBuffer buffer, ImmutableArray<string> roles = default) { // Every default role but outlining. Starting in 15.2, the editor // OutliningManager imports JoinableTaskContext in a way that's // difficult to satisfy in our unit tests. Since we don't directly // depend on it, just disable it if (roles.IsDefault) { roles = ImmutableArray.Create(PredefinedTextViewRoles.Analyzable, PredefinedTextViewRoles.Document, PredefinedTextViewRoles.Editable, PredefinedTextViewRoles.Interactive, PredefinedTextViewRoles.Zoomable); } var roleSet = textEditorFactory.CreateTextViewRoleSet(roles); return new DisposableTextView(textEditorFactory.CreateTextView(buffer, roleSet)); } } public class DisposableTextView : IDisposable { public DisposableTextView(IWpfTextView textView) => this.TextView = textView; public IWpfTextView TextView { get; } public void Dispose() => TextView.Close(); } }
// 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.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using System; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal static class TextEditorFactoryExtensions { public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory) => new DisposableTextView(textEditorFactory.CreateTextView()); public static DisposableTextView CreateDisposableTextView(this ITextEditorFactoryService textEditorFactory, ITextBuffer buffer, ImmutableArray<string> roles = default) { // Every default role but outlining. Starting in 15.2, the editor // OutliningManager imports JoinableTaskContext in a way that's // difficult to satisfy in our unit tests. Since we don't directly // depend on it, just disable it if (roles.IsDefault) { roles = ImmutableArray.Create(PredefinedTextViewRoles.Analyzable, PredefinedTextViewRoles.Document, PredefinedTextViewRoles.Editable, PredefinedTextViewRoles.Interactive, PredefinedTextViewRoles.Zoomable); } var roleSet = textEditorFactory.CreateTextViewRoleSet(roles); return new DisposableTextView(textEditorFactory.CreateTextView(buffer, roleSet)); } } public class DisposableTextView : IDisposable { public DisposableTextView(IWpfTextView textView) => this.TextView = textView; public IWpfTextView TextView { get; } public void Dispose() => TextView.Close(); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/Syntax/InternalSyntax/ChildSyntaxList.Reversed.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; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial struct ChildSyntaxList { internal partial struct Reversed { private readonly GreenNode? _node; internal Reversed(GreenNode? node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } #if DEBUG #pragma warning disable 618 [Obsolete("For debugging", error: true)] private GreenNode[] Nodes { get { var result = new List<GreenNode>(); foreach (var n in this) { result.Add(n); } return result.ToArray(); } } #pragma warning restore 618 #endif } } }
// 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; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal partial struct ChildSyntaxList { internal partial struct Reversed { private readonly GreenNode? _node; internal Reversed(GreenNode? node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } #if DEBUG #pragma warning disable 618 [Obsolete("For debugging", error: true)] private GreenNode[] Nodes { get { var result = new List<GreenNode>(); foreach (var n in this) { result.Add(n); } return result.ToArray(); } } #pragma warning restore 618 #endif } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Def/Implementation/Library/ClassView/AbstractSyncClassViewCommandHandler.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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ClassView { internal abstract class AbstractSyncClassViewCommandHandler : ForegroundThreadAffinitizedObject, ICommandHandler<SyncClassViewCommandArgs> { private const string ClassView = "Class View"; private readonly IServiceProvider _serviceProvider; public string DisplayName => ServicesVSResources.Sync_Class_View; protected AbstractSyncClassViewCommandHandler( IThreadingContext threadingContext, SVsServiceProvider serviceProvider) : base(threadingContext) { Contract.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; } public bool ExecuteCommand(SyncClassViewCommandArgs args, CommandExecutionContext context) { this.AssertIsForeground(); var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; if (caretPosition < 0) { return false; } var snapshot = args.SubjectBuffer.CurrentSnapshot; using var waitScope = context.OperationContext.AddScope(allowCancellation: true, string.Format(ServicesVSResources.Synchronizing_with_0, ClassView)); var document = snapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); if (document == null) { return true; } var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFactsService == null) { return true; } var libraryService = document.GetLanguageService<ILibraryService>(); if (libraryService == null) { return true; } var userCancellationToken = context.OperationContext.UserCancellationToken; var semanticModel = document .GetSemanticModelAsync(userCancellationToken) .WaitAndGetResult(userCancellationToken); var root = semanticModel.SyntaxTree .GetRootAsync(userCancellationToken) .WaitAndGetResult(userCancellationToken); var memberDeclaration = syntaxFactsService.GetContainingMemberDeclaration(root, caretPosition); var symbol = memberDeclaration != null ? semanticModel.GetDeclaredSymbol(memberDeclaration, userCancellationToken) : null; while (symbol != null && !IsValidSymbolToSynchronize(symbol)) { symbol = symbol.ContainingSymbol; } IVsNavInfo navInfo = null; if (symbol != null) { navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, semanticModel.Compilation, useExpandedHierarchy: true); } if (navInfo == null) { navInfo = libraryService.NavInfoFactory.CreateForProject(document.Project); } if (navInfo == null) { return true; } var navigationTool = IServiceProviderExtensions.GetService<SVsClassView, IVsNavigationTool>(_serviceProvider); navigationTool.NavigateToNavInfo(navInfo); return true; } private static bool IsValidSymbolToSynchronize(ISymbol symbol) => symbol.Kind is SymbolKind.Event or SymbolKind.Field or SymbolKind.Method or SymbolKind.NamedType or SymbolKind.Property; public CommandState GetCommandState(SyncClassViewCommandArgs args) => Commanding.CommandState.Available; } }
// 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.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ClassView { internal abstract class AbstractSyncClassViewCommandHandler : ForegroundThreadAffinitizedObject, ICommandHandler<SyncClassViewCommandArgs> { private const string ClassView = "Class View"; private readonly IServiceProvider _serviceProvider; public string DisplayName => ServicesVSResources.Sync_Class_View; protected AbstractSyncClassViewCommandHandler( IThreadingContext threadingContext, SVsServiceProvider serviceProvider) : base(threadingContext) { Contract.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; } public bool ExecuteCommand(SyncClassViewCommandArgs args, CommandExecutionContext context) { this.AssertIsForeground(); var caretPosition = args.TextView.GetCaretPoint(args.SubjectBuffer) ?? -1; if (caretPosition < 0) { return false; } var snapshot = args.SubjectBuffer.CurrentSnapshot; using var waitScope = context.OperationContext.AddScope(allowCancellation: true, string.Format(ServicesVSResources.Synchronizing_with_0, ClassView)); var document = snapshot.GetFullyLoadedOpenDocumentInCurrentContextWithChangesAsync( context.OperationContext).WaitAndGetResult(context.OperationContext.UserCancellationToken); if (document == null) { return true; } var syntaxFactsService = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFactsService == null) { return true; } var libraryService = document.GetLanguageService<ILibraryService>(); if (libraryService == null) { return true; } var userCancellationToken = context.OperationContext.UserCancellationToken; var semanticModel = document .GetSemanticModelAsync(userCancellationToken) .WaitAndGetResult(userCancellationToken); var root = semanticModel.SyntaxTree .GetRootAsync(userCancellationToken) .WaitAndGetResult(userCancellationToken); var memberDeclaration = syntaxFactsService.GetContainingMemberDeclaration(root, caretPosition); var symbol = memberDeclaration != null ? semanticModel.GetDeclaredSymbol(memberDeclaration, userCancellationToken) : null; while (symbol != null && !IsValidSymbolToSynchronize(symbol)) { symbol = symbol.ContainingSymbol; } IVsNavInfo navInfo = null; if (symbol != null) { navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, document.Project, semanticModel.Compilation, useExpandedHierarchy: true); } if (navInfo == null) { navInfo = libraryService.NavInfoFactory.CreateForProject(document.Project); } if (navInfo == null) { return true; } var navigationTool = IServiceProviderExtensions.GetService<SVsClassView, IVsNavigationTool>(_serviceProvider); navigationTool.NavigateToNavInfo(navInfo); return true; } private static bool IsValidSymbolToSynchronize(ISymbol symbol) => symbol.Kind is SymbolKind.Event or SymbolKind.Field or SymbolKind.Method or SymbolKind.NamedType or SymbolKind.Property; public CommandState GetCommandState(SyncClassViewCommandArgs args) => Commanding.CommandState.Available; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Def/ValueTracking/ValueTrackingToolWindow.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.Linq; using System.Windows.Controls; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { [Guid(Guids.ValueTrackingToolWindowIdString)] internal class ValueTrackingToolWindow : ToolWindowPane { private readonly ValueTrackingRoot _root = new(); public static ValueTrackingToolWindow? Instance { get; set; } private ValueTrackingTreeViewModel? _viewModel; public ValueTrackingTreeViewModel? ViewModel { get => _viewModel; set { if (value is null) { throw new ArgumentNullException(nameof(ViewModel)); } _viewModel = value; _root.SetChild(new ValueTrackingTree(_viewModel)); } } /// <summary> /// This paramterless constructor is used when /// the tool window is initialized on open without any /// context. If the tool window is left open across shutdown/restart /// of VS for example, then this gets called. /// </summary> public ValueTrackingToolWindow() : base(null) { Caption = ServicesVSResources.Value_Tracking; Content = _root; } public ValueTrackingToolWindow(ValueTrackingTreeViewModel viewModel) : base(null) { Caption = ServicesVSResources.Value_Tracking; Content = _root; ViewModel = viewModel; } public TreeItemViewModel? Root { get => ViewModel?.Roots.Single(); set { if (value is null) { return; } Contract.ThrowIfNull(ViewModel); ViewModel.Roots.Clear(); ViewModel.Roots.Add(value); } } } }
// 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.Linq; using System.Windows.Controls; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell; using Roslyn.Utilities; using System.Windows; using System.Windows.Data; using System.Windows.Markup; namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { [Guid(Guids.ValueTrackingToolWindowIdString)] internal class ValueTrackingToolWindow : ToolWindowPane { private readonly ValueTrackingRoot _root = new(); public static ValueTrackingToolWindow? Instance { get; set; } private ValueTrackingTreeViewModel? _viewModel; public ValueTrackingTreeViewModel? ViewModel { get => _viewModel; set { if (value is null) { throw new ArgumentNullException(nameof(ViewModel)); } _viewModel = value; _root.SetChild(new ValueTrackingTree(_viewModel)); } } /// <summary> /// This paramterless constructor is used when /// the tool window is initialized on open without any /// context. If the tool window is left open across shutdown/restart /// of VS for example, then this gets called. /// </summary> public ValueTrackingToolWindow() : base(null) { Caption = ServicesVSResources.Value_Tracking; Content = _root; } public ValueTrackingToolWindow(ValueTrackingTreeViewModel viewModel) : base(null) { Caption = ServicesVSResources.Value_Tracking; Content = _root; ViewModel = viewModel; } public TreeItemViewModel? Root { get => ViewModel?.Roots.Single(); set { if (value is null) { return; } Contract.ThrowIfNull(ViewModel); ViewModel.Roots.Clear(); ViewModel.Roots.Add(value); } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Source/SourceModuleSymbol.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents the primary module of an assembly being built by compiler. /// </summary> internal sealed class SourceModuleSymbol : NonMissingModuleSymbol, IAttributeTargetSymbol { /// <summary> /// Owning assembly. /// </summary> private readonly SourceAssemblySymbol _assemblySymbol; private ImmutableArray<AssemblySymbol> _lazyAssembliesToEmbedTypesFrom; private ThreeState _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeState.Unknown; /// <summary> /// The declarations corresponding to the source files of this module. /// </summary> private readonly DeclarationTable _sources; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private ImmutableArray<Location> _locations; private NamespaceSymbol _globalNamespace; private bool _hasBadAttributes; internal SourceModuleSymbol( SourceAssemblySymbol assemblySymbol, DeclarationTable declarations, string moduleName) { Debug.Assert((object)assemblySymbol != null); _assemblySymbol = assemblySymbol; _sources = declarations; _name = moduleName; } internal void RecordPresenceOfBadAttributes() { _hasBadAttributes = true; } internal bool HasBadAttributes { get { return _hasBadAttributes; } } internal override int Ordinal { get { return 0; } } internal override Machine Machine { get { switch (DeclaringCompilation.Options.Platform) { case Platform.Arm: return Machine.ArmThumb2; case Platform.X64: return Machine.Amd64; case Platform.Arm64: return Machine.Arm64; case Platform.Itanium: return Machine.IA64; default: return Machine.I386; } } } internal override bool Bit32Required { get { return DeclaringCompilation.Options.Platform == Platform.X86; } } internal bool AnyReferencedAssembliesAreLinked { get { return GetAssembliesToEmbedTypesFrom().Length > 0; } } internal bool MightContainNoPiaLocalTypes() { return AnyReferencedAssembliesAreLinked || ContainsExplicitDefinitionOfNoPiaLocalTypes; } internal ImmutableArray<AssemblySymbol> GetAssembliesToEmbedTypesFrom() { if (_lazyAssembliesToEmbedTypesFrom.IsDefault) { AssertReferencesInitialized(); var buffer = ArrayBuilder<AssemblySymbol>.GetInstance(); foreach (AssemblySymbol asm in this.GetReferencedAssemblySymbols()) { if (asm.IsLinked) { buffer.Add(asm); } } ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssembliesToEmbedTypesFrom, buffer.ToImmutableAndFree(), default(ImmutableArray<AssemblySymbol>)); } Debug.Assert(!_lazyAssembliesToEmbedTypesFrom.IsDefault); return _lazyAssembliesToEmbedTypesFrom; } internal bool ContainsExplicitDefinitionOfNoPiaLocalTypes { get { if (_lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.Unknown) { _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(GlobalNamespace).ToThreeState(); } Debug.Assert(_lazyContainsExplicitDefinitionOfNoPiaLocalTypes != ThreeState.Unknown); return _lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.True; } } private static bool NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(NamespaceSymbol ns) { foreach (Symbol s in ns.GetMembersUnordered()) { switch (s.Kind) { case SymbolKind.Namespace: if (NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes((NamespaceSymbol)s)) { return true; } break; case SymbolKind.NamedType: if (((NamedTypeSymbol)s).IsExplicitDefinitionOfNoPiaLocalType) { return true; } break; } } return false; } public override NamespaceSymbol GlobalNamespace { get { if ((object)_globalNamespace == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var globalNS = new SourceNamespaceSymbol( this, this, DeclaringCompilation.MergedRootDeclaration, diagnostics); if (Interlocked.CompareExchange(ref _globalNamespace, globalNS, null) == null) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _globalNamespace; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartValidatingReferencedAssemblies: { BindingDiagnosticBag diagnostics = null; if (AnyReferencedAssembliesAreLinked) { diagnostics = BindingDiagnosticBag.GetInstance(); ValidateLinkedAssemblies(diagnostics, cancellationToken); } if (_state.NotePartComplete(CompletionPart.StartValidatingReferencedAssemblies)) { if (diagnostics != null) { _assemblySymbol.AddDeclarationDiagnostics(diagnostics); } _state.NotePartComplete(CompletionPart.FinishValidatingReferencedAssemblies); } if (diagnostics != null) { diagnostics.Free(); } } break; case CompletionPart.FinishValidatingReferencedAssemblies: // some other thread has started validating references (otherwise we would be in the case above) so // we just wait for it to both finish and report the diagnostics. Debug.Assert(_state.HasComplete(CompletionPart.StartValidatingReferencedAssemblies)); _state.SpinWaitComplete(CompletionPart.FinishValidatingReferencedAssemblies, cancellationToken); break; case CompletionPart.MembersCompleted: this.GlobalNamespace.ForceComplete(locationOpt, cancellationToken); if (this.GlobalNamespace.HasComplete(CompletionPart.MembersCompleted)) { _state.NotePartComplete(CompletionPart.MembersCompleted); } else { Debug.Assert(locationOpt != null, "If no location was specified, then the namespace members should be completed"); return; } break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(incompletePart); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } private void ValidateLinkedAssemblies(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { foreach (AssemblySymbol a in GetReferencedAssemblySymbols()) { cancellationToken.ThrowIfCancellationRequested(); if (!a.IsMissing && a.IsLinked) { bool hasGuidAttribute = false; bool hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = false; foreach (var attrData in a.GetAttributes()) { if (attrData.IsTargetAttribute(a, AttributeDescription.GuidAttribute)) { string guidString; if (attrData.TryGetGuidAttributeValue(out guidString)) { hasGuidAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.ImportedFromTypeLibAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.PrimaryInteropAssemblyAttribute)) { if (attrData.CommonConstructorArguments.Length == 2) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } if (hasGuidAttribute && hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { break; } } if (!hasGuidAttribute) { // ERRID_PIAHasNoAssemblyGuid1/ERR_NoPIAAssemblyMissingAttribute diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttribute, NoLocation.Singleton, a, AttributeDescription.GuidAttribute.FullName); } if (!hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { // ERRID_PIAHasNoTypeLibAttribute1/ERR_NoPIAAssemblyMissingAttributes diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttributes, NoLocation.Singleton, a, AttributeDescription.ImportedFromTypeLibAttribute.FullName, AttributeDescription.PrimaryInteropAssemblyAttribute.FullName); } } } } public override ImmutableArray<Location> Locations { get { if (_locations.IsDefault) { ImmutableInterlocked.InterlockedInitialize( ref _locations, DeclaringCompilation.MergedRootDeclaration.Declarations.SelectAsArray(d => (Location)d.Location)); } return _locations; } } /// <summary> /// The name (contains extension) /// </summary> private readonly string _name; public override string Name { get { return _name; } } public override Symbol ContainingSymbol { get { return _assemblySymbol; } } public override AssemblySymbol ContainingAssembly { get { return _assemblySymbol; } } internal SourceAssemblySymbol ContainingSourceAssembly { get { return _assemblySymbol; } } /// <remarks> /// This override is essential - it's a base case of the recursive definition. /// </remarks> internal override CSharpCompilation DeclaringCompilation { get { return _assemblySymbol.DeclaringCompilation; } } internal override ICollection<string> TypeNames { get { return _sources.TypeNames; } } internal override ICollection<string> NamespaceNames { get { return _sources.NamespaceNames; } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return _assemblySymbol; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Module; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return ContainingAssembly.IsInteractive ? AttributeLocation.None : AttributeLocation.Assembly | AttributeLocation.Module; } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { var mergedAttributes = ((SourceAssemblySymbol)this.ContainingAssembly).GetAttributeDeclarations(); if (LoadAndValidateAttributes(OneOrMany.Create(mergedAttributes), ref _lazyCustomAttributesBag)) { var completed = _state.NotePartComplete(CompletionPart.Attributes); Debug.Assert(completed); } } return _lazyCustomAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private ModuleWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ModuleWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultCharSetAttribute)) { CharSet charSet = attribute.GetConstructorArgument<CharSet>(0, SpecialType.System_Enum); if (!ModuleWellKnownAttributeData.IsValidCharSet(charSet)) { CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); } else { arguments.GetOrCreateData<ModuleWellKnownAttributeData>().DefaultCharacterSet = charSet; } } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.NullableContextAttribute | ReservedAttributes.NullablePublicOnlyAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) { CSharpAttributeData.DecodeSkipLocalsInitAttribute<ModuleWellKnownAttributeData>(DeclaringCompilation, ref arguments); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = _assemblySymbol.DeclaringCompilation; if (compilation.Options.AllowUnsafe) { // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known type isn't available. if (!(compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute) is MissingMetadataTypeSymbol)) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Security_UnverifiableCodeAttribute__ctor)); } } if (moduleBuilder.ShouldEmitNullablePublicOnlyAttribute()) { var includesInternals = ImmutableArray.Create( new TypedConstant(compilation.GetSpecialType(SpecialType.System_Boolean), TypedConstantKind.Primitive, _assemblySymbol.InternalsAreVisible)); AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullablePublicOnlyAttribute(includesInternals)); } } internal override bool HasAssemblyCompilationRelaxationsAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasCompilationRelaxationsAttribute; } } internal override bool HasAssemblyRuntimeCompatibilityAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasRuntimeCompatibilityAttribute; } } internal override CharSet? DefaultMarshallingCharSet { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasDefaultCharSetAttribute ? data.DefaultCharacterSet : (CharSet?)null; } } public sealed override bool AreLocalsZeroed { get { var data = GetDecodedWellKnownAttributeData(); return data?.HasSkipLocalsInitAttribute != true; } } public override ModuleMetadata GetMetadata() => 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents the primary module of an assembly being built by compiler. /// </summary> internal sealed class SourceModuleSymbol : NonMissingModuleSymbol, IAttributeTargetSymbol { /// <summary> /// Owning assembly. /// </summary> private readonly SourceAssemblySymbol _assemblySymbol; private ImmutableArray<AssemblySymbol> _lazyAssembliesToEmbedTypesFrom; private ThreeState _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = ThreeState.Unknown; /// <summary> /// The declarations corresponding to the source files of this module. /// </summary> private readonly DeclarationTable _sources; private SymbolCompletionState _state; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private ImmutableArray<Location> _locations; private NamespaceSymbol _globalNamespace; private bool _hasBadAttributes; internal SourceModuleSymbol( SourceAssemblySymbol assemblySymbol, DeclarationTable declarations, string moduleName) { Debug.Assert((object)assemblySymbol != null); _assemblySymbol = assemblySymbol; _sources = declarations; _name = moduleName; } internal void RecordPresenceOfBadAttributes() { _hasBadAttributes = true; } internal bool HasBadAttributes { get { return _hasBadAttributes; } } internal override int Ordinal { get { return 0; } } internal override Machine Machine { get { switch (DeclaringCompilation.Options.Platform) { case Platform.Arm: return Machine.ArmThumb2; case Platform.X64: return Machine.Amd64; case Platform.Arm64: return Machine.Arm64; case Platform.Itanium: return Machine.IA64; default: return Machine.I386; } } } internal override bool Bit32Required { get { return DeclaringCompilation.Options.Platform == Platform.X86; } } internal bool AnyReferencedAssembliesAreLinked { get { return GetAssembliesToEmbedTypesFrom().Length > 0; } } internal bool MightContainNoPiaLocalTypes() { return AnyReferencedAssembliesAreLinked || ContainsExplicitDefinitionOfNoPiaLocalTypes; } internal ImmutableArray<AssemblySymbol> GetAssembliesToEmbedTypesFrom() { if (_lazyAssembliesToEmbedTypesFrom.IsDefault) { AssertReferencesInitialized(); var buffer = ArrayBuilder<AssemblySymbol>.GetInstance(); foreach (AssemblySymbol asm in this.GetReferencedAssemblySymbols()) { if (asm.IsLinked) { buffer.Add(asm); } } ImmutableInterlocked.InterlockedCompareExchange(ref _lazyAssembliesToEmbedTypesFrom, buffer.ToImmutableAndFree(), default(ImmutableArray<AssemblySymbol>)); } Debug.Assert(!_lazyAssembliesToEmbedTypesFrom.IsDefault); return _lazyAssembliesToEmbedTypesFrom; } internal bool ContainsExplicitDefinitionOfNoPiaLocalTypes { get { if (_lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.Unknown) { _lazyContainsExplicitDefinitionOfNoPiaLocalTypes = NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(GlobalNamespace).ToThreeState(); } Debug.Assert(_lazyContainsExplicitDefinitionOfNoPiaLocalTypes != ThreeState.Unknown); return _lazyContainsExplicitDefinitionOfNoPiaLocalTypes == ThreeState.True; } } private static bool NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes(NamespaceSymbol ns) { foreach (Symbol s in ns.GetMembersUnordered()) { switch (s.Kind) { case SymbolKind.Namespace: if (NamespaceContainsExplicitDefinitionOfNoPiaLocalTypes((NamespaceSymbol)s)) { return true; } break; case SymbolKind.NamedType: if (((NamedTypeSymbol)s).IsExplicitDefinitionOfNoPiaLocalType) { return true; } break; } } return false; } public override NamespaceSymbol GlobalNamespace { get { if ((object)_globalNamespace == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var globalNS = new SourceNamespaceSymbol( this, this, DeclaringCompilation.MergedRootDeclaration, diagnostics); if (Interlocked.CompareExchange(ref _globalNamespace, globalNS, null) == null) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _globalNamespace; } } internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return _state.HasComplete(part); } internal override void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var incompletePart = _state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartValidatingReferencedAssemblies: { BindingDiagnosticBag diagnostics = null; if (AnyReferencedAssembliesAreLinked) { diagnostics = BindingDiagnosticBag.GetInstance(); ValidateLinkedAssemblies(diagnostics, cancellationToken); } if (_state.NotePartComplete(CompletionPart.StartValidatingReferencedAssemblies)) { if (diagnostics != null) { _assemblySymbol.AddDeclarationDiagnostics(diagnostics); } _state.NotePartComplete(CompletionPart.FinishValidatingReferencedAssemblies); } if (diagnostics != null) { diagnostics.Free(); } } break; case CompletionPart.FinishValidatingReferencedAssemblies: // some other thread has started validating references (otherwise we would be in the case above) so // we just wait for it to both finish and report the diagnostics. Debug.Assert(_state.HasComplete(CompletionPart.StartValidatingReferencedAssemblies)); _state.SpinWaitComplete(CompletionPart.FinishValidatingReferencedAssemblies, cancellationToken); break; case CompletionPart.MembersCompleted: this.GlobalNamespace.ForceComplete(locationOpt, cancellationToken); if (this.GlobalNamespace.HasComplete(CompletionPart.MembersCompleted)) { _state.NotePartComplete(CompletionPart.MembersCompleted); } else { Debug.Assert(locationOpt != null, "If no location was specified, then the namespace members should be completed"); return; } break; case CompletionPart.None: return; default: // any other values are completion parts intended for other kinds of symbols _state.NotePartComplete(incompletePart); break; } _state.SpinWaitComplete(incompletePart, cancellationToken); } } private void ValidateLinkedAssemblies(BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { foreach (AssemblySymbol a in GetReferencedAssemblySymbols()) { cancellationToken.ThrowIfCancellationRequested(); if (!a.IsMissing && a.IsLinked) { bool hasGuidAttribute = false; bool hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = false; foreach (var attrData in a.GetAttributes()) { if (attrData.IsTargetAttribute(a, AttributeDescription.GuidAttribute)) { string guidString; if (attrData.TryGetGuidAttributeValue(out guidString)) { hasGuidAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.ImportedFromTypeLibAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } else if (attrData.IsTargetAttribute(a, AttributeDescription.PrimaryInteropAssemblyAttribute)) { if (attrData.CommonConstructorArguments.Length == 2) { hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute = true; } } if (hasGuidAttribute && hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { break; } } if (!hasGuidAttribute) { // ERRID_PIAHasNoAssemblyGuid1/ERR_NoPIAAssemblyMissingAttribute diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttribute, NoLocation.Singleton, a, AttributeDescription.GuidAttribute.FullName); } if (!hasImportedFromTypeLibOrPrimaryInteropAssemblyAttribute) { // ERRID_PIAHasNoTypeLibAttribute1/ERR_NoPIAAssemblyMissingAttributes diagnostics.Add(ErrorCode.ERR_NoPIAAssemblyMissingAttributes, NoLocation.Singleton, a, AttributeDescription.ImportedFromTypeLibAttribute.FullName, AttributeDescription.PrimaryInteropAssemblyAttribute.FullName); } } } } public override ImmutableArray<Location> Locations { get { if (_locations.IsDefault) { ImmutableInterlocked.InterlockedInitialize( ref _locations, DeclaringCompilation.MergedRootDeclaration.Declarations.SelectAsArray(d => (Location)d.Location)); } return _locations; } } /// <summary> /// The name (contains extension) /// </summary> private readonly string _name; public override string Name { get { return _name; } } public override Symbol ContainingSymbol { get { return _assemblySymbol; } } public override AssemblySymbol ContainingAssembly { get { return _assemblySymbol; } } internal SourceAssemblySymbol ContainingSourceAssembly { get { return _assemblySymbol; } } /// <remarks> /// This override is essential - it's a base case of the recursive definition. /// </remarks> internal override CSharpCompilation DeclaringCompilation { get { return _assemblySymbol.DeclaringCompilation; } } internal override ICollection<string> TypeNames { get { return _sources.TypeNames; } } internal override ICollection<string> NamespaceNames { get { return _sources.NamespaceNames; } } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return _assemblySymbol; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Module; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { return ContainingAssembly.IsInteractive ? AttributeLocation.None : AttributeLocation.Assembly | AttributeLocation.Module; } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { if (_lazyCustomAttributesBag == null || !_lazyCustomAttributesBag.IsSealed) { var mergedAttributes = ((SourceAssemblySymbol)this.ContainingAssembly).GetAttributeDeclarations(); if (LoadAndValidateAttributes(OneOrMany.Create(mergedAttributes), ref _lazyCustomAttributesBag)) { var completed = _state.NotePartComplete(CompletionPart.Attributes); Debug.Assert(completed); } } return _lazyCustomAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> /// <remarks> /// NOTE: This method should always be kept as a sealed override. /// If you want to override attribute binding logic for a sub-class, then override <see cref="GetAttributesBag"/> method. /// </remarks> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private ModuleWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (ModuleWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } internal override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultCharSetAttribute)) { CharSet charSet = attribute.GetConstructorArgument<CharSet>(0, SpecialType.System_Enum); if (!ModuleWellKnownAttributeData.IsValidCharSet(charSet)) { CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, arguments.AttributeSyntaxOpt); ((BindingDiagnosticBag)arguments.Diagnostics).Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, arguments.AttributeSyntaxOpt.GetErrorDisplayName()); } else { arguments.GetOrCreateData<ModuleWellKnownAttributeData>().DefaultCharacterSet = charSet; } } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.NullableContextAttribute | ReservedAttributes.NullablePublicOnlyAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) { CSharpAttributeData.DecodeSkipLocalsInitAttribute<ModuleWellKnownAttributeData>(DeclaringCompilation, ref arguments); } } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = _assemblySymbol.DeclaringCompilation; if (compilation.Options.AllowUnsafe) { // NOTE: GlobalAttrBind::EmitCompilerGeneratedAttrs skips attribute if the well-known type isn't available. if (!(compilation.GetWellKnownType(WellKnownType.System_Security_UnverifiableCodeAttribute) is MissingMetadataTypeSymbol)) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Security_UnverifiableCodeAttribute__ctor)); } } if (moduleBuilder.ShouldEmitNullablePublicOnlyAttribute()) { var includesInternals = ImmutableArray.Create( new TypedConstant(compilation.GetSpecialType(SpecialType.System_Boolean), TypedConstantKind.Primitive, _assemblySymbol.InternalsAreVisible)); AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullablePublicOnlyAttribute(includesInternals)); } } internal override bool HasAssemblyCompilationRelaxationsAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasCompilationRelaxationsAttribute; } } internal override bool HasAssemblyRuntimeCompatibilityAttribute { get { CommonAssemblyWellKnownAttributeData<NamedTypeSymbol> decodedData = ((SourceAssemblySymbol)this.ContainingAssembly).GetSourceDecodedWellKnownAttributeData(); return decodedData != null && decodedData.HasRuntimeCompatibilityAttribute; } } internal override CharSet? DefaultMarshallingCharSet { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasDefaultCharSetAttribute ? data.DefaultCharacterSet : (CharSet?)null; } } public sealed override bool AreLocalsZeroed { get { var data = GetDecodedWellKnownAttributeData(); return data?.HasSkipLocalsInitAttribute != true; } } public override ModuleMetadata GetMetadata() => null; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenForeach.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 Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenForeach Inherits BasicTestBase ' The loop object must be an array or an object collection <Fact> Public Sub SimpleForeachTest() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ one two ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 46 (0x2e) .maxstack 4 .locals init (String() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "String" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr "one" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr "two" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0027 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: call "Sub System.Console.WriteLine(String)" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add.ovf IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloc.0 IL_0029: ldlen IL_002a: conv.i4 IL_002b: blt.s IL_001b IL_002d: ret } ]]>).Compilation End Sub ' Type is not required in a foreach statement <Fact> Public Sub TypeIsNotRequiredTest() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Class C Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For Each item In myarray Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE")).VerifyIL("C.Main", <![CDATA[ { // Code size 37 (0x25) .maxstack 3 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_001e IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i4 IL_0019: pop IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: add.ovf IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: ldloc.0 IL_0020: ldlen IL_0021: conv.i4 IL_0022: blt.s IL_0016 IL_0024: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {45, 3} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 45 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 42 (0x2a) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 45 IL_000a: conv.i8 IL_000b: stelem.i8 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.3 IL_000f: conv.i8 IL_0010: stelem.i8 IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_0023 IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i8 IL_0019: conv.ovf.i4 IL_001a: call "Sub System.Console.WriteLine(Integer)" IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: add.ovf IL_0022: stloc.1 IL_0023: ldloc.1 IL_0024: ldloc.0 IL_0025: ldlen IL_0026: conv.i4 IL_0027: blt.s IL_0016 IL_0029: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions_2() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {9876543210} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i8 0x24cb016ea IL_0011: stelem.i8 IL_0012: stloc.0 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: br.s IL_0024 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldelem.i8 IL_001a: conv.ovf.i4 IL_001b: call "Sub System.Console.WriteLine(Integer)" IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: add.ovf IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: ldloc.0 IL_0026: ldlen IL_0027: conv.i4 IL_0028: blt.s IL_0017 IL_002a: ret } ]]>) End Sub ' Multiline <Fact> Public Sub Multiline() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Public Sub Main() Dim a() As Integer = New Integer() {7} For Each x As Integer In a : System.Console.WriteLine(x) : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_001b IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: call "Sub System.Console.WriteLine(Integer)" IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: add.ovf IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: ldloc.0 IL_001d: ldlen IL_001e: conv.i4 IL_001f: blt.s IL_000f IL_0021: ret } ]]>) End Sub ' Line continuations <Fact> Public Sub LineContinuations() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Public Shared Sub Main() Dim a() As Integer = New Integer() {7} For _ Each _ x _ As _ Integer _ In _ a _ _ : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_0017 IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: pop IL_0013: ldloc.1 IL_0014: ldc.i4.1 IL_0015: add.ovf IL_0016: stloc.1 IL_0017: ldloc.1 IL_0018: ldloc.0 IL_0019: ldlen IL_001a: conv.i4 IL_001b: blt.s IL_000f IL_001d: ret } ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub IterationVarInConditionalExpression() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each x As S In If(True, x, 1) Next End Sub End Class Public Structure S End Structure </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (S V_0, System.Collections.IEnumerator V_1, S V_2) .try { IL_0000: ldloc.0 IL_0001: box "S" IL_0006: castclass "System.Collections.IEnumerable" IL_000b: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0010: stloc.1 IL_0011: br.s IL_002e IL_0013: ldloc.1 IL_0014: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0019: dup IL_001a: brtrue.s IL_0028 IL_001c: pop IL_001d: ldloca.s V_2 IL_001f: initobj "S" IL_0025: ldloc.2 IL_0026: br.s IL_002d IL_0028: unbox.any "S" IL_002d: pop IL_002e: ldloc.1 IL_002f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0034: brtrue.s IL_0013 IL_0036: leave.s IL_004c } finally { IL_0038: ldloc.1 IL_0039: isinst "System.IDisposable" IL_003e: brfalse.s IL_004b IL_0040: ldloc.1 IL_0041: isinst "System.IDisposable" IL_0046: callvirt "Sub System.IDisposable.Dispose()" IL_004b: endfinally } IL_004c: ret } ]]>) End Sub ' Use the declared variable to initialize collection <Fact> Public Sub IterationVarInCollectionExpression_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {x + 5, x + 6, x + 7} System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 5 6 7 ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub TraversingNothing() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each item In Nothing Next End Sub End Class </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldnull IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0015 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: pop IL_0015: ldloc.0 IL_0016: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001b: brtrue.s IL_0009 IL_001d: leave.s IL_0033 } finally { IL_001f: ldloc.0 IL_0020: isinst "System.IDisposable" IL_0025: brfalse.s IL_0032 IL_0027: ldloc.0 IL_0028: isinst "System.IDisposable" IL_002d: callvirt "Sub System.IDisposable.Dispose()" IL_0032: endfinally } IL_0033: ret } ]]>) End Sub ' Nested ForEach can use a var declared in the outer ForEach <Fact> Public Sub NestedForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x System .Console .WriteLine (y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ]]>) End Sub ' Inner foreach loop referencing the outer foreach loop iteration variable <Fact> Public Sub NestedForeach_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C X Y Z ]]>) End Sub ' Foreach value can't be modified in a loop <Fact> Public Sub ModifyIterationValueInLoop() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Class C Shared Sub Main() Dim list As New ArrayList() list.Add("One") list.Add("Two") For Each s As String In list s = "a" Next For Each s As String In list System.Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ One Two ]]>) End Sub ' Pass fields as a ref argument for 'foreach iteration variable' <Fact()> Public Sub PassFieldsAsRefArgument() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim sa As S() = New S(2) {New S With {.I = 1}, New S With {.I = 2}, New S With {.I = 3}} For Each s As S In sa f(s.i) Next For Each s As S In sa System.Console.WriteLine(s.i) Next End Sub Private Shared Sub f(ByRef iref As Integer) iref = 1 End Sub End Class Structure S Public I As integer End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>) End Sub ' With multidimensional arrays, you can use one loop to iterate through the elements <Fact> Public Sub TraversingMultidimensionalArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D(,) As Integer = New Integer (2,1) {} numbers2D(0,0) = 9 numbers2D(0,1) = 99 numbers2D(1,0) = 3 numbers2D(1,1) = 33 numbers2D(2,0) = 5 numbers2D(2,1) = 55 For Each i As Integer In numbers2D System.Console.WriteLine(i) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 9 99 3 33 5 55 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 98 (0x62) .maxstack 5 .locals init (System.Collections.IEnumerator V_0) IL_0000: ldc.i4.3 IL_0001: ldc.i4.2 IL_0002: newobj "Integer(*,*)..ctor" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 9 IL_000c: call "Integer(*,*).Set" IL_0011: dup IL_0012: ldc.i4.0 IL_0013: ldc.i4.1 IL_0014: ldc.i4.s 99 IL_0016: call "Integer(*,*).Set" IL_001b: dup IL_001c: ldc.i4.1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.3 IL_001f: call "Integer(*,*).Set" IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.1 IL_0027: ldc.i4.s 33 IL_0029: call "Integer(*,*).Set" IL_002e: dup IL_002f: ldc.i4.2 IL_0030: ldc.i4.0 IL_0031: ldc.i4.5 IL_0032: call "Integer(*,*).Set" IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.1 IL_003a: ldc.i4.s 55 IL_003c: call "Integer(*,*).Set" IL_0041: callvirt "Function System.Array.GetEnumerator() As System.Collections.IEnumerator" IL_0046: stloc.0 IL_0047: br.s IL_0059 IL_0049: ldloc.0 IL_004a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0054: call "Sub System.Console.WriteLine(Integer)" IL_0059: ldloc.0 IL_005a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_005f: brtrue.s IL_0049 IL_0061: ret } ]]>) End Sub ' Traversing jagged arrays <Fact> Public Sub TraversingJaggedArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {4, 5, 6}} For Each x As Integer() In numbers2D For Each y As Integer In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 4 5 6 ]]>) End Sub ' Optimization to foreach (char c in String) by treating String as a char array <Fact()> Public Sub TraversingString() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim str As String = "ABC" For Each x In str System.Console.WriteLine(x) Next For Each var In "goo" If Not var.[GetType]().Equals(GetType(Char)) Then System.Console.WriteLine("False") End If Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C ]]>) End Sub ' Traversing items in Dictionary <Fact> Public Sub TraversingDictionary() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim s As New Dictionary(Of Integer, Integer)() s.Add(1, 2) s.Add(2, 3) s.Add(3, 4) For Each pair In s System .Console .WriteLine (pair.Key) Next For Each pair As KeyValuePair(Of Integer, Integer) In s System .Console .WriteLine (pair.Value ) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 2 3 4 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 141 (0x8d) .maxstack 3 .locals init (System.Collections.Generic.Dictionary(Of Integer, Integer) V_0, //s System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_1, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_2, //pair System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_3, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_4) //pair IL_0000: newobj "Sub System.Collections.Generic.Dictionary(Of Integer, Integer)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: ldc.i4.2 IL_0009: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_000e: ldloc.0 IL_000f: ldc.i4.2 IL_0010: ldc.i4.3 IL_0011: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_0016: ldloc.0 IL_0017: ldc.i4.3 IL_0018: ldc.i4.4 IL_0019: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" .try { IL_001e: ldloc.0 IL_001f: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0024: stloc.1 IL_0025: br.s IL_003b IL_0027: ldloca.s V_1 IL_0029: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Key() As Integer" IL_0036: call "Sub System.Console.WriteLine(Integer)" IL_003b: ldloca.s V_1 IL_003d: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_0042: brtrue.s IL_0027 IL_0044: leave.s IL_0054 } finally { IL_0046: ldloca.s V_1 IL_0048: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_004e: callvirt "Sub System.IDisposable.Dispose()" IL_0053: endfinally } IL_0054: nop .try { IL_0055: ldloc.0 IL_0056: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_005b: stloc.3 IL_005c: br.s IL_0073 IL_005e: ldloca.s V_3 IL_0060: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_0065: stloc.s V_4 IL_0067: ldloca.s V_4 IL_0069: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Value() As Integer" IL_006e: call "Sub System.Console.WriteLine(Integer)" IL_0073: ldloca.s V_3 IL_0075: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_007a: brtrue.s IL_005e IL_007c: leave.s IL_008c } finally { IL_007e: ldloca.s V_3 IL_0080: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0086: callvirt "Sub System.IDisposable.Dispose()" IL_008b: endfinally } IL_008c: ret } ]]>) End Sub ' Breaking from nested Loops <Fact> Public Sub BreakFromForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A X Y Z ]]>) End Sub ' Continuing for nested Loops <Fact> Public Sub ContinueInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y, x End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A C X Y Z ]]>) End Sub ' Query expression works in foreach <Fact()> Public Sub QueryExpressionInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Imports System Imports System.Collections Imports System.Linq Class C Public Shared Sub Main() For Each x In From w In New Integer() {1, 2, 3} Select z = w.ToString() System.Console.WriteLine(x.ToLower()) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), references:={LinqAssemblyRef}, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 103 (0x67) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator(Of String) V_0) .try { IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0016: brfalse.s IL_001f IL_0018: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_001d: br.s IL_0035 IL_001f: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0024: ldftn "Function C._Closure$__._Lambda$__1-0(Integer) As String" IL_002a: newobj "Sub System.Func(Of Integer, String)..ctor(Object, System.IntPtr)" IL_002f: dup IL_0030: stsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0035: call "Function System.Linq.Enumerable.Select(Of Integer, String)(System.Collections.Generic.IEnumerable(Of Integer), System.Func(Of Integer, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of String).GetEnumerator() As System.Collections.Generic.IEnumerator(Of String)" IL_003f: stloc.0 IL_0040: br.s IL_0052 IL_0042: ldloc.0 IL_0043: callvirt "Function System.Collections.Generic.IEnumerator(Of String).get_Current() As String" IL_0048: callvirt "Function String.ToLower() As String" IL_004d: call "Sub System.Console.WriteLine(String)" IL_0052: ldloc.0 IL_0053: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0058: brtrue.s IL_0042 IL_005a: leave.s IL_0066 } finally { IL_005c: ldloc.0 IL_005d: brfalse.s IL_0065 IL_005f: ldloc.0 IL_0060: callvirt "Sub System.IDisposable.Dispose()" IL_0065: endfinally } IL_0066: ret } ]]>) End Sub ' No confusion in a foreach statement when from is a value type <Fact> Public Sub ReDimFrom() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim src = New System.Collections.ArrayList() src.Add(new from(1)) For Each x As from In src System.Console.WriteLine(x.X) Next End Sub End Class Public Structure from Dim X As Integer Public Sub New(p as integer) x = p End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub ' Foreach on generic type that implements the Collection Pattern <Fact> Public Sub GenericTypeImplementsCollection() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() For Each j In New Gen(Of Integer)() Next End Sub End Class Public Class Gen(Of T As New) Public Function GetEnumerator() As IEnumerator(Of T) Return Nothing End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 1 .locals init (System.Collections.Generic.IEnumerator(Of Integer) V_0) .try { IL_0000: newobj "Sub Gen(Of Integer)..ctor()" IL_0005: call "Function Gen(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_000a: stloc.0 IL_000b: br.s IL_0014 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0013: pop IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001a: brtrue.s IL_000d IL_001c: leave.s IL_0028 } finally { IL_001e: ldloc.0 IL_001f: brfalse.s IL_0027 IL_0021: ldloc.0 IL_0022: callvirt "Sub System.IDisposable.Dispose()" IL_0027: endfinally } IL_0028: ret } ]]>) End Sub ' Customer defined type of collection to support 'foreach' <Fact> Public Sub CustomerDefinedCollections() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim col As New MyCollection() For Each i As Integer In col Console.WriteLine(i) Next End Sub End Class Public Class MyCollection Private items As Integer() Public Sub New() items = New Integer(4) {1, 4, 3, 2, 5} End Sub Public Function GetEnumerator() As MyEnumerator Return New MyEnumerator(Me) End Function Public Class MyEnumerator Private nIndex As Integer Private collection As MyCollection Public Sub New(coll As MyCollection) collection = coll nIndex = nIndex - 1 End Sub Public Function MoveNext() As Boolean nIndex = nIndex + 1 Return (nIndex &lt; collection.items.GetLength(0)) End Function Public ReadOnly Property Current() As Integer Get Return (collection.items(nIndex)) End Get End Property End Class End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 4 3 2 5 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (MyCollection.MyEnumerator V_0) IL_0000: newobj "Sub MyCollection..ctor()" IL_0005: callvirt "Function MyCollection.GetEnumerator() As MyCollection.MyEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function MyCollection.MyEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function MyCollection.MyEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachPattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable ' Explicit implementation won't match pattern. Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 3 2 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0022 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: call "Sub System.Console.WriteLine(Object)" IL_0022: ldloc.0 IL_0023: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0028: brtrue.s IL_000d IL_002a: leave.s IL_0040 } finally { IL_002c: ldloc.0 IL_002d: isinst "System.IDisposable" IL_0032: brfalse.s IL_003f IL_0034: ldloc.0 IL_0035: isinst "System.IDisposable" IL_003a: callvirt "Sub System.IDisposable.Dispose()" IL_003f: endfinally } IL_0040: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: leave.s IL_0032 } finally { IL_0024: ldloca.s V_0 IL_0026: constrained. "Enumerator" IL_002c: callvirt "Sub System.IDisposable.Dispose()" IL_0031: endfinally } IL_0032: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposeStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Dispose() End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Public Function GetEnumerator() As IEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: stloc.1 IL_000a: ldloca.s V_1 IL_000c: call "Function Enumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0011: stloc.0 IL_0012: br.s IL_0029 IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_001a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0024: call "Sub System.Console.WriteLine(Object)" IL_0029: ldloc.0 IL_002a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_002f: brtrue.s IL_0014 IL_0031: leave.s IL_0047 } finally { IL_0033: ldloc.0 IL_0034: isinst "System.IDisposable" IL_0039: brfalse.s IL_0046 IL_003b: ldloc.0 IL_003c: isinst "System.IDisposable" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Class Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 45 (0x2d) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: leave.s IL_002c } finally { IL_0022: ldloc.0 IL_0023: brfalse.s IL_002b IL_0025: ldloc.0 IL_0026: callvirt "Sub System.IDisposable.Dispose()" IL_002b: endfinally } IL_002c: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableAbstractClass() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable1() System.Console.WriteLine(x) Next For Each x In New Enumerable2() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable1 Public Function GetEnumerator() As AbstractEnumerator Return New DisposableEnumerator() End Function End Class Class Enumerable2 Public Function GetEnumerator() As AbstractEnumerator Return New NonDisposableEnumerator() End Function End Class MustInherit Class AbstractEnumerator Public MustOverride ReadOnly Property Current() As Integer Public MustOverride Function MoveNext() As Boolean End Class Class DisposableEnumerator Inherits AbstractEnumerator Implements System.IDisposable Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose System.Console.WriteLine("Done with DisposableEnumerator") End Sub End Class Class NonDisposableEnumerator Inherits AbstractEnumerator Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Decrement(x) &gt; -4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 -1 -2 -3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (AbstractEnumerator V_0, AbstractEnumerator V_1) IL_0000: newobj "Sub Enumerable1..ctor()" IL_0005: call "Function Enumerable1.GetEnumerator() As AbstractEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: newobj "Sub Enumerable2..ctor()" IL_0025: call "Function Enumerable2.GetEnumerator() As AbstractEnumerator" IL_002a: stloc.1 IL_002b: br.s IL_0038 IL_002d: ldloc.1 IL_002e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0033: call "Sub System.Console.WriteLine(Integer)" IL_0038: ldloc.1 IL_0039: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_003e: brtrue.s IL_002d IL_0040: ret } ]]>) End Sub <WorkItem(528679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528679")> <Fact> Public Sub TestForEachNested() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Class C Public Shared Sub Main() For Each x In New Enumerable() For Each y In New Enumerable() System.Console.WriteLine("({0}, {1})", x, y) Next Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3) ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 3 .locals init (Enumerator V_0, Integer V_1, //x Enumerator V_2, Integer V_3) //y IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0046 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: stloc.1 IL_0014: newobj "Sub Enumerable..ctor()" IL_0019: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001e: stloc.2 IL_001f: br.s IL_003e IL_0021: ldloc.2 IL_0022: callvirt "Function Enumerator.get_Current() As Integer" IL_0027: stloc.3 IL_0028: ldstr "({0}, {1})" IL_002d: ldloc.1 IL_002e: box "Integer" IL_0033: ldloc.3 IL_0034: box "Integer" IL_0039: call "Sub System.Console.WriteLine(String, Object, Object)" IL_003e: ldloc.2 IL_003f: callvirt "Function Enumerator.MoveNext() As Boolean" IL_0044: brtrue.s IL_0021 IL_0046: ldloc.0 IL_0047: callvirt "Function Enumerator.MoveNext() As Boolean" IL_004c: brtrue.s IL_000d IL_004e: ret } ]]>) End Sub <WorkItem(542075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542075")> <Fact> Public Sub TestGetEnumeratorWithParams() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Imports System Class C public Shared Sub Main() For Each x In New B() Console.WriteLine(x.ToLower()) Next End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return nothing End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ a b c ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 1 .locals init (System.Collections.Generic.List(Of String).Enumerator V_0) .try { IL_0000: newobj "Sub B..ctor()" IL_0005: call "Function A.GetEnumerator() As System.Collections.Generic.List(Of String).Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_001e IL_000d: ldloca.s V_0 IL_000f: call "Function System.Collections.Generic.List(Of String).Enumerator.get_Current() As String" IL_0014: callvirt "Function String.ToLower() As String" IL_0019: call "Sub System.Console.WriteLine(String)" IL_001e: ldloca.s V_0 IL_0020: call "Function System.Collections.Generic.List(Of String).Enumerator.MoveNext() As Boolean" IL_0025: brtrue.s IL_000d IL_0027: leave.s IL_0037 } finally { IL_0029: ldloca.s V_0 IL_002b: constrained. "System.Collections.Generic.List(Of String).Enumerator" IL_0031: callvirt "Sub System.IDisposable.Dispose()" IL_0036: endfinally } IL_0037: ret } ]]>) End Sub <Fact> Public Sub TestMoveNextWithNonBoolDeclaredReturnType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class Program Public Shared Sub Main() Goo(sub(x) For Each y In x Next end sub ) End Sub Public Shared Sub Goo(a As System.Action(Of IEnumerable)) System.Console.WriteLine(1) End Sub End Class Class A Public Function GetEnumerator() As E(Of Boolean) Return New E(Of Boolean)() End Function End Class Class E(Of T) Public Function MoveNext() As T Return Nothing End Function Public Property Current() As Integer Get Return m_Current End Get Set(value As Integer) m_Current = Value End Set End Property Private m_Current As Integer End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <Fact()> Public Sub TestNonConstantNullInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Program Public Shared Sub Main() Try Const s As String = Nothing For Each y In TryCast(s, String) Next Catch generatedExceptionName As System.NullReferenceException System.Console.WriteLine(1) End Try End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachStructEnumerable() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachMutableStructEnumerablePattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Public i As Integer Public Function GetEnumerator() As Enumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 1 .locals init (Enumerable V_0, //e Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" IL_0013: ldloca.s V_0 IL_0015: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001a: stloc.1 IL_001b: br.s IL_0025 IL_001d: ldloca.s V_1 IL_001f: call "Function Enumerator.get_Current() As Integer" IL_0024: pop IL_0025: ldloca.s V_1 IL_0027: call "Function Enumerator.MoveNext() As Boolean" IL_002c: brtrue.s IL_001d IL_002e: ldloc.0 IL_002f: ldfld "Enumerable.i As Integer" IL_0034: call "Sub System.Console.WriteLine(Integer)" IL_0039: ret } ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachMutableStructEnumerableInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Implements IEnumerable Public i As Integer Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Implements IEnumerator Private x As Integer Public ReadOnly Property Current() As Object Implements IEnumerator.Current Get Return x End Get End Property Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Reset() Implements IEnumerator.Reset x = 0 End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 92 (0x5c) .maxstack 1 .locals init (Enumerable V_0, //e System.Collections.IEnumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" .try { IL_0013: ldloc.0 IL_0014: box "Enumerable" IL_0019: castclass "System.Collections.IEnumerable" IL_001e: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0023: stloc.1 IL_0024: br.s IL_0032 IL_0026: ldloc.1 IL_0027: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0031: pop IL_0032: ldloc.1 IL_0033: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0038: brtrue.s IL_0026 IL_003a: leave.s IL_0050 } finally { IL_003c: ldloc.1 IL_003d: isinst "System.IDisposable" IL_0042: brfalse.s IL_004f IL_0044: ldloc.1 IL_0045: isinst "System.IDisposable" IL_004a: callvirt "Sub System.IDisposable.Dispose()" IL_004f: endfinally } IL_0050: ldloc.0 IL_0051: ldfld "Enumerable.i As Integer" IL_0056: call "Sub System.Console.WriteLine(Integer)" IL_005b: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeCanBeReferenceType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 80 (0x50) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_004f } finally { IL_0039: ldloc.1 IL_003a: box "S" IL_003f: brfalse.s IL_004e IL_0041: ldloca.s V_1 IL_0043: constrained. "S" IL_0049: callvirt "Sub System.IDisposable.Dispose()" IL_004e: endfinally } IL_004f: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeHasValueConstraint() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable, Structure}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable, Structure}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_0047 } finally { IL_0039: ldloca.s V_1 IL_003b: constrained. "S" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub NoObjectCopyForGetCurrent() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Collections.Generic Class C2 Public Structure S1 Public Field as Integer Public Sub New(x as integer) Field = x End Sub End Structure Public Shared Sub Main() dim coll = New List(Of S1) coll.add(new S1(23)) coll.add(new S1(42)) DoStuff(coll) End Sub Public Shared Sub DoStuff(coll as System.Collections.IEnumerable) for each x as Object in coll Console.WriteLine(Directcast(x,S1).Field) next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 23 42 ]]>).VerifyIL("C2.DoStuff", <![CDATA[ { // Code size 66 (0x42) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldarg.0 IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0023 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: unbox "C2.S1" IL_0019: ldfld "C2.S1.Field As Integer" IL_001e: call "Sub System.Console.WriteLine(Integer)" IL_0023: ldloc.0 IL_0024: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0029: brtrue.s IL_0009 IL_002b: leave.s IL_0041 } finally { IL_002d: ldloc.0 IL_002e: isinst "System.IDisposable" IL_0033: brfalse.s IL_0040 IL_0035: ldloc.0 IL_0036: isinst "System.IDisposable" IL_003b: callvirt "Sub System.IDisposable.Dispose()" IL_0040: endfinally } IL_0041: ret } ]]>) ' there should be a check for null before calling Dispose End Sub <WorkItem(542185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542185")> <Fact> Public Sub CustomDefinedType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim x = New B() End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return New List(Of Integer).Enumerator() End Function End Class </file> </compilation>) End Sub <Fact> Public Sub ForEachQuery() CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Linq Module Program Sub Main(args As String()) Dim ii As Integer() = New Integer() {1, 2, 3} For Each iii In ii.Where(Function(jj) jj >= ii(0)).Select(Function(jj) jj) System.Console.Write(iii) Next End Sub End Module </file> </compilation>, references:={LinqAssemblyRef}, expectedOutput:="123") End Sub <WorkItem(544311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544311")> <Fact()> Public Sub ForEachWithMultipleDimArray() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Program Sub Main() Dim k(,) = {{1}, {1}} For Each [Custom] In k Console.Write(VerifyStaticType([Custom], GetType(Integer))) Console.Write(VerifyStaticType([Custom], GetType(Object))) Exit For Next End Sub Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean Return GetType(T) Is y End Function End Module </file> </compilation>, expectedOutput:="TrueFalse") End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() Dim actions = New List(Of Action)() Dim values = New List(Of Integer) From {1, 2, 3} ' test lifting of control variable in loop body when collection is array For Each i As Integer In values actions.Add(Sub() Console.WriteLine(i)) Next For Each a In actions a() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 154 (0x9a) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //actions System.Collections.Generic.List(Of Integer) V_1, //values System.Collections.Generic.List(Of Integer).Enumerator V_2, m1._Closure$__0-0 V_3, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_4) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0012: dup IL_0013: ldc.i4.2 IL_0014: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0020: stloc.1 .try { IL_0021: ldloc.1 IL_0022: callvirt "Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator" IL_0027: stloc.2 IL_0028: br.s IL_0050 IL_002a: ldloc.3 IL_002b: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0030: stloc.3 IL_0031: ldloc.3 IL_0032: ldloca.s V_2 IL_0034: call "Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer" IL_0039: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_003e: ldloc.0 IL_003f: ldloc.3 IL_0040: ldftn "Sub m1._Closure$__0-0._Lambda$__0()" IL_0046: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004b: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0050: ldloca.s V_2 IL_0052: call "Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean" IL_0057: brtrue.s IL_002a IL_0059: leave.s IL_0069 } finally { IL_005b: ldloca.s V_2 IL_005d: constrained. "System.Collections.Generic.List(Of Integer).Enumerator" IL_0063: callvirt "Sub System.IDisposable.Dispose()" IL_0068: endfinally } IL_0069: nop .try { IL_006a: ldloc.0 IL_006b: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0070: stloc.s V_4 IL_0072: br.s IL_0080 IL_0074: ldloca.s V_4 IL_0076: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_007b: callvirt "Sub System.Action.Invoke()" IL_0080: ldloca.s V_4 IL_0082: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_0087: brtrue.s IL_0074 IL_0089: leave.s IL_0099 } finally { IL_008b: ldloca.s V_4 IL_008d: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_0093: callvirt "Sub System.IDisposable.Dispose()" IL_0098: endfinally } IL_0099: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_2() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. For Each i As Integer In (function() {i + 1, i + 2, i + 3})() x(i) = Sub() console.writeline(i.toString) Next for i = 1 to 3 x(i).invoke() next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 93 (0x5d) .maxstack 4 .locals init (System.Action() V_0, //x Integer() V_1, Integer V_2, m1._Closure$__0-1 V_3, //$VB$Closure_0 Integer V_4) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: newobj "Sub m1._Closure$__0-0..ctor()" IL_000d: callvirt "Function m1._Closure$__0-0._Lambda$__0() As Integer()" IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_003f IL_0017: ldloc.3 IL_0018: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_001d: stloc.3 IL_001e: ldloc.3 IL_001f: ldloc.1 IL_0020: ldloc.2 IL_0021: ldelem.i4 IL_0022: stfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_0027: ldloc.0 IL_0028: ldloc.3 IL_0029: ldfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_002e: ldloc.3 IL_002f: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0035: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_003a: stelem.ref IL_003b: ldloc.2 IL_003c: ldc.i4.1 IL_003d: add.ovf IL_003e: stloc.2 IL_003f: ldloc.2 IL_0040: ldloc.1 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_0017 IL_0045: ldc.i4.1 IL_0046: stloc.s V_4 IL_0048: ldloc.0 IL_0049: ldloc.s V_4 IL_004b: ldelem.ref IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ldloc.s V_4 IL_0053: ldc.i4.1 IL_0054: add.ovf IL_0055: stloc.s V_4 IL_0057: ldloc.s V_4 IL_0059: ldc.i4.3 IL_005a: ble.s IL_0048 IL_005c: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_3() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action for j = 0 to 2 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. for each i as integer in (function(a) goo())(i) x(i) = sub() console.write(i.toString &amp; " ") next for i = 1 to 3 x(i).invoke() next Console.Writeline() next j End Sub function goo() as IEnumerable(of Integer) return new list(of integer) from {1, 2, 3} end function End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[1 2 3 1 2 3 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 170 (0xaa) .maxstack 4 .locals init (System.Action() V_0, //x Integer V_1, //j Integer V_2, System.Collections.Generic.IEnumerator(Of Integer) V_3, m1._Closure$__0-0 V_4, //$VB$Closure_0 Integer V_5) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: nop .try { IL_000b: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0010: brfalse.s IL_0019 IL_0012: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0017: br.s IL_002f IL_0019: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_001e: ldftn "Function m1._Closure$__._Lambda$__0-0(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_0024: newobj "Sub VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_0029: dup IL_002a: stsfld "m1._Closure$__.$I0-0 As <generated method>" IL_002f: ldloc.2 IL_0030: box "Integer" IL_0035: callvirt "Function VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer)).Invoke(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_003f: stloc.3 IL_0040: br.s IL_006e IL_0042: ldloc.s V_4 IL_0044: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0049: stloc.s V_4 IL_004b: ldloc.s V_4 IL_004d: ldloc.3 IL_004e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0053: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0058: ldloc.0 IL_0059: ldloc.s V_4 IL_005b: ldfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0060: ldloc.s V_4 IL_0062: ldftn "Sub m1._Closure$__0-0._Lambda$__1()" IL_0068: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_006d: stelem.ref IL_006e: ldloc.3 IL_006f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0074: brtrue.s IL_0042 IL_0076: leave.s IL_0082 } finally { IL_0078: ldloc.3 IL_0079: brfalse.s IL_0081 IL_007b: ldloc.3 IL_007c: callvirt "Sub System.IDisposable.Dispose()" IL_0081: endfinally } IL_0082: ldc.i4.1 IL_0083: stloc.s V_5 IL_0085: ldloc.0 IL_0086: ldloc.s V_5 IL_0088: ldelem.ref IL_0089: callvirt "Sub System.Action.Invoke()" IL_008e: ldloc.s V_5 IL_0090: ldc.i4.1 IL_0091: add.ovf IL_0092: stloc.s V_5 IL_0094: ldloc.s V_5 IL_0096: ldc.i4.3 IL_0097: ble.s IL_0085 IL_0099: call "Sub System.Console.WriteLine()" IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: add.ovf IL_00a1: stloc.1 IL_00a2: ldloc.1 IL_00a3: ldc.i4.2 IL_00a4: ble IL_000a IL_00a9: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_4() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim lambdas As New List(Of Action) 'Expected 0,1,2, 0,1,2, 0,1,2 lambdas.clear For y = 1 To 3 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. The for each itself is nested in a for loop. For Each x as integer In (function(a) x = x + 1 return {a, x, 2} end function)(x) lambdas.add( Sub() Console.Write(x.ToString + "," ) ) Next lambdas.add(sub() Console.WriteLine()) Next For Each lambda In lambdas lambda() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 0,1,2, 0,1,2, 0,1,2, ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 195 (0xc3) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //lambdas Integer V_1, //y Object() V_2, Integer V_3, m1._Closure$__0-1 V_4, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_5) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt "Sub System.Collections.Generic.List(Of System.Action).Clear()" IL_000c: ldc.i4.1 IL_000d: stloc.1 IL_000e: newobj "Sub m1._Closure$__0-0..ctor()" IL_0013: dup IL_0014: ldfld "m1._Closure$__0-0.$VB$NonLocal_2 As Integer" IL_0019: box "Integer" IL_001e: callvirt "Function m1._Closure$__0-0._Lambda$__0(Object) As Object()" IL_0023: stloc.2 IL_0024: ldc.i4.0 IL_0025: stloc.3 IL_0026: br.s IL_0057 IL_0028: ldloc.s V_4 IL_002a: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_002f: stloc.s V_4 IL_0031: ldloc.s V_4 IL_0033: ldloc.2 IL_0034: ldloc.3 IL_0035: ldelem.ref IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_003b: stfld "m1._Closure$__0-1.$VB$Local_x As Integer" IL_0040: ldloc.0 IL_0041: ldloc.s V_4 IL_0043: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0049: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004e: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0053: ldloc.3 IL_0054: ldc.i4.1 IL_0055: add.ovf IL_0056: stloc.3 IL_0057: ldloc.3 IL_0058: ldloc.2 IL_0059: ldlen IL_005a: conv.i4 IL_005b: blt.s IL_0028 IL_005d: ldloc.0 IL_005e: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_0063: brfalse.s IL_006c IL_0065: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_006a: br.s IL_0082 IL_006c: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_0071: ldftn "Sub m1._Closure$__._Lambda$__0-2()" IL_0077: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_007c: dup IL_007d: stsfld "m1._Closure$__.$I0-2 As System.Action" IL_0082: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0087: ldloc.1 IL_0088: ldc.i4.1 IL_0089: add.ovf IL_008a: stloc.1 IL_008b: ldloc.1 IL_008c: ldc.i4.3 IL_008d: ble IL_000e IL_0092: nop .try { IL_0093: ldloc.0 IL_0094: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0099: stloc.s V_5 IL_009b: br.s IL_00a9 IL_009d: ldloca.s V_5 IL_009f: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_00a4: callvirt "Sub System.Action.Invoke()" IL_00a9: ldloca.s V_5 IL_00ab: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_00b0: brtrue.s IL_009d IL_00b2: leave.s IL_00c2 } finally { IL_00b4: ldloca.s V_5 IL_00b6: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_00bc: callvirt "Sub System.IDisposable.Dispose()" IL_00c1: endfinally } IL_00c2: ret } ]]>) End Sub <Fact> Public Sub ForEachLateBinding() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off imports system Class C Shared Sub Main() Dim o As Object = {1, 2, 3} For Each x In o console.writeline(x) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 84 (0x54) .maxstack 3 .locals init (Object V_0, //o System.Collections.IEnumerator V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 .try { IL_0012: ldloc.0 IL_0013: castclass "System.Collections.IEnumerable" IL_0018: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_001d: stloc.1 IL_001e: br.s IL_0035 IL_0020: ldloc.1 IL_0021: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: call "Sub System.Console.WriteLine(Object)" IL_0035: ldloc.1 IL_0036: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_003b: brtrue.s IL_0020 IL_003d: leave.s IL_0053 } finally { IL_003f: ldloc.1 IL_0040: isinst "System.IDisposable" IL_0045: brfalse.s IL_0052 IL_0047: ldloc.1 IL_0048: isinst "System.IDisposable" IL_004d: callvirt "Sub System.IDisposable.Dispose()" IL_0052: endfinally } IL_0053: ret } ]]>).Compilation 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 Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenForeach Inherits BasicTestBase ' The loop object must be an array or an object collection <Fact> Public Sub SimpleForeachTest() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Shared Sub Main() Dim arr As String() = New String(1) {} arr(0) = "one" arr(1) = "two" For Each s As String In arr Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ one two ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 46 (0x2e) .maxstack 4 .locals init (String() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "String" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldstr "one" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldstr "two" IL_0015: stelem.ref IL_0016: stloc.0 IL_0017: ldc.i4.0 IL_0018: stloc.1 IL_0019: br.s IL_0027 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldelem.ref IL_001e: call "Sub System.Console.WriteLine(String)" IL_0023: ldloc.1 IL_0024: ldc.i4.1 IL_0025: add.ovf IL_0026: stloc.1 IL_0027: ldloc.1 IL_0028: ldloc.0 IL_0029: ldlen IL_002a: conv.i4 IL_002b: blt.s IL_001b IL_002d: ret } ]]>).Compilation End Sub ' Type is not required in a foreach statement <Fact> Public Sub TypeIsNotRequiredTest() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Class C Shared Sub Main() Dim myarray As Integer() = New Integer(2) {1, 2, 3} For Each item In myarray Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE")).VerifyIL("C.Main", <![CDATA[ { // Code size 37 (0x25) .maxstack 3 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_001e IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i4 IL_0019: pop IL_001a: ldloc.1 IL_001b: ldc.i4.1 IL_001c: add.ovf IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: ldloc.0 IL_0020: ldlen IL_0021: conv.i4 IL_0022: blt.s IL_0016 IL_0024: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {45, 3} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 45 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 42 (0x2a) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.2 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 45 IL_000a: conv.i8 IL_000b: stelem.i8 IL_000c: dup IL_000d: ldc.i4.1 IL_000e: ldc.i4.3 IL_000f: conv.i8 IL_0010: stelem.i8 IL_0011: stloc.0 IL_0012: ldc.i4.0 IL_0013: stloc.1 IL_0014: br.s IL_0023 IL_0016: ldloc.0 IL_0017: ldloc.1 IL_0018: ldelem.i8 IL_0019: conv.ovf.i4 IL_001a: call "Sub System.Console.WriteLine(Integer)" IL_001f: ldloc.1 IL_0020: ldc.i4.1 IL_0021: add.ovf IL_0022: stloc.1 IL_0023: ldloc.1 IL_0024: ldloc.0 IL_0025: ldlen IL_0026: conv.i4 IL_0027: blt.s IL_0016 IL_0029: ret } ]]>) End Sub ' Narrowing conversions from the elements in group to element are evaluated and performed at run time <Fact> Public Sub NarrowConversions_2() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Sub Main() For Each number As Integer In New Long() {9876543210} Console.WriteLine(number) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 43 (0x2b) .maxstack 4 .locals init (Long() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Long" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i8 0x24cb016ea IL_0011: stelem.i8 IL_0012: stloc.0 IL_0013: ldc.i4.0 IL_0014: stloc.1 IL_0015: br.s IL_0024 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldelem.i8 IL_001a: conv.ovf.i4 IL_001b: call "Sub System.Console.WriteLine(Integer)" IL_0020: ldloc.1 IL_0021: ldc.i4.1 IL_0022: add.ovf IL_0023: stloc.1 IL_0024: ldloc.1 IL_0025: ldloc.0 IL_0026: ldlen IL_0027: conv.i4 IL_0028: blt.s IL_0017 IL_002a: ret } ]]>) End Sub ' Multiline <Fact> Public Sub Multiline() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Shared Public Sub Main() Dim a() As Integer = New Integer() {7} For Each x As Integer In a : System.Console.WriteLine(x) : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 34 (0x22) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_001b IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: call "Sub System.Console.WriteLine(Integer)" IL_0017: ldloc.1 IL_0018: ldc.i4.1 IL_0019: add.ovf IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: ldloc.0 IL_001d: ldlen IL_001e: conv.i4 IL_001f: blt.s IL_000f IL_0021: ret } ]]>) End Sub ' Line continuations <Fact> Public Sub LineContinuations() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Class C Public Shared Sub Main() Dim a() As Integer = New Integer() {7} For _ Each _ x _ As _ Integer _ In _ a _ _ : Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 30 (0x1e) .maxstack 4 .locals init (Integer() V_0, Integer V_1) IL_0000: ldc.i4.1 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.7 IL_0009: stelem.i4 IL_000a: stloc.0 IL_000b: ldc.i4.0 IL_000c: stloc.1 IL_000d: br.s IL_0017 IL_000f: ldloc.0 IL_0010: ldloc.1 IL_0011: ldelem.i4 IL_0012: pop IL_0013: ldloc.1 IL_0014: ldc.i4.1 IL_0015: add.ovf IL_0016: stloc.1 IL_0017: ldloc.1 IL_0018: ldloc.0 IL_0019: ldlen IL_001a: conv.i4 IL_001b: blt.s IL_000f IL_001d: ret } ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub IterationVarInConditionalExpression() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each x As S In If(True, x, 1) Next End Sub End Class Public Structure S End Structure </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 77 (0x4d) .maxstack 2 .locals init (S V_0, System.Collections.IEnumerator V_1, S V_2) .try { IL_0000: ldloc.0 IL_0001: box "S" IL_0006: castclass "System.Collections.IEnumerable" IL_000b: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0010: stloc.1 IL_0011: br.s IL_002e IL_0013: ldloc.1 IL_0014: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0019: dup IL_001a: brtrue.s IL_0028 IL_001c: pop IL_001d: ldloca.s V_2 IL_001f: initobj "S" IL_0025: ldloc.2 IL_0026: br.s IL_002d IL_0028: unbox.any "S" IL_002d: pop IL_002e: ldloc.1 IL_002f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0034: brtrue.s IL_0013 IL_0036: leave.s IL_004c } finally { IL_0038: ldloc.1 IL_0039: isinst "System.IDisposable" IL_003e: brfalse.s IL_004b IL_0040: ldloc.1 IL_0041: isinst "System.IDisposable" IL_0046: callvirt "Sub System.IDisposable.Dispose()" IL_004b: endfinally } IL_004c: ret } ]]>) End Sub ' Use the declared variable to initialize collection <Fact> Public Sub IterationVarInCollectionExpression_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() For Each x As Integer In New Integer() {x + 5, x + 6, x + 7} System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 5 6 7 ]]>) End Sub <Fact(), WorkItem(9151, "DevDiv_Projects/Roslyn"), WorkItem(546096, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546096")> Public Sub TraversingNothing() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Class C Shared Sub Main() For Each item In Nothing Next End Sub End Class </file> </compilation>).VerifyIL("C.Main", <![CDATA[ { // Code size 52 (0x34) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldnull IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0015 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: pop IL_0015: ldloc.0 IL_0016: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001b: brtrue.s IL_0009 IL_001d: leave.s IL_0033 } finally { IL_001f: ldloc.0 IL_0020: isinst "System.IDisposable" IL_0025: brfalse.s IL_0032 IL_0027: ldloc.0 IL_0028: isinst "System.IDisposable" IL_002d: callvirt "Sub System.IDisposable.Dispose()" IL_0032: endfinally } IL_0033: ret } ]]>) End Sub ' Nested ForEach can use a var declared in the outer ForEach <Fact> Public Sub NestedForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Shared Sub Main() Dim c(3)() As Integer For Each x As Integer() In c ReDim x(3) For i As Integer = 0 To 3 x(i) = i Next For Each y As Integer In x System .Console .WriteLine (y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3 ]]>) End Sub ' Inner foreach loop referencing the outer foreach loop iteration variable <Fact> Public Sub NestedForeach_1() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C X Y Z ]]>) End Sub ' Foreach value can't be modified in a loop <Fact> Public Sub ModifyIterationValueInLoop() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Collections Class C Shared Sub Main() Dim list As New ArrayList() list.Add("One") list.Add("Two") For Each s As String In list s = "a" Next For Each s As String In list System.Console.WriteLine(s) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ One Two ]]>) End Sub ' Pass fields as a ref argument for 'foreach iteration variable' <Fact()> Public Sub PassFieldsAsRefArgument() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim sa As S() = New S(2) {New S With {.I = 1}, New S With {.I = 2}, New S With {.I = 3}} For Each s As S In sa f(s.i) Next For Each s As S In sa System.Console.WriteLine(s.i) Next End Sub Private Shared Sub f(ByRef iref As Integer) iref = 1 End Sub End Class Structure S Public I As integer End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>) End Sub ' With multidimensional arrays, you can use one loop to iterate through the elements <Fact> Public Sub TraversingMultidimensionalArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D(,) As Integer = New Integer (2,1) {} numbers2D(0,0) = 9 numbers2D(0,1) = 99 numbers2D(1,0) = 3 numbers2D(1,1) = 33 numbers2D(2,0) = 5 numbers2D(2,1) = 55 For Each i As Integer In numbers2D System.Console.WriteLine(i) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 9 99 3 33 5 55 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 98 (0x62) .maxstack 5 .locals init (System.Collections.IEnumerator V_0) IL_0000: ldc.i4.3 IL_0001: ldc.i4.2 IL_0002: newobj "Integer(*,*)..ctor" IL_0007: dup IL_0008: ldc.i4.0 IL_0009: ldc.i4.0 IL_000a: ldc.i4.s 9 IL_000c: call "Integer(*,*).Set" IL_0011: dup IL_0012: ldc.i4.0 IL_0013: ldc.i4.1 IL_0014: ldc.i4.s 99 IL_0016: call "Integer(*,*).Set" IL_001b: dup IL_001c: ldc.i4.1 IL_001d: ldc.i4.0 IL_001e: ldc.i4.3 IL_001f: call "Integer(*,*).Set" IL_0024: dup IL_0025: ldc.i4.1 IL_0026: ldc.i4.1 IL_0027: ldc.i4.s 33 IL_0029: call "Integer(*,*).Set" IL_002e: dup IL_002f: ldc.i4.2 IL_0030: ldc.i4.0 IL_0031: ldc.i4.5 IL_0032: call "Integer(*,*).Set" IL_0037: dup IL_0038: ldc.i4.2 IL_0039: ldc.i4.1 IL_003a: ldc.i4.s 55 IL_003c: call "Integer(*,*).Set" IL_0041: callvirt "Function System.Array.GetEnumerator() As System.Collections.IEnumerator" IL_0046: stloc.0 IL_0047: br.s IL_0059 IL_0049: ldloc.0 IL_004a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0054: call "Sub System.Console.WriteLine(Integer)" IL_0059: ldloc.0 IL_005a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_005f: brtrue.s IL_0049 IL_0061: ret } ]]>) End Sub ' Traversing jagged arrays <Fact> Public Sub TraversingJaggedArray() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim numbers2D As Integer()() = New Integer()() {New Integer() {1, 2}, New Integer() {4, 5, 6}} For Each x As Integer() In numbers2D For Each y As Integer In x System.Console.WriteLine(y) Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 4 5 6 ]]>) End Sub ' Optimization to foreach (char c in String) by treating String as a char array <Fact()> Public Sub TraversingString() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim str As String = "ABC" For Each x In str System.Console.WriteLine(x) Next For Each var In "goo" If Not var.[GetType]().Equals(GetType(Char)) Then System.Console.WriteLine("False") End If Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A B C ]]>) End Sub ' Traversing items in Dictionary <Fact> Public Sub TraversingDictionary() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim s As New Dictionary(Of Integer, Integer)() s.Add(1, 2) s.Add(2, 3) s.Add(3, 4) For Each pair In s System .Console .WriteLine (pair.Key) Next For Each pair As KeyValuePair(Of Integer, Integer) In s System .Console .WriteLine (pair.Value ) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 2 3 4 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 141 (0x8d) .maxstack 3 .locals init (System.Collections.Generic.Dictionary(Of Integer, Integer) V_0, //s System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_1, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_2, //pair System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator V_3, System.Collections.Generic.KeyValuePair(Of Integer, Integer) V_4) //pair IL_0000: newobj "Sub System.Collections.Generic.Dictionary(Of Integer, Integer)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldc.i4.1 IL_0008: ldc.i4.2 IL_0009: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_000e: ldloc.0 IL_000f: ldc.i4.2 IL_0010: ldc.i4.3 IL_0011: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" IL_0016: ldloc.0 IL_0017: ldc.i4.3 IL_0018: ldc.i4.4 IL_0019: callvirt "Sub System.Collections.Generic.Dictionary(Of Integer, Integer).Add(Integer, Integer)" .try { IL_001e: ldloc.0 IL_001f: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0024: stloc.1 IL_0025: br.s IL_003b IL_0027: ldloca.s V_1 IL_0029: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_002e: stloc.2 IL_002f: ldloca.s V_2 IL_0031: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Key() As Integer" IL_0036: call "Sub System.Console.WriteLine(Integer)" IL_003b: ldloca.s V_1 IL_003d: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_0042: brtrue.s IL_0027 IL_0044: leave.s IL_0054 } finally { IL_0046: ldloca.s V_1 IL_0048: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_004e: callvirt "Sub System.IDisposable.Dispose()" IL_0053: endfinally } IL_0054: nop .try { IL_0055: ldloc.0 IL_0056: callvirt "Function System.Collections.Generic.Dictionary(Of Integer, Integer).GetEnumerator() As System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_005b: stloc.3 IL_005c: br.s IL_0073 IL_005e: ldloca.s V_3 IL_0060: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.get_Current() As System.Collections.Generic.KeyValuePair(Of Integer, Integer)" IL_0065: stloc.s V_4 IL_0067: ldloca.s V_4 IL_0069: call "Function System.Collections.Generic.KeyValuePair(Of Integer, Integer).get_Value() As Integer" IL_006e: call "Sub System.Console.WriteLine(Integer)" IL_0073: ldloca.s V_3 IL_0075: call "Function System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator.MoveNext() As Boolean" IL_007a: brtrue.s IL_005e IL_007c: leave.s IL_008c } finally { IL_007e: ldloca.s V_3 IL_0080: constrained. "System.Collections.Generic.Dictionary(Of Integer, Integer).Enumerator" IL_0086: callvirt "Sub System.IDisposable.Dispose()" IL_008b: endfinally } IL_008c: ret } ]]>) End Sub ' Breaking from nested Loops <Fact> Public Sub BreakFromForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Exit For Else System.Console.WriteLine(y) End If Next Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A X Y Z ]]>) End Sub ' Continuing for nested Loops <Fact> Public Sub ContinueInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Class C Public Shared Sub Main() Dim S As String() = New String() {"ABC", "XYZ"} For Each x As String In S For Each y As Char In x If y = "B"c Then Continue For End If System.Console.WriteLine(y) Next y, x End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ A C X Y Z ]]>) End Sub ' Query expression works in foreach <Fact()> Public Sub QueryExpressionInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off Option Infer On Imports System Imports System.Collections Imports System.Linq Class C Public Shared Sub Main() For Each x In From w In New Integer() {1, 2, 3} Select z = w.ToString() System.Console.WriteLine(x.ToLower()) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), references:={LinqAssemblyRef}, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 103 (0x67) .maxstack 3 .locals init (System.Collections.Generic.IEnumerator(Of String) V_0) .try { IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0016: brfalse.s IL_001f IL_0018: ldsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_001d: br.s IL_0035 IL_001f: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0024: ldftn "Function C._Closure$__._Lambda$__1-0(Integer) As String" IL_002a: newobj "Sub System.Func(Of Integer, String)..ctor(Object, System.IntPtr)" IL_002f: dup IL_0030: stsfld "C._Closure$__.$I1-0 As System.Func(Of Integer, String)" IL_0035: call "Function System.Linq.Enumerable.Select(Of Integer, String)(System.Collections.Generic.IEnumerable(Of Integer), System.Func(Of Integer, String)) As System.Collections.Generic.IEnumerable(Of String)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of String).GetEnumerator() As System.Collections.Generic.IEnumerator(Of String)" IL_003f: stloc.0 IL_0040: br.s IL_0052 IL_0042: ldloc.0 IL_0043: callvirt "Function System.Collections.Generic.IEnumerator(Of String).get_Current() As String" IL_0048: callvirt "Function String.ToLower() As String" IL_004d: call "Sub System.Console.WriteLine(String)" IL_0052: ldloc.0 IL_0053: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0058: brtrue.s IL_0042 IL_005a: leave.s IL_0066 } finally { IL_005c: ldloc.0 IL_005d: brfalse.s IL_0065 IL_005f: ldloc.0 IL_0060: callvirt "Sub System.IDisposable.Dispose()" IL_0065: endfinally } IL_0066: ret } ]]>) End Sub ' No confusion in a foreach statement when from is a value type <Fact> Public Sub ReDimFrom() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim src = New System.Collections.ArrayList() src.Add(new from(1)) For Each x As from In src System.Console.WriteLine(x.X) Next End Sub End Class Public Structure from Dim X As Integer Public Sub New(p as integer) x = p End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub ' Foreach on generic type that implements the Collection Pattern <Fact> Public Sub GenericTypeImplementsCollection() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() For Each j In New Gen(Of Integer)() Next End Sub End Class Public Class Gen(Of T As New) Public Function GetEnumerator() As IEnumerator(Of T) Return Nothing End Function End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C.Main", <![CDATA[ { // Code size 41 (0x29) .maxstack 1 .locals init (System.Collections.Generic.IEnumerator(Of Integer) V_0) .try { IL_0000: newobj "Sub Gen(Of Integer)..ctor()" IL_0005: call "Function Gen(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_000a: stloc.0 IL_000b: br.s IL_0014 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0013: pop IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_001a: brtrue.s IL_000d IL_001c: leave.s IL_0028 } finally { IL_001e: ldloc.0 IL_001f: brfalse.s IL_0027 IL_0021: ldloc.0 IL_0022: callvirt "Sub System.IDisposable.Dispose()" IL_0027: endfinally } IL_0028: ret } ]]>) End Sub ' Customer defined type of collection to support 'foreach' <Fact> Public Sub CustomerDefinedCollections() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Imports System Class C Public Shared Sub Main() Dim col As New MyCollection() For Each i As Integer In col Console.WriteLine(i) Next End Sub End Class Public Class MyCollection Private items As Integer() Public Sub New() items = New Integer(4) {1, 4, 3, 2, 5} End Sub Public Function GetEnumerator() As MyEnumerator Return New MyEnumerator(Me) End Function Public Class MyEnumerator Private nIndex As Integer Private collection As MyCollection Public Sub New(coll As MyCollection) collection = coll nIndex = nIndex - 1 End Sub Public Function MoveNext() As Boolean nIndex = nIndex + 1 Return (nIndex &lt; collection.items.GetLength(0)) End Function Public ReadOnly Property Current() As Integer Get Return (collection.items(nIndex)) End Get End Property End Class End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 4 3 2 5 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (MyCollection.MyEnumerator V_0) IL_0000: newobj "Sub MyCollection..ctor()" IL_0005: callvirt "Function MyCollection.GetEnumerator() As MyCollection.MyEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function MyCollection.MyEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function MyCollection.MyEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachPattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Implements System.Collections.IEnumerable ' Explicit implementation won't match pattern. Private Function System_Collections_IEnumerable_GetEnumerator() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator Dim list As New System.Collections.Generic.List(Of Integer)() list.Add(3) list.Add(2) list.Add(1) Return list.GetEnumerator() End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 3 2 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0022 IL_000d: ldloc.0 IL_000e: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0013: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: call "Sub System.Console.WriteLine(Object)" IL_0022: ldloc.0 IL_0023: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0028: brtrue.s IL_000d IL_002a: leave.s IL_0040 } finally { IL_002c: ldloc.0 IL_002d: isinst "System.IDisposable" IL_0032: brfalse.s IL_003f IL_0034: ldloc.0 IL_0035: isinst "System.IDisposable" IL_003a: callvirt "Sub System.IDisposable.Dispose()" IL_003f: endfinally } IL_0040: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: leave.s IL_0032 } finally { IL_0024: ldloca.s V_0 IL_0026: constrained. "Enumerator" IL_002c: callvirt "Sub System.IDisposable.Dispose()" IL_0031: endfinally } IL_0032: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposeStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Dispose() End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 35 (0x23) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0019 IL_000d: ldloca.s V_0 IL_000f: call "Function Enumerator.get_Current() As Integer" IL_0014: call "Sub System.Console.WriteLine(Integer)" IL_0019: ldloca.s V_0 IL_001b: call "Function Enumerator.MoveNext() As Boolean" IL_0020: brtrue.s IL_000d IL_0022: ret } ]]>) End Sub <Fact> Public Sub TestForEachExplicitlyGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachGetEnumeratorStruct() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Public Function GetEnumerator() As IEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: stloc.1 IL_000a: ldloca.s V_1 IL_000c: call "Function Enumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0011: stloc.0 IL_0012: br.s IL_0029 IL_0014: ldloc.0 IL_0015: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_001a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0024: call "Sub System.Console.WriteLine(Object)" IL_0029: ldloc.0 IL_002a: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_002f: brtrue.s IL_0014 IL_0031: leave.s IL_0047 } finally { IL_0033: ldloc.0 IL_0034: isinst "System.IDisposable" IL_0039: brfalse.s IL_0046 IL_003b: ldloc.0 IL_003c: isinst "System.IDisposable" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub TestForEachDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Implements System.IDisposable Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose End Sub End Class Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 45 (0x2d) .maxstack 1 .locals init (Enumerator V_0) .try { IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: leave.s IL_002c } finally { IL_0022: ldloc.0 IL_0023: brfalse.s IL_002b IL_0025: ldloc.0 IL_0026: callvirt "Sub System.IDisposable.Dispose()" IL_002b: endfinally } IL_002c: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableSealed() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class NotInheritable Class Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 33 (0x21) .maxstack 1 .locals init (Enumerator V_0) IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function Enumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: ret } ]]>) End Sub <Fact> Public Sub TestForEachNonDisposableAbstractClass() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() For Each x In New Enumerable1() System.Console.WriteLine(x) Next For Each x In New Enumerable2() System.Console.WriteLine(x) Next End Sub End Class Class Enumerable1 Public Function GetEnumerator() As AbstractEnumerator Return New DisposableEnumerator() End Function End Class Class Enumerable2 Public Function GetEnumerator() As AbstractEnumerator Return New NonDisposableEnumerator() End Function End Class MustInherit Class AbstractEnumerator Public MustOverride ReadOnly Property Current() As Integer Public MustOverride Function MoveNext() As Boolean End Class Class DisposableEnumerator Inherits AbstractEnumerator Implements System.IDisposable Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Private Sub System_IDisposable_Dispose() Implements System.IDisposable.Dispose System.Console.WriteLine("Done with DisposableEnumerator") End Sub End Class Class NonDisposableEnumerator Inherits AbstractEnumerator Private x As Integer Public Overrides ReadOnly Property Current() As Integer Get Return x End Get End Property Public Overrides Function MoveNext() As Boolean Return System.Threading.Interlocked.Decrement(x) &gt; -4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 -1 -2 -3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 65 (0x41) .maxstack 1 .locals init (AbstractEnumerator V_0, AbstractEnumerator V_1) IL_0000: newobj "Sub Enumerable1..ctor()" IL_0005: call "Function Enumerable1.GetEnumerator() As AbstractEnumerator" IL_000a: stloc.0 IL_000b: br.s IL_0018 IL_000d: ldloc.0 IL_000e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0013: call "Sub System.Console.WriteLine(Integer)" IL_0018: ldloc.0 IL_0019: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_001e: brtrue.s IL_000d IL_0020: newobj "Sub Enumerable2..ctor()" IL_0025: call "Function Enumerable2.GetEnumerator() As AbstractEnumerator" IL_002a: stloc.1 IL_002b: br.s IL_0038 IL_002d: ldloc.1 IL_002e: callvirt "Function AbstractEnumerator.get_Current() As Integer" IL_0033: call "Sub System.Console.WriteLine(Integer)" IL_0038: ldloc.1 IL_0039: callvirt "Function AbstractEnumerator.MoveNext() As Boolean" IL_003e: brtrue.s IL_002d IL_0040: ret } ]]>) End Sub <WorkItem(528679, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528679")> <Fact> Public Sub TestForEachNested() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer on Class C Public Shared Sub Main() For Each x In New Enumerable() For Each y In New Enumerable() System.Console.WriteLine("({0}, {1})", x, y) Next Next End Sub End Class Class Enumerable Public Function GetEnumerator() As Enumerator Return New Enumerator() End Function End Class Class Enumerator Private x As Integer = 0 Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ (1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3) ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 3 .locals init (Enumerator V_0, Integer V_1, //x Enumerator V_2, Integer V_3) //y IL_0000: newobj "Sub Enumerable..ctor()" IL_0005: call "Function Enumerable.GetEnumerator() As Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_0046 IL_000d: ldloc.0 IL_000e: callvirt "Function Enumerator.get_Current() As Integer" IL_0013: stloc.1 IL_0014: newobj "Sub Enumerable..ctor()" IL_0019: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001e: stloc.2 IL_001f: br.s IL_003e IL_0021: ldloc.2 IL_0022: callvirt "Function Enumerator.get_Current() As Integer" IL_0027: stloc.3 IL_0028: ldstr "({0}, {1})" IL_002d: ldloc.1 IL_002e: box "Integer" IL_0033: ldloc.3 IL_0034: box "Integer" IL_0039: call "Sub System.Console.WriteLine(String, Object, Object)" IL_003e: ldloc.2 IL_003f: callvirt "Function Enumerator.MoveNext() As Boolean" IL_0044: brtrue.s IL_0021 IL_0046: ldloc.0 IL_0047: callvirt "Function Enumerator.MoveNext() As Boolean" IL_004c: brtrue.s IL_000d IL_004e: ret } ]]>) End Sub <WorkItem(542075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542075")> <Fact> Public Sub TestGetEnumeratorWithParams() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Imports System Class C public Shared Sub Main() For Each x In New B() Console.WriteLine(x.ToLower()) Next End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return nothing End Function End Class </file> </compilation>, expectedOutput:=<![CDATA[ a b c ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 56 (0x38) .maxstack 1 .locals init (System.Collections.Generic.List(Of String).Enumerator V_0) .try { IL_0000: newobj "Sub B..ctor()" IL_0005: call "Function A.GetEnumerator() As System.Collections.Generic.List(Of String).Enumerator" IL_000a: stloc.0 IL_000b: br.s IL_001e IL_000d: ldloca.s V_0 IL_000f: call "Function System.Collections.Generic.List(Of String).Enumerator.get_Current() As String" IL_0014: callvirt "Function String.ToLower() As String" IL_0019: call "Sub System.Console.WriteLine(String)" IL_001e: ldloca.s V_0 IL_0020: call "Function System.Collections.Generic.List(Of String).Enumerator.MoveNext() As Boolean" IL_0025: brtrue.s IL_000d IL_0027: leave.s IL_0037 } finally { IL_0029: ldloca.s V_0 IL_002b: constrained. "System.Collections.Generic.List(Of String).Enumerator" IL_0031: callvirt "Sub System.IDisposable.Dispose()" IL_0036: endfinally } IL_0037: ret } ]]>) End Sub <Fact> Public Sub TestMoveNextWithNonBoolDeclaredReturnType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class Program Public Shared Sub Main() Goo(sub(x) For Each y In x Next end sub ) End Sub Public Shared Sub Goo(a As System.Action(Of IEnumerable)) System.Console.WriteLine(1) End Sub End Class Class A Public Function GetEnumerator() As E(Of Boolean) Return New E(Of Boolean)() End Function End Class Class E(Of T) Public Function MoveNext() As T Return Nothing End Function Public Property Current() As Integer Get Return m_Current End Get Set(value As Integer) m_Current = Value End Set End Property Private m_Current As Integer End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <Fact()> Public Sub TestNonConstantNullInForeach() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class Program Public Shared Sub Main() Try Const s As String = Nothing For Each y In TryCast(s, String) Next Catch generatedExceptionName As System.NullReferenceException System.Console.WriteLine(1) End Try End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 1 ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachStructEnumerable() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C public Shared Sub Main() For Each x In New Enumerable() System.Console.WriteLine(x) Next End Sub End Class Structure Enumerable Implements IEnumerable Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Return New Integer() {1, 2, 3}.GetEnumerator() End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 79 (0x4f) .maxstack 1 .locals init (System.Collections.IEnumerator V_0, Enumerable V_1) .try { IL_0000: ldloca.s V_1 IL_0002: initobj "Enumerable" IL_0008: ldloc.1 IL_0009: box "Enumerable" IL_000e: castclass "System.Collections.IEnumerable" IL_0013: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0018: stloc.0 IL_0019: br.s IL_0030 IL_001b: ldloc.0 IL_001c: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0021: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Sub System.Console.WriteLine(Object)" IL_0030: ldloc.0 IL_0031: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0036: brtrue.s IL_001b IL_0038: leave.s IL_004e } finally { IL_003a: ldloc.0 IL_003b: isinst "System.IDisposable" IL_0040: brfalse.s IL_004d IL_0042: ldloc.0 IL_0043: isinst "System.IDisposable" IL_0048: callvirt "Sub System.IDisposable.Dispose()" IL_004d: endfinally } IL_004e: ret } ]]>) End Sub <Fact> Public Sub TestForEachMutableStructEnumerablePattern() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Public i As Integer Public Function GetEnumerator() As Enumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Private x As Integer Public ReadOnly Property Current() As Integer Get Return x End Get End Property Public Function MoveNext() As Boolean Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 1 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 58 (0x3a) .maxstack 1 .locals init (Enumerable V_0, //e Enumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" IL_0013: ldloca.s V_0 IL_0015: call "Function Enumerable.GetEnumerator() As Enumerator" IL_001a: stloc.1 IL_001b: br.s IL_0025 IL_001d: ldloca.s V_1 IL_001f: call "Function Enumerator.get_Current() As Integer" IL_0024: pop IL_0025: ldloca.s V_1 IL_0027: call "Function Enumerator.MoveNext() As Boolean" IL_002c: brtrue.s IL_001d IL_002e: ldloc.0 IL_002f: ldfld "Enumerable.i As Integer" IL_0034: call "Sub System.Console.WriteLine(Integer)" IL_0039: ret } ]]>) End Sub <WorkItem(542079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542079")> <Fact> Public Sub TestForEachMutableStructEnumerableInterface() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections Class C Public Shared Sub Main() Dim e As New Enumerable() System.Console.WriteLine(e.i) For Each x In e Next System.Console.WriteLine(e.i) End Sub End Class Structure Enumerable Implements IEnumerable Public i As Integer Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator i = i + 1 Return New Enumerator() End Function End Structure Structure Enumerator Implements IEnumerator Private x As Integer Public ReadOnly Property Current() As Object Implements IEnumerator.Current Get Return x End Get End Property Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext Return System.Threading.Interlocked.Increment(x) &lt; 4 End Function Public Sub Reset() Implements IEnumerator.Reset x = 0 End Sub End Structure </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 92 (0x5c) .maxstack 1 .locals init (Enumerable V_0, //e System.Collections.IEnumerator V_1) IL_0000: ldloca.s V_0 IL_0002: initobj "Enumerable" IL_0008: ldloc.0 IL_0009: ldfld "Enumerable.i As Integer" IL_000e: call "Sub System.Console.WriteLine(Integer)" .try { IL_0013: ldloc.0 IL_0014: box "Enumerable" IL_0019: castclass "System.Collections.IEnumerable" IL_001e: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0023: stloc.1 IL_0024: br.s IL_0032 IL_0026: ldloc.1 IL_0027: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0031: pop IL_0032: ldloc.1 IL_0033: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0038: brtrue.s IL_0026 IL_003a: leave.s IL_0050 } finally { IL_003c: ldloc.1 IL_003d: isinst "System.IDisposable" IL_0042: brfalse.s IL_004f IL_0044: ldloc.1 IL_0045: isinst "System.IDisposable" IL_004a: callvirt "Sub System.IDisposable.Dispose()" IL_004f: endfinally } IL_0050: ldloc.0 IL_0051: ldfld "Enumerable.i As Integer" IL_0056: call "Sub System.Console.WriteLine(Integer)" IL_005b: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeCanBeReferenceType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 80 (0x50) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_004f } finally { IL_0039: ldloc.1 IL_003a: box "S" IL_003f: brfalse.s IL_004e IL_0041: ldloca.s V_1 IL_0043: constrained. "S" IL_0049: callvirt "Sub System.IDisposable.Dispose()" IL_004e: endfinally } IL_004f: ret } ]]>) End Sub <Fact()> Public Sub TypeParameterAsEnumeratorTypeHasValueConstraint() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Imports System.Collections Public Class Custom(Of S As {IEnumerator, IDisposable, Structure}) Public Function GetEnumerator() As S Return Nothing End Function End Class Class C1(Of S As {IEnumerator, IDisposable, Structure}) Public Sub DoStuff() Dim myCustomCollection As Custom(Of S) = nothing For Each element In myCustomCollection Console.WriteLine("goo") Next End Sub End Class Class C2 Public Shared Sub Main() End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe).VerifyIL("C1(Of S).DoStuff", <![CDATA[ { // Code size 72 (0x48) .maxstack 1 .locals init (Custom(Of S) V_0, //myCustomCollection S V_1) IL_0000: ldnull IL_0001: stloc.0 .try { IL_0002: ldloc.0 IL_0003: callvirt "Function Custom(Of S).GetEnumerator() As S" IL_0008: stloc.1 IL_0009: br.s IL_0028 IL_000b: ldloca.s V_1 IL_000d: constrained. "S" IL_0013: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0018: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_001d: pop IL_001e: ldstr "goo" IL_0023: call "Sub System.Console.WriteLine(String)" IL_0028: ldloca.s V_1 IL_002a: constrained. "S" IL_0030: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0035: brtrue.s IL_000b IL_0037: leave.s IL_0047 } finally { IL_0039: ldloca.s V_1 IL_003b: constrained. "S" IL_0041: callvirt "Sub System.IDisposable.Dispose()" IL_0046: endfinally } IL_0047: ret } ]]>) End Sub <Fact> Public Sub NoObjectCopyForGetCurrent() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System Imports System.Collections.Generic Class C2 Public Structure S1 Public Field as Integer Public Sub New(x as integer) Field = x End Sub End Structure Public Shared Sub Main() dim coll = New List(Of S1) coll.add(new S1(23)) coll.add(new S1(42)) DoStuff(coll) End Sub Public Shared Sub DoStuff(coll as System.Collections.IEnumerable) for each x as Object in coll Console.WriteLine(Directcast(x,S1).Field) next End Sub End Class </file> </compilation>, expectedOutput:=<![CDATA[ 23 42 ]]>).VerifyIL("C2.DoStuff", <![CDATA[ { // Code size 66 (0x42) .maxstack 1 .locals init (System.Collections.IEnumerator V_0) .try { IL_0000: ldarg.0 IL_0001: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_0006: stloc.0 IL_0007: br.s IL_0023 IL_0009: ldloc.0 IL_000a: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_000f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0014: unbox "C2.S1" IL_0019: ldfld "C2.S1.Field As Integer" IL_001e: call "Sub System.Console.WriteLine(Integer)" IL_0023: ldloc.0 IL_0024: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0029: brtrue.s IL_0009 IL_002b: leave.s IL_0041 } finally { IL_002d: ldloc.0 IL_002e: isinst "System.IDisposable" IL_0033: brfalse.s IL_0040 IL_0035: ldloc.0 IL_0036: isinst "System.IDisposable" IL_003b: callvirt "Sub System.IDisposable.Dispose()" IL_0040: endfinally } IL_0041: ret } ]]>) ' there should be a check for null before calling Dispose End Sub <WorkItem(542185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542185")> <Fact> Public Sub CustomDefinedType() Dim TEMP = CompileAndVerify( <compilation> <file name="a.vb"> Option Infer On Imports System.Collections.Generic Class C Public Shared Sub Main() Dim x = New B() End Sub End Class Class A Public Function GetEnumerator() As List(Of String).Enumerator Dim s = New List(Of String)() s.Add("A") s.Add("B") s.Add("C") Return s.GetEnumerator() End Function End Class Class B Inherits A Public Overloads Function GetEnumerator(ParamArray x As Integer()) As List(Of Integer).Enumerator Return New List(Of Integer).Enumerator() End Function End Class </file> </compilation>) End Sub <Fact> Public Sub ForEachQuery() CompileAndVerify( <compilation> <file name="a.vb"> Imports System.Linq Module Program Sub Main(args As String()) Dim ii As Integer() = New Integer() {1, 2, 3} For Each iii In ii.Where(Function(jj) jj >= ii(0)).Select(Function(jj) jj) System.Console.Write(iii) Next End Sub End Module </file> </compilation>, references:={LinqAssemblyRef}, expectedOutput:="123") End Sub <WorkItem(544311, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544311")> <Fact()> Public Sub ForEachWithMultipleDimArray() CompileAndVerify( <compilation> <file name="a.vb"> Option Strict On Imports System Module Program Sub Main() Dim k(,) = {{1}, {1}} For Each [Custom] In k Console.Write(VerifyStaticType([Custom], GetType(Integer))) Console.Write(VerifyStaticType([Custom], GetType(Object))) Exit For Next End Sub Function VerifyStaticType(Of T)(ByVal x As T, ByVal y As System.Type) As Boolean Return GetType(T) Is y End Function End Module </file> </compilation>, expectedOutput:="TrueFalse") End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() Dim actions = New List(Of Action)() Dim values = New List(Of Integer) From {1, 2, 3} ' test lifting of control variable in loop body when collection is array For Each i As Integer In values actions.Add(Sub() Console.WriteLine(i)) Next For Each a In actions a() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 154 (0x9a) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //actions System.Collections.Generic.List(Of Integer) V_1, //values System.Collections.Generic.List(Of Integer).Enumerator V_2, m1._Closure$__0-0 V_3, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_4) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: newobj "Sub System.Collections.Generic.List(Of Integer)..ctor()" IL_000b: dup IL_000c: ldc.i4.1 IL_000d: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0012: dup IL_0013: ldc.i4.2 IL_0014: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0019: dup IL_001a: ldc.i4.3 IL_001b: callvirt "Sub System.Collections.Generic.List(Of Integer).Add(Integer)" IL_0020: stloc.1 .try { IL_0021: ldloc.1 IL_0022: callvirt "Function System.Collections.Generic.List(Of Integer).GetEnumerator() As System.Collections.Generic.List(Of Integer).Enumerator" IL_0027: stloc.2 IL_0028: br.s IL_0050 IL_002a: ldloc.3 IL_002b: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0030: stloc.3 IL_0031: ldloc.3 IL_0032: ldloca.s V_2 IL_0034: call "Function System.Collections.Generic.List(Of Integer).Enumerator.get_Current() As Integer" IL_0039: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_003e: ldloc.0 IL_003f: ldloc.3 IL_0040: ldftn "Sub m1._Closure$__0-0._Lambda$__0()" IL_0046: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004b: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0050: ldloca.s V_2 IL_0052: call "Function System.Collections.Generic.List(Of Integer).Enumerator.MoveNext() As Boolean" IL_0057: brtrue.s IL_002a IL_0059: leave.s IL_0069 } finally { IL_005b: ldloca.s V_2 IL_005d: constrained. "System.Collections.Generic.List(Of Integer).Enumerator" IL_0063: callvirt "Sub System.IDisposable.Dispose()" IL_0068: endfinally } IL_0069: nop .try { IL_006a: ldloc.0 IL_006b: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0070: stloc.s V_4 IL_0072: br.s IL_0080 IL_0074: ldloca.s V_4 IL_0076: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_007b: callvirt "Sub System.Action.Invoke()" IL_0080: ldloca.s V_4 IL_0082: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_0087: brtrue.s IL_0074 IL_0089: leave.s IL_0099 } finally { IL_008b: ldloca.s V_4 IL_008d: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_0093: callvirt "Sub System.IDisposable.Dispose()" IL_0098: endfinally } IL_0099: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_2() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. For Each i As Integer In (function() {i + 1, i + 2, i + 3})() x(i) = Sub() console.writeline(i.toString) Next for i = 1 to 3 x(i).invoke() next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 93 (0x5d) .maxstack 4 .locals init (System.Action() V_0, //x Integer() V_1, Integer V_2, m1._Closure$__0-1 V_3, //$VB$Closure_0 Integer V_4) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: newobj "Sub m1._Closure$__0-0..ctor()" IL_000d: callvirt "Function m1._Closure$__0-0._Lambda$__0() As Integer()" IL_0012: stloc.1 IL_0013: ldc.i4.0 IL_0014: stloc.2 IL_0015: br.s IL_003f IL_0017: ldloc.3 IL_0018: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_001d: stloc.3 IL_001e: ldloc.3 IL_001f: ldloc.1 IL_0020: ldloc.2 IL_0021: ldelem.i4 IL_0022: stfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_0027: ldloc.0 IL_0028: ldloc.3 IL_0029: ldfld "m1._Closure$__0-1.$VB$Local_i As Integer" IL_002e: ldloc.3 IL_002f: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0035: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_003a: stelem.ref IL_003b: ldloc.2 IL_003c: ldc.i4.1 IL_003d: add.ovf IL_003e: stloc.2 IL_003f: ldloc.2 IL_0040: ldloc.1 IL_0041: ldlen IL_0042: conv.i4 IL_0043: blt.s IL_0017 IL_0045: ldc.i4.1 IL_0046: stloc.s V_4 IL_0048: ldloc.0 IL_0049: ldloc.s V_4 IL_004b: ldelem.ref IL_004c: callvirt "Sub System.Action.Invoke()" IL_0051: ldloc.s V_4 IL_0053: ldc.i4.1 IL_0054: add.ovf IL_0055: stloc.s V_4 IL_0057: ldloc.s V_4 IL_0059: ldc.i4.3 IL_005a: ble.s IL_0048 IL_005c: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_3() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim x(10) as action for j = 0 to 2 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. for each i as integer in (function(a) goo())(i) x(i) = sub() console.write(i.toString &amp; " ") next for i = 1 to 3 x(i).invoke() next Console.Writeline() next j End Sub function goo() as IEnumerable(of Integer) return new list(of integer) from {1, 2, 3} end function End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[1 2 3 1 2 3 1 2 3 ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 170 (0xaa) .maxstack 4 .locals init (System.Action() V_0, //x Integer V_1, //j Integer V_2, System.Collections.Generic.IEnumerator(Of Integer) V_3, m1._Closure$__0-0 V_4, //$VB$Closure_0 Integer V_5) //i IL_0000: ldc.i4.s 11 IL_0002: newarr "System.Action" IL_0007: stloc.0 IL_0008: ldc.i4.0 IL_0009: stloc.1 IL_000a: nop .try { IL_000b: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0010: brfalse.s IL_0019 IL_0012: ldsfld "m1._Closure$__.$I0-0 As <generated method>" IL_0017: br.s IL_002f IL_0019: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_001e: ldftn "Function m1._Closure$__._Lambda$__0-0(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_0024: newobj "Sub VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer))..ctor(Object, System.IntPtr)" IL_0029: dup IL_002a: stsfld "m1._Closure$__.$I0-0 As <generated method>" IL_002f: ldloc.2 IL_0030: box "Integer" IL_0035: callvirt "Function VB$AnonymousDelegate_0(Of Object, System.Collections.Generic.IEnumerable(Of Integer)).Invoke(Object) As System.Collections.Generic.IEnumerable(Of Integer)" IL_003a: callvirt "Function System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer)" IL_003f: stloc.3 IL_0040: br.s IL_006e IL_0042: ldloc.s V_4 IL_0044: newobj "Sub m1._Closure$__0-0..ctor(m1._Closure$__0-0)" IL_0049: stloc.s V_4 IL_004b: ldloc.s V_4 IL_004d: ldloc.3 IL_004e: callvirt "Function System.Collections.Generic.IEnumerator(Of Integer).get_Current() As Integer" IL_0053: stfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0058: ldloc.0 IL_0059: ldloc.s V_4 IL_005b: ldfld "m1._Closure$__0-0.$VB$Local_i As Integer" IL_0060: ldloc.s V_4 IL_0062: ldftn "Sub m1._Closure$__0-0._Lambda$__1()" IL_0068: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_006d: stelem.ref IL_006e: ldloc.3 IL_006f: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_0074: brtrue.s IL_0042 IL_0076: leave.s IL_0082 } finally { IL_0078: ldloc.3 IL_0079: brfalse.s IL_0081 IL_007b: ldloc.3 IL_007c: callvirt "Sub System.IDisposable.Dispose()" IL_0081: endfinally } IL_0082: ldc.i4.1 IL_0083: stloc.s V_5 IL_0085: ldloc.0 IL_0086: ldloc.s V_5 IL_0088: ldelem.ref IL_0089: callvirt "Sub System.Action.Invoke()" IL_008e: ldloc.s V_5 IL_0090: ldc.i4.1 IL_0091: add.ovf IL_0092: stloc.s V_5 IL_0094: ldloc.s V_5 IL_0096: ldc.i4.3 IL_0097: ble.s IL_0085 IL_0099: call "Sub System.Console.WriteLine()" IL_009e: ldloc.1 IL_009f: ldc.i4.1 IL_00a0: add.ovf IL_00a1: stloc.1 IL_00a2: ldloc.1 IL_00a3: ldc.i4.2 IL_00a4: ble IL_000a IL_00a9: ret } ]]>) End Sub <WorkItem(545519, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545519")> <Fact()> Public Sub NewForEachScopeDev11_4() Dim source = <compilation> <file name="a.vb"> imports system imports system.collections.generic Module m1 Sub Main() ' Test Array Dim lambdas As New List(Of Action) 'Expected 0,1,2, 0,1,2, 0,1,2 lambdas.clear For y = 1 To 3 ' test lifting of control variable in loop body and lifting of control variable when used ' in the collection expression itself. The for each itself is nested in a for loop. For Each x as integer In (function(a) x = x + 1 return {a, x, 2} end function)(x) lambdas.add( Sub() Console.Write(x.ToString + "," ) ) Next lambdas.add(sub() Console.WriteLine()) Next For Each lambda In lambdas lambda() Next End Sub End Module </file> </compilation> CompileAndVerify(source, expectedOutput:=<![CDATA[ 0,1,2, 0,1,2, 0,1,2, ]]>).VerifyIL("m1.Main", <![CDATA[ { // Code size 195 (0xc3) .maxstack 3 .locals init (System.Collections.Generic.List(Of System.Action) V_0, //lambdas Integer V_1, //y Object() V_2, Integer V_3, m1._Closure$__0-1 V_4, //$VB$Closure_0 System.Collections.Generic.List(Of System.Action).Enumerator V_5) IL_0000: newobj "Sub System.Collections.Generic.List(Of System.Action)..ctor()" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: callvirt "Sub System.Collections.Generic.List(Of System.Action).Clear()" IL_000c: ldc.i4.1 IL_000d: stloc.1 IL_000e: newobj "Sub m1._Closure$__0-0..ctor()" IL_0013: dup IL_0014: ldfld "m1._Closure$__0-0.$VB$NonLocal_2 As Integer" IL_0019: box "Integer" IL_001e: callvirt "Function m1._Closure$__0-0._Lambda$__0(Object) As Object()" IL_0023: stloc.2 IL_0024: ldc.i4.0 IL_0025: stloc.3 IL_0026: br.s IL_0057 IL_0028: ldloc.s V_4 IL_002a: newobj "Sub m1._Closure$__0-1..ctor(m1._Closure$__0-1)" IL_002f: stloc.s V_4 IL_0031: ldloc.s V_4 IL_0033: ldloc.2 IL_0034: ldloc.3 IL_0035: ldelem.ref IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_003b: stfld "m1._Closure$__0-1.$VB$Local_x As Integer" IL_0040: ldloc.0 IL_0041: ldloc.s V_4 IL_0043: ldftn "Sub m1._Closure$__0-1._Lambda$__1()" IL_0049: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_004e: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0053: ldloc.3 IL_0054: ldc.i4.1 IL_0055: add.ovf IL_0056: stloc.3 IL_0057: ldloc.3 IL_0058: ldloc.2 IL_0059: ldlen IL_005a: conv.i4 IL_005b: blt.s IL_0028 IL_005d: ldloc.0 IL_005e: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_0063: brfalse.s IL_006c IL_0065: ldsfld "m1._Closure$__.$I0-2 As System.Action" IL_006a: br.s IL_0082 IL_006c: ldsfld "m1._Closure$__.$I As m1._Closure$__" IL_0071: ldftn "Sub m1._Closure$__._Lambda$__0-2()" IL_0077: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_007c: dup IL_007d: stsfld "m1._Closure$__.$I0-2 As System.Action" IL_0082: callvirt "Sub System.Collections.Generic.List(Of System.Action).Add(System.Action)" IL_0087: ldloc.1 IL_0088: ldc.i4.1 IL_0089: add.ovf IL_008a: stloc.1 IL_008b: ldloc.1 IL_008c: ldc.i4.3 IL_008d: ble IL_000e IL_0092: nop .try { IL_0093: ldloc.0 IL_0094: callvirt "Function System.Collections.Generic.List(Of System.Action).GetEnumerator() As System.Collections.Generic.List(Of System.Action).Enumerator" IL_0099: stloc.s V_5 IL_009b: br.s IL_00a9 IL_009d: ldloca.s V_5 IL_009f: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.get_Current() As System.Action" IL_00a4: callvirt "Sub System.Action.Invoke()" IL_00a9: ldloca.s V_5 IL_00ab: call "Function System.Collections.Generic.List(Of System.Action).Enumerator.MoveNext() As Boolean" IL_00b0: brtrue.s IL_009d IL_00b2: leave.s IL_00c2 } finally { IL_00b4: ldloca.s V_5 IL_00b6: constrained. "System.Collections.Generic.List(Of System.Action).Enumerator" IL_00bc: callvirt "Sub System.IDisposable.Dispose()" IL_00c1: endfinally } IL_00c2: ret } ]]>) End Sub <Fact> Public Sub ForEachLateBinding() Dim compilation1 = CompileAndVerify( <compilation> <file name="a.vb"> Option Strict Off imports system Class C Shared Sub Main() Dim o As Object = {1, 2, 3} For Each x In o console.writeline(x) Next End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseExe.WithModuleName("MODULE"), expectedOutput:=<![CDATA[ 1 2 3 ]]>).VerifyIL("C.Main", <![CDATA[ { // Code size 84 (0x54) .maxstack 3 .locals init (Object V_0, //o System.Collections.IEnumerator V_1) IL_0000: ldc.i4.3 IL_0001: newarr "Integer" IL_0006: dup IL_0007: ldtoken "<PrivateImplementationDetails>.__StaticArrayInitTypeSize=12 <PrivateImplementationDetails>.4636993D3E1DA4E9D6B8F87B79E8F7C6D018580D52661950EABC3845C5897A4D" IL_000c: call "Sub System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)" IL_0011: stloc.0 .try { IL_0012: ldloc.0 IL_0013: castclass "System.Collections.IEnumerable" IL_0018: callvirt "Function System.Collections.IEnumerable.GetEnumerator() As System.Collections.IEnumerator" IL_001d: stloc.1 IL_001e: br.s IL_0035 IL_0020: ldloc.1 IL_0021: callvirt "Function System.Collections.IEnumerator.get_Current() As Object" IL_0026: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0030: call "Sub System.Console.WriteLine(Object)" IL_0035: ldloc.1 IL_0036: callvirt "Function System.Collections.IEnumerator.MoveNext() As Boolean" IL_003b: brtrue.s IL_0020 IL_003d: leave.s IL_0053 } finally { IL_003f: ldloc.1 IL_0040: isinst "System.IDisposable" IL_0045: brfalse.s IL_0052 IL_0047: ldloc.1 IL_0048: isinst "System.IDisposable" IL_004d: callvirt "Sub System.IDisposable.Dispose()" IL_0052: endfinally } IL_0053: ret } ]]>).Compilation End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core.Wpf/Interactive/InteractiveWindowResetCommand.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 extern alias InteractiveHost; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Editor.Interactive; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { /// <summary> /// Represents a reset command which can be run from a REPL window. /// </summary> [Export(typeof(IInteractiveWindowCommand))] [ContentType(InteractiveWindowContentTypes.CommandContentTypeName)] internal sealed class InteractiveWindowResetCommand : IInteractiveWindowCommand { private const string CommandName = "reset"; private const string NoConfigParameterName = "noconfig"; private const string PlatformCore = "core"; private const string PlatformDesktop32 = "32"; private const string PlatformDesktop64 = "64"; private const string PlatformNames = PlatformCore + "|" + PlatformDesktop32 + "|" + PlatformDesktop64; private static readonly int s_noConfigParameterNameLength = NoConfigParameterName.Length; private readonly IStandardClassificationService _registry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractiveWindowResetCommand(IStandardClassificationService registry) => _registry = registry; public string Description => EditorFeaturesWpfResources.Reset_the_execution_environment_to_the_initial_state_keep_history; public IEnumerable<string> DetailedDescription => null; public IEnumerable<string> Names => SpecializedCollections.SingletonEnumerable(CommandName); public string CommandLine => "[" + NoConfigParameterName + "] [" + PlatformNames + "]"; public IEnumerable<KeyValuePair<string, string>> ParametersDescription { get { yield return new KeyValuePair<string, string>(NoConfigParameterName, EditorFeaturesWpfResources.Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script); yield return new KeyValuePair<string, string>(PlatformNames, EditorFeaturesWpfResources.Interactive_host_process_platform); } } public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) { if (!TryParseArguments(arguments, out var initialize, out var platform)) { ReportInvalidArguments(window); return ExecutionResult.Failed; } var evaluator = (CSharpInteractiveEvaluator)window.Evaluator; evaluator.ResetOptions = new InteractiveEvaluatorResetOptions(platform); return window.Operations.ResetAsync(initialize); } public IEnumerable<ClassificationSpan> ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify) { var arguments = snapshot.GetText(argumentsSpan); var argumentsStart = argumentsSpan.Start; foreach (var pos in GetNoConfigPositions(arguments)) { var snapshotSpan = new SnapshotSpan(snapshot, new Span(argumentsStart + pos, s_noConfigParameterNameLength)); yield return new ClassificationSpan(snapshotSpan, _registry.Keyword); } } /// <remarks> /// Internal for testing. /// </remarks> internal static IEnumerable<int> GetNoConfigPositions(string arguments) { var startIndex = 0; while (true) { var index = arguments.IndexOf(NoConfigParameterName, startIndex, StringComparison.Ordinal); if (index < 0) yield break; if ((index == 0 || char.IsWhiteSpace(arguments[index - 1])) && (index + s_noConfigParameterNameLength == arguments.Length || char.IsWhiteSpace(arguments[index + s_noConfigParameterNameLength]))) { yield return index; } startIndex = index + s_noConfigParameterNameLength; } } /// <remarks> /// Accessibility is internal for testing. /// </remarks> internal static bool TryParseArguments(string arguments, out bool initialize, out InteractiveHostPlatform? platform) { platform = null; initialize = true; var noConfigSpecified = false; foreach (var argument in arguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { switch (argument.ToLowerInvariant()) { case PlatformDesktop32: if (platform != null) { return false; } platform = InteractiveHostPlatform.Desktop32; break; case PlatformDesktop64: if (platform != null) { return false; } platform = InteractiveHostPlatform.Desktop64; break; case PlatformCore: if (platform != null) { return false; } platform = InteractiveHostPlatform.Core; break; case NoConfigParameterName: if (noConfigSpecified) { return false; } noConfigSpecified = true; initialize = false; break; default: return false; } } return true; } internal static string GetCommandLine(bool initialize, InteractiveHostPlatform? platform) => CommandName + (initialize ? "" : " " + NoConfigParameterName) + platform switch { null => "", InteractiveHostPlatform.Core => " " + PlatformCore, InteractiveHostPlatform.Desktop64 => " " + PlatformDesktop64, InteractiveHostPlatform.Desktop32 => " " + PlatformDesktop32, _ => throw ExceptionUtilities.Unreachable }; private void ReportInvalidArguments(IInteractiveWindow window) { var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)]; commands.DisplayCommandUsage(this, window.ErrorOutputWriter, displayDetails: 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 extern alias InteractiveHost; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Editor.Interactive; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.Language.StandardClassification; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; using InteractiveHost::Microsoft.CodeAnalysis.Interactive; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { /// <summary> /// Represents a reset command which can be run from a REPL window. /// </summary> [Export(typeof(IInteractiveWindowCommand))] [ContentType(InteractiveWindowContentTypes.CommandContentTypeName)] internal sealed class InteractiveWindowResetCommand : IInteractiveWindowCommand { private const string CommandName = "reset"; private const string NoConfigParameterName = "noconfig"; private const string PlatformCore = "core"; private const string PlatformDesktop32 = "32"; private const string PlatformDesktop64 = "64"; private const string PlatformNames = PlatformCore + "|" + PlatformDesktop32 + "|" + PlatformDesktop64; private static readonly int s_noConfigParameterNameLength = NoConfigParameterName.Length; private readonly IStandardClassificationService _registry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InteractiveWindowResetCommand(IStandardClassificationService registry) => _registry = registry; public string Description => EditorFeaturesWpfResources.Reset_the_execution_environment_to_the_initial_state_keep_history; public IEnumerable<string> DetailedDescription => null; public IEnumerable<string> Names => SpecializedCollections.SingletonEnumerable(CommandName); public string CommandLine => "[" + NoConfigParameterName + "] [" + PlatformNames + "]"; public IEnumerable<KeyValuePair<string, string>> ParametersDescription { get { yield return new KeyValuePair<string, string>(NoConfigParameterName, EditorFeaturesWpfResources.Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script); yield return new KeyValuePair<string, string>(PlatformNames, EditorFeaturesWpfResources.Interactive_host_process_platform); } } public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) { if (!TryParseArguments(arguments, out var initialize, out var platform)) { ReportInvalidArguments(window); return ExecutionResult.Failed; } var evaluator = (CSharpInteractiveEvaluator)window.Evaluator; evaluator.ResetOptions = new InteractiveEvaluatorResetOptions(platform); return window.Operations.ResetAsync(initialize); } public IEnumerable<ClassificationSpan> ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify) { var arguments = snapshot.GetText(argumentsSpan); var argumentsStart = argumentsSpan.Start; foreach (var pos in GetNoConfigPositions(arguments)) { var snapshotSpan = new SnapshotSpan(snapshot, new Span(argumentsStart + pos, s_noConfigParameterNameLength)); yield return new ClassificationSpan(snapshotSpan, _registry.Keyword); } } /// <remarks> /// Internal for testing. /// </remarks> internal static IEnumerable<int> GetNoConfigPositions(string arguments) { var startIndex = 0; while (true) { var index = arguments.IndexOf(NoConfigParameterName, startIndex, StringComparison.Ordinal); if (index < 0) yield break; if ((index == 0 || char.IsWhiteSpace(arguments[index - 1])) && (index + s_noConfigParameterNameLength == arguments.Length || char.IsWhiteSpace(arguments[index + s_noConfigParameterNameLength]))) { yield return index; } startIndex = index + s_noConfigParameterNameLength; } } /// <remarks> /// Accessibility is internal for testing. /// </remarks> internal static bool TryParseArguments(string arguments, out bool initialize, out InteractiveHostPlatform? platform) { platform = null; initialize = true; var noConfigSpecified = false; foreach (var argument in arguments.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) { switch (argument.ToLowerInvariant()) { case PlatformDesktop32: if (platform != null) { return false; } platform = InteractiveHostPlatform.Desktop32; break; case PlatformDesktop64: if (platform != null) { return false; } platform = InteractiveHostPlatform.Desktop64; break; case PlatformCore: if (platform != null) { return false; } platform = InteractiveHostPlatform.Core; break; case NoConfigParameterName: if (noConfigSpecified) { return false; } noConfigSpecified = true; initialize = false; break; default: return false; } } return true; } internal static string GetCommandLine(bool initialize, InteractiveHostPlatform? platform) => CommandName + (initialize ? "" : " " + NoConfigParameterName) + platform switch { null => "", InteractiveHostPlatform.Core => " " + PlatformCore, InteractiveHostPlatform.Desktop64 => " " + PlatformDesktop64, InteractiveHostPlatform.Desktop32 => " " + PlatformDesktop32, _ => throw ExceptionUtilities.Unreachable }; private void ReportInvalidArguments(IInteractiveWindow window) { var commands = (IInteractiveWindowCommands)window.Properties[typeof(IInteractiveWindowCommands)]; commands.DisplayCommandUsage(this, window.ErrorOutputWriter, displayDetails: false); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/Emit/Emit/EmitMetadata.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.IO Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class EmitMetadata Inherits BasicTestBase <Fact, WorkItem(547015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547015")> Public Sub IncorrectCustomAssemblyTableSize_TooManyMethodSpecs() Dim source = TestResources.MetadataTests.Invalid.ManyMethodSpecs CompileAndVerify(VisualBasicCompilation.Create("Goo", syntaxTrees:={Parse(source)}, references:={MscorlibRef, SystemCoreRef, MsvbRef})) End Sub <Fact> Public Sub InstantiatedGenerics() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Class A(Of T) Public Class B Inherits A(Of T) Friend Class C Inherits B End Class Protected y1 As B Protected y2 As A(Of D).B End Class Public Class H(Of S) Public Class I Inherits A(Of T).H(Of S) End Class End Class Friend x1 As A(Of T) Friend x2 As A(Of D) End Class Public Class D Public Class K(Of T) Public Class L Inherits K(Of T) End Class End Class End Class Namespace NS1 Class E Inherits D End Class End Namespace Class F Inherits A(Of D) End Class Class G Inherits A(Of NS1.E).B End Class Class J Inherits A(Of D).H(Of D) End Class Public Class M End Class Public Class N Inherits D.K(Of M) End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitTest1", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) CompileAndVerify(c1, symbolValidator:= Sub([Module]) Dim dump = DumpTypeInfo([Module]).ToString() AssertEx.AssertEqualToleratingWhitespaceDifferences(" <Global> <type name=""&lt;Module&gt;"" /> <type name=""A"" Of=""T"" base=""System.Object""> <field name=""x1"" type=""A(Of T)"" /> <field name=""x2"" type=""A(Of D)"" /> <type name=""B"" base=""A(Of T)""> <field name=""y1"" type=""A(Of T).B"" /> <field name=""y2"" type=""A(Of D).B"" /> <type name=""C"" base=""A(Of T).B"" /> </type> <type name=""H"" Of=""S"" base=""System.Object""> <type name=""I"" base=""A(Of T).H(Of S)"" /> </type> </type> <type name=""D"" base=""System.Object""> <type name=""K"" Of=""T"" base=""System.Object""> <type name=""L"" base=""D.K(Of T)"" /> </type> </type> <type name=""F"" base=""A(Of D)"" /> <type name=""G"" base=""A(Of NS1.E).B"" /> <type name=""J"" base=""A(Of D).H(Of D)"" /> <type name=""M"" base=""System.Object"" /> <type name=""N"" base=""D.K(Of M)"" /> <NS1> <type name=""E"" base=""D"" /> </NS1> </Global> ", dump) End Sub) End Sub Private Shared Function DumpTypeInfo(moduleSymbol As ModuleSymbol) As Xml.Linq.XElement Return LoadChildNamespace(moduleSymbol.GlobalNamespace) End Function Friend Shared Function LoadChildNamespace(n As NamespaceSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement((If(n.Name.Length = 0, "Global", n.Name))) Dim childrenTypes = n.GetTypeMembers().AsEnumerable().OrderBy(Function(t) t, New TypeComparer()) elem.Add(From t In childrenTypes Select LoadChildType(t)) Dim childrenNS = n.GetMembers(). Select(Function(m) (TryCast(m, NamespaceSymbol))). Where(Function(m) m IsNot Nothing). OrderBy(Function(child) child.Name, StringComparer.OrdinalIgnoreCase) elem.Add(From c In childrenNS Select LoadChildNamespace(c)) Return elem End Function Private Shared Function LoadChildType(t As NamedTypeSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("type") elem.Add(New System.Xml.Linq.XAttribute("name", t.Name)) If t.Arity > 0 Then Dim typeParams As String = String.Empty For Each param In t.TypeParameters If typeParams.Length > 0 Then typeParams += "," End If typeParams += param.Name Next elem.Add(New System.Xml.Linq.XAttribute("Of", typeParams)) End If If t.BaseType IsNot Nothing Then elem.Add(New System.Xml.Linq.XAttribute("base", t.BaseType.ToTestDisplayString())) End If Dim fields = t.GetMembers(). Where(Function(m) m.Kind = SymbolKind.Field). OrderBy(Function(f) f.Name).Cast(Of FieldSymbol)() elem.Add(From f In fields Select LoadField(f)) Dim childrenTypes = t.GetTypeMembers().AsEnumerable().OrderBy(Function(c) c, New TypeComparer()) elem.Add(From c In childrenTypes Select LoadChildType(c)) Return elem End Function Private Shared Function LoadField(f As FieldSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("field") elem.Add(New System.Xml.Linq.XAttribute("name", f.Name)) elem.Add(New System.Xml.Linq.XAttribute("type", f.Type.ToTestDisplayString())) Return elem End Function <Fact> Public Sub FakeILGen() Dim comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class D Public Sub New() End Sub Public Shared Sub Main() System.Console.WriteLine(65536) 'arrayField = new string[] {&quot;string1&quot;, &quot;string2&quot;} 'System.Console.WriteLine(arrayField[1]) 'System.Console.WriteLine(arrayField[0]) System.Console.WriteLine(&quot;string2&quot;) System.Console.WriteLine(&quot;string1&quot;) End Sub Shared arrayField As String() End Class </file> </compilation>, {Net40.mscorlib}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:= "65536" & Environment.NewLine & "string2" & Environment.NewLine & "string1" & Environment.NewLine) End Sub <Fact> Public Sub AssemblyRefs() Dim mscorlibRef = Net40.mscorlib Dim metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1 Dim metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2 Dim source As String = <text> Public Class Test Inherits C107 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, metadataTestLib1, metadataTestLib2}, TestOptions.ReleaseDll) Dim dllImage = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs As PEAssembly = metadata.GetAssembly Dim refs = emitAssemblyRefs.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs.Count) Assert.Equal(refs(0).Name, "MDTestLib1", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs(1).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) End Using Dim multiModule = TestReferences.SymbolsTests.MultiModule.Assembly Dim source2 As String = <text> Public Class Test Inherits Class2 End Class </text>.Value Dim c2 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs2", {VisualBasicSyntaxTree.ParseText(source2)}, {mscorlibRef, multiModule}, TestOptions.ReleaseDll) dllImage = CompileAndVerify(c2).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs2 As PEAssembly = metadata.GetAssembly Dim refs2 = emitAssemblyRefs2.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs2.Count) Assert.Equal(refs2(1).Name, "MultiModule", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs2(0).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) Dim metadataReader = emitAssemblyRefs2.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.File)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) End Using End Sub <Fact> Public Sub AddModule() Dim mscorlibRef = Net40.mscorlib Dim netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1) Dim netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2) Dim source As String = <text> Public Class Test Inherits Class1 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAddModule", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, netModule1.GetReference(), netModule2.GetReference()}, TestOptions.ReleaseDll) Dim class1 = c1.GlobalNamespace.GetMembers("Class1") Assert.Equal(1, class1.Count()) Dim manifestModule = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.Create(ModuleMetadata.CreateFromImage(manifestModule), netModule1, netModule2) Dim emitAddModule As PEAssembly = metadata.GetAssembly Assert.Equal(3, emitAddModule.Modules.Length) Dim reader = emitAddModule.GetMetadataReader() Assert.Equal(2, reader.GetTableRowCount(TableIndex.File)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name)) Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name)) Assert.False(file1.HashValue.IsNil) Assert.False(file2.HashValue.IsNil) Dim moduleRefName = reader.GetModuleReference(reader.GetModuleReferences().Single()).Name Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName)) Dim actual = From h In reader.ExportedTypes Let et = reader.GetExportedType(h) Select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{CInt(et.Attributes):X4}" AssertEx.Equal( { "NS1.Class4 0x26000001 (AssemblyFile) 0x0001", ".Class7 0x27000001 (ExportedType) 0x0002", ".Class1 0x26000001 (AssemblyFile) 0x0001", ".Class3 0x27000003 (ExportedType) 0x0002", ".Class2 0x26000002 (AssemblyFile) 0x0001" }, actual) End Using End Sub <Fact> Public Sub ImplementingAnInterface() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Interface I1 End Interface Public Class A Implements I1 End Class Public Interface I2 Sub M2() End Interface Public Interface I3 Sub M3() End Interface Public MustInherit Class B Implements I2, I3 Public MustOverride Sub M2() Implements I2.M2 Public MustOverride Sub M3() Implements I3.M3 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_ImplementingAnInterface", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub([module]) Dim classA = [module].GlobalNamespace.GetTypeMembers("A").Single() Dim classB = [module].GlobalNamespace.GetTypeMembers("B").Single() Dim i1 = [module].GlobalNamespace.GetTypeMembers("I1").Single() Dim i2 = [module].GlobalNamespace.GetTypeMembers("I2").Single() Dim i3 = [module].GlobalNamespace.GetTypeMembers("I3").Single() Assert.Equal(TypeKind.Interface, i1.TypeKind) Assert.Equal(TypeKind.Interface, i2.TypeKind) Assert.Equal(TypeKind.Interface, i3.TypeKind) Assert.Equal(TypeKind.Class, classA.TypeKind) Assert.Equal(TypeKind.Class, classB.TypeKind) Assert.Same(i1, classA.Interfaces.Single()) Dim interfaces = classB.Interfaces Assert.Same(i2, interfaces(0)) Assert.Same(i3, interfaces(1)) Assert.Equal(1, i2.GetMembers("M2").Length) Assert.Equal(1, i3.GetMembers("M3").Length) End Sub) End Sub <Fact> Public Sub Types() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public MustInherit Class A Public MustOverride Function M1(ByRef p1 As System.Array) As A() Public MustOverride Function M2(p2 As System.Boolean) As A(,) Public MustOverride Function M3(p3 As System.Char) As A(,,) Public MustOverride Sub M4(p4 As System.SByte, p5 As System.Single, p6 As System.Double, p7 As System.Int16, p8 As System.Int32, p9 As System.Int64, p10 As System.IntPtr, p11 As System.String, p12 As System.Byte, p13 As System.UInt16, p14 As System.UInt32, p15 As System.UInt64, p16 As System.UIntPtr) Public MustOverride Sub M5(Of T, S)(p17 As T, p18 As S) End Class Friend NotInheritable class B End Class Class C Public Class D End Class Friend Class E End Class Protected Class F End Class Private Class G End Class Protected Friend Class H End Class End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Types", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) Dim validator = Function(isFromSource As Boolean) _ Sub([Module] As ModuleSymbol) Dim classA = [Module].GlobalNamespace.GetTypeMembers("A").Single() Dim m1 = classA.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim m2 = classA.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim m3 = classA.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim m4 = classA.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim m5 = classA.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim method1Ret = DirectCast(m1.ReturnType, ArrayTypeSymbol) Dim method2Ret = DirectCast(m2.ReturnType, ArrayTypeSymbol) Dim method3Ret = DirectCast(m3.ReturnType, ArrayTypeSymbol) Assert.Equal(1, method1Ret.Rank) Assert.True(method1Ret.IsSZArray) Assert.Same(classA, method1Ret.ElementType) Assert.Equal(2, method2Ret.Rank) Assert.False(method2Ret.IsSZArray) Assert.Same(classA, method2Ret.ElementType) Assert.Equal(3, method3Ret.Rank) Assert.Same(classA, method3Ret.ElementType) Assert.Null(method1Ret.ContainingSymbol) Assert.Equal(ImmutableArray.Create(Of Location)(), method1Ret.Locations) Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), method1Ret.DeclaringSyntaxReferences) Assert.True(classA.IsMustInherit) Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility) Dim classB = [Module].GlobalNamespace.GetTypeMembers("B").Single() Assert.True(classB.IsNotInheritable) Assert.Equal(Accessibility.Friend, classB.DeclaredAccessibility) Dim classC = [Module].GlobalNamespace.GetTypeMembers("C").Single() 'Assert.True(classC.IsStatic) Assert.Equal(Accessibility.Friend, classC.DeclaredAccessibility) Dim classD = classC.GetTypeMembers("D").Single() Dim classE = classC.GetTypeMembers("E").Single() Dim classF = classC.GetTypeMembers("F").Single() Dim classH = classC.GetTypeMembers("H").Single() Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility) Assert.Equal(Accessibility.Friend, classE.DeclaredAccessibility) Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility) Assert.Equal(Accessibility.ProtectedOrFriend, classH.DeclaredAccessibility) If isFromSource Then Dim classG = classC.GetTypeMembers("G").Single() Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility) End If Dim parameter1 = m1.Parameters.Single() Dim parameter1Type = parameter1.Type Assert.True(parameter1.IsByRef) Assert.Same([Module].GetCorLibType(SpecialType.System_Array), parameter1Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type) Dim method4ParamTypes = m4.Parameters.Select(Function(p) p.Type).ToArray() Assert.Same([Module].GetCorLibType(SpecialType.System_Void), m4.ReturnType) Assert.Same([Module].GetCorLibType(SpecialType.System_SByte), method4ParamTypes(0)) Assert.Same([Module].GetCorLibType(SpecialType.System_Single), method4ParamTypes(1)) Assert.Same([Module].GetCorLibType(SpecialType.System_Double), method4ParamTypes(2)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int16), method4ParamTypes(3)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int32), method4ParamTypes(4)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int64), method4ParamTypes(5)) Assert.Same([Module].GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes(6)) Assert.Same([Module].GetCorLibType(SpecialType.System_String), method4ParamTypes(7)) Assert.Same([Module].GetCorLibType(SpecialType.System_Byte), method4ParamTypes(8)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt16), method4ParamTypes(9)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt32), method4ParamTypes(10)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt64), method4ParamTypes(11)) Assert.Same([Module].GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes(12)) Assert.True(m5.IsGenericMethod) Assert.Same(m5.TypeParameters(0), m5.Parameters(0).Type) Assert.Same(m5.TypeParameters(1), m5.Parameters(1).Type) If Not isFromSource Then Dim peReader = (DirectCast([Module], PEModuleSymbol)).Module.GetMetadataReader() Dim list = New List(Of String)() For Each typeRef In peReader.TypeReferences list.Add(peReader.GetString(peReader.GetTypeReference(typeRef).Name)) Next AssertEx.SetEqual({"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "DebuggingModes", "Object", "Array"}, list) End If End Sub CompileAndVerify(c1, symbolValidator:=validator(False), sourceSymbolValidator:=validator(True)) End Sub <Fact> Public Sub Fields() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Class A public F1 As Integer End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Fields", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub(m) Dim classA = m.GlobalNamespace.GetTypeMembers("A").Single() Dim f1 = classA.GetMembers("F1").OfType(Of FieldSymbol)().Single() Assert.Equal(0, f1.CustomModifiers.Length) End Sub) End Sub <Fact()> Public Sub EmittedModuleTable() CompileAndVerify( <compilation> <file name="a.vb"> Public Class A_class End Class </file> </compilation>, validator:=AddressOf EmittedModuleRecordValidator) End Sub Private Sub EmittedModuleRecordValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs As TypeDefinitionHandle() = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(2, typeDefs.Length) Assert.Equal("<Module>", reader.GetString(reader.GetTypeDefinition(typeDefs(0)).Name)) Assert.Equal("A_class", reader.GetString(reader.GetTypeDefinition(typeDefs(1)).Name)) ' Expected: 0 which is equal to [.class private auto ansi <Module>] Assert.Equal(0, reader.GetTypeDefinition(typeDefs(0)).Attributes) End Sub <WorkItem(543517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543517")> <Fact()> Public Sub EmitBeforeFieldInit() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Public Class A_class End Class Public Class B_class Shared Sub New() End Sub End Class Public Class C_class Shared Fld As Integer = 123 Shared Sub New() End Sub End Class Public Class D_class Const Fld As Integer = 123 End Class Public Class E_class Const Fld As Date = #12:00:00 AM# Shared Sub New() End Sub End Class Public Class F_class Shared Fld As Date = #12:00:00 AM# End Class Public Class G_class Const Fld As DateTime = #11/04/2008# End Class </file> </compilation>, validator:=AddressOf EmitBeforeFieldInitValidator) End Sub Private Sub EmitBeforeFieldInitValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(8, typeDefs.Length) Dim row = reader.GetTypeDefinition(typeDefs(0)) Assert.Equal("<Module>", reader.GetString(row.Name)) Assert.Equal(0, row.Attributes) row = reader.GetTypeDefinition(typeDefs(1)) Assert.Equal("A_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(2)) Assert.Equal("B_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(3)) Assert.Equal("C_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(4)) Assert.Equal("D_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(5)) Assert.Equal("E_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(6)) Assert.Equal("F_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) row = reader.GetTypeDefinition(typeDefs(7)) Assert.Equal("G_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) End Sub <Fact()> Public Sub GenericMethods2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As TC1 = New TC1() System.Console.WriteLine(x.GetType()) Dim y As TC2(Of Byte) = New TC2(Of Byte)() System.Console.WriteLine(y.GetType()) Dim z As TC3(Of Byte).TC4 = New TC3(Of Byte).TC4() System.Console.WriteLine(z.GetType()) End Sub End Module Class TC1 Sub TM1(Of T1)() TM1(Of T1)() End Sub Sub TM2(Of T2)() TM2(Of Integer)() End Sub End Class Class TC2(Of T3) Sub TM3(Of T4)() TM3(Of T4)() TM3(Of T4)() End Sub Sub TM4(Of T5)() TM4(Of Integer)() TM4(Of Integer)() End Sub Shared Sub TM5(Of T6)(x As T6) TC2(Of Integer).TM5(Of T6)(x) End Sub Shared Sub TM6(Of T7)(x As T7) TC2(Of Integer).TM6(Of Integer)(1) End Sub Sub TM9() TM9() TM9() End Sub End Class Class TC3(Of T8) Public Class TC4 Sub TM7(Of T9)() TM7(Of T9)() TM7(Of Integer)() End Sub Shared Sub TM8(Of T10)(x As T10) TC3(Of Integer).TC4.TM8(Of T10)(x) TC3(Of Integer).TC4.TM8(Of Integer)(1) End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ TC1 TC2`1[System.Byte] TC3`1+TC4[System.Byte] ]]>) End Sub <Fact()> Public Sub Constructors() Dim sources = <compilation> <file name="c.vb"> Namespace N MustInherit Class C Shared Sub New() End Sub Protected Sub New() End Sub End Class End Namespace </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetNamespaceMembers().Single.GetTypeMembers("C").Single() Dim ctor = type.GetMethod(".ctor") Assert.NotNull(ctor) Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name) Assert.Equal(MethodKind.Constructor, ctor.MethodKind) Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility) Assert.True(ctor.IsDefinition) Assert.False(ctor.IsShared) Assert.False(ctor.IsMustOverride) Assert.False(ctor.IsNotOverridable) Assert.False(ctor.IsOverridable) Assert.False(ctor.IsOverrides) Assert.False(ctor.IsGenericMethod) Assert.False(ctor.IsExtensionMethod) Assert.True(ctor.IsSub) Assert.False(ctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()) Assert.Equal(0, ctor.TypeParameters.Length) Assert.Equal("Void", ctor.ReturnType.Name) If isFromSource Then Dim cctor = type.GetMethod(".cctor") Assert.NotNull(cctor) Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name) Assert.Equal(MethodKind.SharedConstructor, cctor.MethodKind) Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility) Assert.True(cctor.IsDefinition) Assert.True(cctor.IsShared) Assert.False(cctor.IsMustOverride) Assert.False(cctor.IsNotOverridable) Assert.False(cctor.IsOverridable) Assert.False(cctor.IsOverrides) Assert.False(cctor.IsGenericMethod) Assert.False(cctor.IsExtensionMethod) Assert.True(cctor.IsSub) Assert.False(cctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString()) Assert.Equal(0, cctor.TypeArguments.Length) Assert.Equal(0, cctor.Parameters.Length) Assert.Equal("Void", cctor.ReturnType.Name) Else Assert.Equal(0, type.GetMembers(".cctor").Length) End If End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub <Fact()> Public Sub DoNotImportPrivateMembers() Dim sources = <compilation> <file name="c.vb"> Namespace [Namespace] Public Class [Public] End Class Friend Class [Friend] End Class End Namespace Class Types Public Class [Public] End Class Friend Class [Friend] End Class Protected Class [Protected] End Class Protected Friend Class ProtectedFriend End Class Private Class [Private] End Class End Class Class FIelds Public [Public] Friend [Friend] Protected [Protected] Protected Friend ProtectedFriend Private [Private] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub Protected Sub [Protected]() End Sub Protected Friend Sub ProtectedFriend() End Sub Private Sub [Private]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] Protected Property [Protected] Protected Friend Property ProtectedFriend Private Property [Private] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim nmspace = [module].GlobalNamespace.GetNamespaceMembers().Single() Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault()) Assert.NotNull(nmspace.GetTypeMembers("Friend").SingleOrDefault()) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, True) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, False) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub Private Sub CheckPrivateMembers(type As NamedTypeSymbol, isFromSource As Boolean, importPrivates As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Assert.NotNull(type.GetMembers("Friend").SingleOrDefault()) Assert.NotNull(type.GetMembers("Protected").SingleOrDefault()) Assert.NotNull(type.GetMembers("ProtectedFriend").SingleOrDefault()) Dim member = type.GetMembers("Private").SingleOrDefault() If importPrivates OrElse isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact()> Public Sub DoNotImportInternalMembers() Dim sources = <compilation> <file name="c.vb"> Class FIelds Public [Public] Friend [Friend] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub Private Sub CheckInternalMembers(type As NamedTypeSymbol, isFromSource As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Dim member = type.GetMembers("Friend").SingleOrDefault() If isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact, WorkItem(6190, "https://github.com/dotnet/roslyn/issues/6190"), WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")> Public Sub EmitWithNoResourcesAllPlatforms() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file> Class Test Shared Sub Main() End Sub End Class </file> </compilation>) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu"), Platform.AnyCpu) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu32BitPreferred"), Platform.AnyCpu32BitPreferred) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Arm"), Platform.Arm) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Itanium"), Platform.Itanium) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X64"), Platform.X64) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X86"), Platform.X86) End Sub Private Sub VerifyEmitWithNoResources(comp As VisualBasicCompilation, platform As Platform) Dim options = TestOptions.ReleaseExe.WithPlatform(platform) CompileAndVerify(comp.WithOptions(options)) 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.IO Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Roslyn.Test.Utilities Imports Roslyn.Test.Utilities.TestMetadata Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Public Class EmitMetadata Inherits BasicTestBase <Fact, WorkItem(547015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547015")> Public Sub IncorrectCustomAssemblyTableSize_TooManyMethodSpecs() Dim source = TestResources.MetadataTests.Invalid.ManyMethodSpecs CompileAndVerify(VisualBasicCompilation.Create("Goo", syntaxTrees:={Parse(source)}, references:={MscorlibRef, SystemCoreRef, MsvbRef})) End Sub <Fact> Public Sub InstantiatedGenerics() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Class A(Of T) Public Class B Inherits A(Of T) Friend Class C Inherits B End Class Protected y1 As B Protected y2 As A(Of D).B End Class Public Class H(Of S) Public Class I Inherits A(Of T).H(Of S) End Class End Class Friend x1 As A(Of T) Friend x2 As A(Of D) End Class Public Class D Public Class K(Of T) Public Class L Inherits K(Of T) End Class End Class End Class Namespace NS1 Class E Inherits D End Class End Namespace Class F Inherits A(Of D) End Class Class G Inherits A(Of NS1.E).B End Class Class J Inherits A(Of D).H(Of D) End Class Public Class M End Class Public Class N Inherits D.K(Of M) End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitTest1", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) CompileAndVerify(c1, symbolValidator:= Sub([Module]) Dim dump = DumpTypeInfo([Module]).ToString() AssertEx.AssertEqualToleratingWhitespaceDifferences(" <Global> <type name=""&lt;Module&gt;"" /> <type name=""A"" Of=""T"" base=""System.Object""> <field name=""x1"" type=""A(Of T)"" /> <field name=""x2"" type=""A(Of D)"" /> <type name=""B"" base=""A(Of T)""> <field name=""y1"" type=""A(Of T).B"" /> <field name=""y2"" type=""A(Of D).B"" /> <type name=""C"" base=""A(Of T).B"" /> </type> <type name=""H"" Of=""S"" base=""System.Object""> <type name=""I"" base=""A(Of T).H(Of S)"" /> </type> </type> <type name=""D"" base=""System.Object""> <type name=""K"" Of=""T"" base=""System.Object""> <type name=""L"" base=""D.K(Of T)"" /> </type> </type> <type name=""F"" base=""A(Of D)"" /> <type name=""G"" base=""A(Of NS1.E).B"" /> <type name=""J"" base=""A(Of D).H(Of D)"" /> <type name=""M"" base=""System.Object"" /> <type name=""N"" base=""D.K(Of M)"" /> <NS1> <type name=""E"" base=""D"" /> </NS1> </Global> ", dump) End Sub) End Sub Private Shared Function DumpTypeInfo(moduleSymbol As ModuleSymbol) As Xml.Linq.XElement Return LoadChildNamespace(moduleSymbol.GlobalNamespace) End Function Friend Shared Function LoadChildNamespace(n As NamespaceSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement((If(n.Name.Length = 0, "Global", n.Name))) Dim childrenTypes = n.GetTypeMembers().AsEnumerable().OrderBy(Function(t) t, New TypeComparer()) elem.Add(From t In childrenTypes Select LoadChildType(t)) Dim childrenNS = n.GetMembers(). Select(Function(m) (TryCast(m, NamespaceSymbol))). Where(Function(m) m IsNot Nothing). OrderBy(Function(child) child.Name, StringComparer.OrdinalIgnoreCase) elem.Add(From c In childrenNS Select LoadChildNamespace(c)) Return elem End Function Private Shared Function LoadChildType(t As NamedTypeSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("type") elem.Add(New System.Xml.Linq.XAttribute("name", t.Name)) If t.Arity > 0 Then Dim typeParams As String = String.Empty For Each param In t.TypeParameters If typeParams.Length > 0 Then typeParams += "," End If typeParams += param.Name Next elem.Add(New System.Xml.Linq.XAttribute("Of", typeParams)) End If If t.BaseType IsNot Nothing Then elem.Add(New System.Xml.Linq.XAttribute("base", t.BaseType.ToTestDisplayString())) End If Dim fields = t.GetMembers(). Where(Function(m) m.Kind = SymbolKind.Field). OrderBy(Function(f) f.Name).Cast(Of FieldSymbol)() elem.Add(From f In fields Select LoadField(f)) Dim childrenTypes = t.GetTypeMembers().AsEnumerable().OrderBy(Function(c) c, New TypeComparer()) elem.Add(From c In childrenTypes Select LoadChildType(c)) Return elem End Function Private Shared Function LoadField(f As FieldSymbol) As Xml.Linq.XElement Dim elem As Xml.Linq.XElement = New System.Xml.Linq.XElement("field") elem.Add(New System.Xml.Linq.XAttribute("name", f.Name)) elem.Add(New System.Xml.Linq.XAttribute("type", f.Type.ToTestDisplayString())) Return elem End Function <Fact> Public Sub FakeILGen() Dim comp = CompilationUtils.CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"> Public Class D Public Sub New() End Sub Public Shared Sub Main() System.Console.WriteLine(65536) 'arrayField = new string[] {&quot;string1&quot;, &quot;string2&quot;} 'System.Console.WriteLine(arrayField[1]) 'System.Console.WriteLine(arrayField[0]) System.Console.WriteLine(&quot;string2&quot;) System.Console.WriteLine(&quot;string1&quot;) End Sub Shared arrayField As String() End Class </file> </compilation>, {Net40.mscorlib}, TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:= "65536" & Environment.NewLine & "string2" & Environment.NewLine & "string1" & Environment.NewLine) End Sub <Fact> Public Sub AssemblyRefs() Dim mscorlibRef = Net40.mscorlib Dim metadataTestLib1 = TestReferences.SymbolsTests.MDTestLib1 Dim metadataTestLib2 = TestReferences.SymbolsTests.MDTestLib2 Dim source As String = <text> Public Class Test Inherits C107 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, metadataTestLib1, metadataTestLib2}, TestOptions.ReleaseDll) Dim dllImage = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs As PEAssembly = metadata.GetAssembly Dim refs = emitAssemblyRefs.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs.Count) Assert.Equal(refs(0).Name, "MDTestLib1", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs(1).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) End Using Dim multiModule = TestReferences.SymbolsTests.MultiModule.Assembly Dim source2 As String = <text> Public Class Test Inherits Class2 End Class </text>.Value Dim c2 = VisualBasicCompilation.Create("VB_EmitAssemblyRefs2", {VisualBasicSyntaxTree.ParseText(source2)}, {mscorlibRef, multiModule}, TestOptions.ReleaseDll) dllImage = CompileAndVerify(c2).EmittedAssemblyData Using metadata = AssemblyMetadata.CreateFromImage(dllImage) Dim emitAssemblyRefs2 As PEAssembly = metadata.GetAssembly Dim refs2 = emitAssemblyRefs2.Modules(0).ReferencedAssemblies.AsEnumerable().OrderBy(Function(r) r.Name).ToArray() Assert.Equal(2, refs2.Count) Assert.Equal(refs2(1).Name, "MultiModule", StringComparer.OrdinalIgnoreCase) Assert.Equal(refs2(0).Name, "mscorlib", StringComparer.OrdinalIgnoreCase) Dim metadataReader = emitAssemblyRefs2.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.File)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) End Using End Sub <Fact> Public Sub AddModule() Dim mscorlibRef = Net40.mscorlib Dim netModule1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1) Dim netModule2 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule2) Dim source As String = <text> Public Class Test Inherits Class1 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_EmitAddModule", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef, netModule1.GetReference(), netModule2.GetReference()}, TestOptions.ReleaseDll) Dim class1 = c1.GlobalNamespace.GetMembers("Class1") Assert.Equal(1, class1.Count()) Dim manifestModule = CompileAndVerify(c1).EmittedAssemblyData Using metadata = AssemblyMetadata.Create(ModuleMetadata.CreateFromImage(manifestModule), netModule1, netModule2) Dim emitAddModule As PEAssembly = metadata.GetAssembly Assert.Equal(3, emitAddModule.Modules.Length) Dim reader = emitAddModule.GetMetadataReader() Assert.Equal(2, reader.GetTableRowCount(TableIndex.File)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal("netModule1.netmodule", reader.GetString(file1.Name)) Assert.Equal("netModule2.netmodule", reader.GetString(file2.Name)) Assert.False(file1.HashValue.IsNil) Assert.False(file2.HashValue.IsNil) Dim moduleRefName = reader.GetModuleReference(reader.GetModuleReferences().Single()).Name Assert.Equal("netModule1.netmodule", reader.GetString(moduleRefName)) Dim actual = From h In reader.ExportedTypes Let et = reader.GetExportedType(h) Select $"{reader.GetString(et.NamespaceDefinition)}.{reader.GetString(et.Name)} 0x{MetadataTokens.GetToken(et.Implementation):X8} ({et.Implementation.Kind}) 0x{CInt(et.Attributes):X4}" AssertEx.Equal( { "NS1.Class4 0x26000001 (AssemblyFile) 0x0001", ".Class7 0x27000001 (ExportedType) 0x0002", ".Class1 0x26000001 (AssemblyFile) 0x0001", ".Class3 0x27000003 (ExportedType) 0x0002", ".Class2 0x26000002 (AssemblyFile) 0x0001" }, actual) End Using End Sub <Fact> Public Sub ImplementingAnInterface() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Interface I1 End Interface Public Class A Implements I1 End Class Public Interface I2 Sub M2() End Interface Public Interface I3 Sub M3() End Interface Public MustInherit Class B Implements I2, I3 Public MustOverride Sub M2() Implements I2.M2 Public MustOverride Sub M3() Implements I3.M3 End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_ImplementingAnInterface", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub([module]) Dim classA = [module].GlobalNamespace.GetTypeMembers("A").Single() Dim classB = [module].GlobalNamespace.GetTypeMembers("B").Single() Dim i1 = [module].GlobalNamespace.GetTypeMembers("I1").Single() Dim i2 = [module].GlobalNamespace.GetTypeMembers("I2").Single() Dim i3 = [module].GlobalNamespace.GetTypeMembers("I3").Single() Assert.Equal(TypeKind.Interface, i1.TypeKind) Assert.Equal(TypeKind.Interface, i2.TypeKind) Assert.Equal(TypeKind.Interface, i3.TypeKind) Assert.Equal(TypeKind.Class, classA.TypeKind) Assert.Equal(TypeKind.Class, classB.TypeKind) Assert.Same(i1, classA.Interfaces.Single()) Dim interfaces = classB.Interfaces Assert.Same(i2, interfaces(0)) Assert.Same(i3, interfaces(1)) Assert.Equal(1, i2.GetMembers("M2").Length) Assert.Equal(1, i3.GetMembers("M3").Length) End Sub) End Sub <Fact> Public Sub Types() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public MustInherit Class A Public MustOverride Function M1(ByRef p1 As System.Array) As A() Public MustOverride Function M2(p2 As System.Boolean) As A(,) Public MustOverride Function M3(p3 As System.Char) As A(,,) Public MustOverride Sub M4(p4 As System.SByte, p5 As System.Single, p6 As System.Double, p7 As System.Int16, p8 As System.Int32, p9 As System.Int64, p10 As System.IntPtr, p11 As System.String, p12 As System.Byte, p13 As System.UInt16, p14 As System.UInt32, p15 As System.UInt64, p16 As System.UIntPtr) Public MustOverride Sub M5(Of T, S)(p17 As T, p18 As S) End Class Friend NotInheritable class B End Class Class C Public Class D End Class Friend Class E End Class Protected Class F End Class Private Class G End Class Protected Friend Class H End Class End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Types", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) Dim validator = Function(isFromSource As Boolean) _ Sub([Module] As ModuleSymbol) Dim classA = [Module].GlobalNamespace.GetTypeMembers("A").Single() Dim m1 = classA.GetMembers("M1").OfType(Of MethodSymbol)().Single() Dim m2 = classA.GetMembers("M2").OfType(Of MethodSymbol)().Single() Dim m3 = classA.GetMembers("M3").OfType(Of MethodSymbol)().Single() Dim m4 = classA.GetMembers("M4").OfType(Of MethodSymbol)().Single() Dim m5 = classA.GetMembers("M5").OfType(Of MethodSymbol)().Single() Dim method1Ret = DirectCast(m1.ReturnType, ArrayTypeSymbol) Dim method2Ret = DirectCast(m2.ReturnType, ArrayTypeSymbol) Dim method3Ret = DirectCast(m3.ReturnType, ArrayTypeSymbol) Assert.Equal(1, method1Ret.Rank) Assert.True(method1Ret.IsSZArray) Assert.Same(classA, method1Ret.ElementType) Assert.Equal(2, method2Ret.Rank) Assert.False(method2Ret.IsSZArray) Assert.Same(classA, method2Ret.ElementType) Assert.Equal(3, method3Ret.Rank) Assert.Same(classA, method3Ret.ElementType) Assert.Null(method1Ret.ContainingSymbol) Assert.Equal(ImmutableArray.Create(Of Location)(), method1Ret.Locations) Assert.Equal(ImmutableArray.Create(Of SyntaxReference)(), method1Ret.DeclaringSyntaxReferences) Assert.True(classA.IsMustInherit) Assert.Equal(Accessibility.Public, classA.DeclaredAccessibility) Dim classB = [Module].GlobalNamespace.GetTypeMembers("B").Single() Assert.True(classB.IsNotInheritable) Assert.Equal(Accessibility.Friend, classB.DeclaredAccessibility) Dim classC = [Module].GlobalNamespace.GetTypeMembers("C").Single() 'Assert.True(classC.IsStatic) Assert.Equal(Accessibility.Friend, classC.DeclaredAccessibility) Dim classD = classC.GetTypeMembers("D").Single() Dim classE = classC.GetTypeMembers("E").Single() Dim classF = classC.GetTypeMembers("F").Single() Dim classH = classC.GetTypeMembers("H").Single() Assert.Equal(Accessibility.Public, classD.DeclaredAccessibility) Assert.Equal(Accessibility.Friend, classE.DeclaredAccessibility) Assert.Equal(Accessibility.Protected, classF.DeclaredAccessibility) Assert.Equal(Accessibility.ProtectedOrFriend, classH.DeclaredAccessibility) If isFromSource Then Dim classG = classC.GetTypeMembers("G").Single() Assert.Equal(Accessibility.Private, classG.DeclaredAccessibility) End If Dim parameter1 = m1.Parameters.Single() Dim parameter1Type = parameter1.Type Assert.True(parameter1.IsByRef) Assert.Same([Module].GetCorLibType(SpecialType.System_Array), parameter1Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Boolean), m2.Parameters.Single().Type) Assert.Same([Module].GetCorLibType(SpecialType.System_Char), m3.Parameters.Single().Type) Dim method4ParamTypes = m4.Parameters.Select(Function(p) p.Type).ToArray() Assert.Same([Module].GetCorLibType(SpecialType.System_Void), m4.ReturnType) Assert.Same([Module].GetCorLibType(SpecialType.System_SByte), method4ParamTypes(0)) Assert.Same([Module].GetCorLibType(SpecialType.System_Single), method4ParamTypes(1)) Assert.Same([Module].GetCorLibType(SpecialType.System_Double), method4ParamTypes(2)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int16), method4ParamTypes(3)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int32), method4ParamTypes(4)) Assert.Same([Module].GetCorLibType(SpecialType.System_Int64), method4ParamTypes(5)) Assert.Same([Module].GetCorLibType(SpecialType.System_IntPtr), method4ParamTypes(6)) Assert.Same([Module].GetCorLibType(SpecialType.System_String), method4ParamTypes(7)) Assert.Same([Module].GetCorLibType(SpecialType.System_Byte), method4ParamTypes(8)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt16), method4ParamTypes(9)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt32), method4ParamTypes(10)) Assert.Same([Module].GetCorLibType(SpecialType.System_UInt64), method4ParamTypes(11)) Assert.Same([Module].GetCorLibType(SpecialType.System_UIntPtr), method4ParamTypes(12)) Assert.True(m5.IsGenericMethod) Assert.Same(m5.TypeParameters(0), m5.Parameters(0).Type) Assert.Same(m5.TypeParameters(1), m5.Parameters(1).Type) If Not isFromSource Then Dim peReader = (DirectCast([Module], PEModuleSymbol)).Module.GetMetadataReader() Dim list = New List(Of String)() For Each typeRef In peReader.TypeReferences list.Add(peReader.GetString(peReader.GetTypeReference(typeRef).Name)) Next AssertEx.SetEqual({"CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "DebuggingModes", "Object", "Array"}, list) End If End Sub CompileAndVerify(c1, symbolValidator:=validator(False), sourceSymbolValidator:=validator(True)) End Sub <Fact> Public Sub Fields() Dim mscorlibRef = Net40.mscorlib Dim source As String = <text> Public Class A public F1 As Integer End Class </text>.Value Dim c1 = VisualBasicCompilation.Create("VB_Fields", {VisualBasicSyntaxTree.ParseText(source)}, {mscorlibRef}, TestOptions.ReleaseDll) CompileAndVerify(c1, symbolValidator:= Sub(m) Dim classA = m.GlobalNamespace.GetTypeMembers("A").Single() Dim f1 = classA.GetMembers("F1").OfType(Of FieldSymbol)().Single() Assert.Equal(0, f1.CustomModifiers.Length) End Sub) End Sub <Fact()> Public Sub EmittedModuleTable() CompileAndVerify( <compilation> <file name="a.vb"> Public Class A_class End Class </file> </compilation>, validator:=AddressOf EmittedModuleRecordValidator) End Sub Private Sub EmittedModuleRecordValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs As TypeDefinitionHandle() = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(2, typeDefs.Length) Assert.Equal("<Module>", reader.GetString(reader.GetTypeDefinition(typeDefs(0)).Name)) Assert.Equal("A_class", reader.GetString(reader.GetTypeDefinition(typeDefs(1)).Name)) ' Expected: 0 which is equal to [.class private auto ansi <Module>] Assert.Equal(0, reader.GetTypeDefinition(typeDefs(0)).Attributes) End Sub <WorkItem(543517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543517")> <Fact()> Public Sub EmitBeforeFieldInit() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Public Class A_class End Class Public Class B_class Shared Sub New() End Sub End Class Public Class C_class Shared Fld As Integer = 123 Shared Sub New() End Sub End Class Public Class D_class Const Fld As Integer = 123 End Class Public Class E_class Const Fld As Date = #12:00:00 AM# Shared Sub New() End Sub End Class Public Class F_class Shared Fld As Date = #12:00:00 AM# End Class Public Class G_class Const Fld As DateTime = #11/04/2008# End Class </file> </compilation>, validator:=AddressOf EmitBeforeFieldInitValidator) End Sub Private Sub EmitBeforeFieldInitValidator(assembly As PEAssembly) Dim reader = assembly.GetMetadataReader() Dim typeDefs = reader.TypeDefinitions.AsEnumerable().ToArray() Assert.Equal(8, typeDefs.Length) Dim row = reader.GetTypeDefinition(typeDefs(0)) Assert.Equal("<Module>", reader.GetString(row.Name)) Assert.Equal(0, row.Attributes) row = reader.GetTypeDefinition(typeDefs(1)) Assert.Equal("A_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(2)) Assert.Equal("B_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(3)) Assert.Equal("C_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(4)) Assert.Equal("D_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(5)) Assert.Equal("E_class", reader.GetString(row.Name)) Assert.Equal(1, row.Attributes) row = reader.GetTypeDefinition(typeDefs(6)) Assert.Equal("F_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) row = reader.GetTypeDefinition(typeDefs(7)) Assert.Equal("G_class", reader.GetString(row.Name)) Assert.Equal(TypeAttributes.BeforeFieldInit Or TypeAttributes.Public, row.Attributes) End Sub <Fact()> Public Sub GenericMethods2() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Module Module1 Sub Main() Dim x As TC1 = New TC1() System.Console.WriteLine(x.GetType()) Dim y As TC2(Of Byte) = New TC2(Of Byte)() System.Console.WriteLine(y.GetType()) Dim z As TC3(Of Byte).TC4 = New TC3(Of Byte).TC4() System.Console.WriteLine(z.GetType()) End Sub End Module Class TC1 Sub TM1(Of T1)() TM1(Of T1)() End Sub Sub TM2(Of T2)() TM2(Of Integer)() End Sub End Class Class TC2(Of T3) Sub TM3(Of T4)() TM3(Of T4)() TM3(Of T4)() End Sub Sub TM4(Of T5)() TM4(Of Integer)() TM4(Of Integer)() End Sub Shared Sub TM5(Of T6)(x As T6) TC2(Of Integer).TM5(Of T6)(x) End Sub Shared Sub TM6(Of T7)(x As T7) TC2(Of Integer).TM6(Of Integer)(1) End Sub Sub TM9() TM9() TM9() End Sub End Class Class TC3(Of T8) Public Class TC4 Sub TM7(Of T9)() TM7(Of T9)() TM7(Of Integer)() End Sub Shared Sub TM8(Of T10)(x As T10) TC3(Of Integer).TC4.TM8(Of T10)(x) TC3(Of Integer).TC4.TM8(Of Integer)(1) End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ TC1 TC2`1[System.Byte] TC3`1+TC4[System.Byte] ]]>) End Sub <Fact()> Public Sub Constructors() Dim sources = <compilation> <file name="c.vb"> Namespace N MustInherit Class C Shared Sub New() End Sub Protected Sub New() End Sub End Class End Namespace </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim type = [module].GlobalNamespace.GetNamespaceMembers().Single.GetTypeMembers("C").Single() Dim ctor = type.GetMethod(".ctor") Assert.NotNull(ctor) Assert.Equal(WellKnownMemberNames.InstanceConstructorName, ctor.Name) Assert.Equal(MethodKind.Constructor, ctor.MethodKind) Assert.Equal(Accessibility.Protected, ctor.DeclaredAccessibility) Assert.True(ctor.IsDefinition) Assert.False(ctor.IsShared) Assert.False(ctor.IsMustOverride) Assert.False(ctor.IsNotOverridable) Assert.False(ctor.IsOverridable) Assert.False(ctor.IsOverrides) Assert.False(ctor.IsGenericMethod) Assert.False(ctor.IsExtensionMethod) Assert.True(ctor.IsSub) Assert.False(ctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.InstanceConstructorName + "()", ctor.ToTestDisplayString()) Assert.Equal(0, ctor.TypeParameters.Length) Assert.Equal("Void", ctor.ReturnType.Name) If isFromSource Then Dim cctor = type.GetMethod(".cctor") Assert.NotNull(cctor) Assert.Equal(WellKnownMemberNames.StaticConstructorName, cctor.Name) Assert.Equal(MethodKind.SharedConstructor, cctor.MethodKind) Assert.Equal(Accessibility.Private, cctor.DeclaredAccessibility) Assert.True(cctor.IsDefinition) Assert.True(cctor.IsShared) Assert.False(cctor.IsMustOverride) Assert.False(cctor.IsNotOverridable) Assert.False(cctor.IsOverridable) Assert.False(cctor.IsOverrides) Assert.False(cctor.IsGenericMethod) Assert.False(cctor.IsExtensionMethod) Assert.True(cctor.IsSub) Assert.False(cctor.IsVararg) ' Bug - 2067 Assert.Equal("Sub N.C." + WellKnownMemberNames.StaticConstructorName + "()", cctor.ToTestDisplayString()) Assert.Equal(0, cctor.TypeArguments.Length) Assert.Equal(0, cctor.Parameters.Length) Assert.Equal("Void", cctor.ReturnType.Name) Else Assert.Equal(0, type.GetMembers(".cctor").Length) End If End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub <Fact()> Public Sub DoNotImportPrivateMembers() Dim sources = <compilation> <file name="c.vb"> Namespace [Namespace] Public Class [Public] End Class Friend Class [Friend] End Class End Namespace Class Types Public Class [Public] End Class Friend Class [Friend] End Class Protected Class [Protected] End Class Protected Friend Class ProtectedFriend End Class Private Class [Private] End Class End Class Class FIelds Public [Public] Friend [Friend] Protected [Protected] Protected Friend ProtectedFriend Private [Private] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub Protected Sub [Protected]() End Sub Protected Friend Sub ProtectedFriend() End Sub Private Sub [Private]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] Protected Property [Protected] Protected Friend Property ProtectedFriend Private Property [Private] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) Dim nmspace = [module].GlobalNamespace.GetNamespaceMembers().Single() Assert.NotNull(nmspace.GetTypeMembers("Public").SingleOrDefault()) Assert.NotNull(nmspace.GetTypeMembers("Friend").SingleOrDefault()) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Types").Single(), isFromSource, True) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource, False) CheckPrivateMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource, False) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal)) End Sub Private Sub CheckPrivateMembers(type As NamedTypeSymbol, isFromSource As Boolean, importPrivates As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Assert.NotNull(type.GetMembers("Friend").SingleOrDefault()) Assert.NotNull(type.GetMembers("Protected").SingleOrDefault()) Assert.NotNull(type.GetMembers("ProtectedFriend").SingleOrDefault()) Dim member = type.GetMembers("Private").SingleOrDefault() If importPrivates OrElse isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact()> Public Sub DoNotImportInternalMembers() Dim sources = <compilation> <file name="c.vb"> Class FIelds Public [Public] Friend [Friend] End Class Class Methods Public Sub [Public]() End Sub Friend Sub [Friend]() End Sub End Class Class Properties Public Property [Public] Friend Property [Friend] End Class </file> </compilation> Dim validator = Function(isFromSource As Boolean) _ Sub([module] As ModuleSymbol) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Fields").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Methods").Single(), isFromSource) CheckInternalMembers([module].GlobalNamespace.GetTypeMembers("Properties").Single(), isFromSource) End Sub CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False)) End Sub Private Sub CheckInternalMembers(type As NamedTypeSymbol, isFromSource As Boolean) Assert.NotNull(type.GetMembers("Public").SingleOrDefault()) Dim member = type.GetMembers("Friend").SingleOrDefault() If isFromSource Then Assert.NotNull(member) Else Assert.Null(member) End If End Sub <Fact, WorkItem(6190, "https://github.com/dotnet/roslyn/issues/6190"), WorkItem(90, "https://github.com/dotnet/roslyn/issues/90")> Public Sub EmitWithNoResourcesAllPlatforms() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file> Class Test Shared Sub Main() End Sub End Class </file> </compilation>) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu"), Platform.AnyCpu) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_AnyCpu32BitPreferred"), Platform.AnyCpu32BitPreferred) VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Arm"), Platform.Arm) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_Itanium"), Platform.Itanium) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X64"), Platform.X64) ' broken before fix VerifyEmitWithNoResources(comp.WithAssemblyName("EmitWithNoResourcesAllPlatforms_X86"), Platform.X86) End Sub Private Sub VerifyEmitWithNoResources(comp As VisualBasicCompilation, platform As Platform) Dim options = TestOptions.ReleaseExe.WithPlatform(platform) CompileAndVerify(comp.WithOptions(options)) End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/CSharp/Portable/ExternalAccess/Pythia/Api/IPythiaSignatureHelpProviderImplementation.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal interface IPythiaSignatureHelpProviderImplementation { Task<(ImmutableArray<PythiaSignatureHelpItemWrapper> items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync(ImmutableArray<IMethodSymbol> accessibleMethods, Document document, InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, SymbolInfo currentSymbol, 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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.ExternalAccess.Pythia.Api { internal interface IPythiaSignatureHelpProviderImplementation { Task<(ImmutableArray<PythiaSignatureHelpItemWrapper> items, int? selectedItemIndex)> GetMethodGroupItemsAndSelectionAsync(ImmutableArray<IMethodSymbol> accessibleMethods, Document document, InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, SymbolInfo currentSymbol, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Sources/UserDefinedBinaryOperators.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. Public Structure UserDefinedBinaryOperator{2} Public Shared Operator +(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator -(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator *(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator /(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator \(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Mod(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator ^(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator =(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <>(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Like(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator &(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator And(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Or(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Xor(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <<(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >>(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator End Structure
' 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. Public Structure UserDefinedBinaryOperator{2} Public Shared Operator +(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator -(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator *(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator /(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator \(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Mod(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator ^(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator =(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <>(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >=(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Like(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator &(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator And(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Or(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator Xor(x As UserDefinedBinaryOperator{2}{0}, y As UserDefinedBinaryOperator{2}{1}) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator <<(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator Public Shared Operator >>(x As UserDefinedBinaryOperator{2}{0}, y As Integer) As UserDefinedBinaryOperator{2} Return x End Operator End Structure
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/SourceGeneratedFileItemSourceProvider.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.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(SourceGeneratedFileItemSourceProvider))] [Order] [AppliesToProject("CSharp | VB")] internal sealed class SourceGeneratedFileItemSourceProvider : AttachedCollectionSourceProvider<SourceGeneratorItem> { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SourceGeneratedFileItemSourceProvider(VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider asyncListenerProvider, IThreadingContext threadingContext) { _workspace = workspace; _asyncListener = asyncListenerProvider.GetListener(FeatureAttribute.SourceGenerators); _threadingContext = threadingContext; } protected override IAttachedCollectionSource? CreateCollectionSource(SourceGeneratorItem item, string relationshipName) { if (relationshipName == KnownRelationships.Contains) { return new SourceGeneratedFileItemSource(item, _workspace, _asyncListener, _threadingContext); } 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. using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export(typeof(IAttachedCollectionSourceProvider))] [Name(nameof(SourceGeneratedFileItemSourceProvider))] [Order] [AppliesToProject("CSharp | VB")] internal sealed class SourceGeneratedFileItemSourceProvider : AttachedCollectionSourceProvider<SourceGeneratorItem> { private readonly Workspace _workspace; private readonly IAsynchronousOperationListener _asyncListener; private readonly IThreadingContext _threadingContext; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public SourceGeneratedFileItemSourceProvider(VisualStudioWorkspace workspace, IAsynchronousOperationListenerProvider asyncListenerProvider, IThreadingContext threadingContext) { _workspace = workspace; _asyncListener = asyncListenerProvider.GetListener(FeatureAttribute.SourceGenerators); _threadingContext = threadingContext; } protected override IAttachedCollectionSource? CreateCollectionSource(SourceGeneratorItem item, string relationshipName) { if (relationshipName == KnownRelationships.Contains) { return new SourceGeneratedFileItemSource(item, _workspace, _asyncListener, _threadingContext); } return null; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_BreakStatement.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitBreakStatement(BoundBreakStatement node) { BoundStatement result = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors); if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentBreakStatement(node, result); } return result; } } }
// 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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode VisitBreakStatement(BoundBreakStatement node) { BoundStatement result = new BoundGotoStatement(node.Syntax, node.Label, node.HasErrors); if (this.Instrument && !node.WasCompilerGenerated) { result = _instrumenter.InstrumentBreakStatement(node, result); } return result; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/XamlRequestDispatcherFactory.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; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer { /// <summary> /// Implements the Language Server Protocol for XAML /// </summary> [Export(typeof(XamlRequestDispatcherFactory)), Shared] internal sealed class XamlRequestDispatcherFactory : AbstractRequestDispatcherFactory { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlRequestDispatcherFactory( [ImportMany] IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, XamlProjectService projectService, [Import(AllowDefault = true)] IXamlLanguageServerFeedbackService? feedbackService) : base(requestHandlerProviders) { _projectService = projectService; _feedbackService = feedbackService; } public override RequestDispatcher CreateRequestDispatcher(ImmutableArray<string> supportedLanguages) { return new XamlRequestDispatcher(_projectService, _requestHandlerProviders, _feedbackService, supportedLanguages); } private class XamlRequestDispatcher : RequestDispatcher { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; public XamlRequestDispatcher( XamlProjectService projectService, ImmutableArray<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, IXamlLanguageServerFeedbackService? feedbackService, ImmutableArray<string> languageNames) : base(requestHandlerProviders, languageNames) { _projectService = projectService; _feedbackService = feedbackService; } protected override async Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(RequestExecutionQueue queue, RequestType request, ClientCapabilities clientCapabilities, string? clientName, string methodName, bool mutatesSolutionState, bool requiresLSPSolution, IRequestHandler<RequestType, ResponseType> handler, CancellationToken cancellationToken) { var textDocument = handler.GetTextDocumentIdentifier(request); DocumentId? documentId = null; if (textDocument is { Uri: { IsAbsoluteUri: true } documentUri }) { documentId = _projectService.TrackOpenDocument(documentUri.LocalPath); } using (var requestScope = _feedbackService?.CreateRequestScope(documentId, methodName)) { try { return await base.ExecuteRequestAsync(queue, request, clientCapabilities, clientName, methodName, mutatesSolutionState, requiresLSPSolution, handler, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (e is not OperationCanceledException) { // Inform Xaml language service that the RequestScope failed. // This doesn't send the exception to Telemetry or Watson requestScope?.RecordFailure(e); throw; } } } } } }
// 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; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer { /// <summary> /// Implements the Language Server Protocol for XAML /// </summary> [Export(typeof(XamlRequestDispatcherFactory)), Shared] internal sealed class XamlRequestDispatcherFactory : AbstractRequestDispatcherFactory { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlRequestDispatcherFactory( [ImportMany] IEnumerable<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, XamlProjectService projectService, [Import(AllowDefault = true)] IXamlLanguageServerFeedbackService? feedbackService) : base(requestHandlerProviders) { _projectService = projectService; _feedbackService = feedbackService; } public override RequestDispatcher CreateRequestDispatcher(ImmutableArray<string> supportedLanguages) { return new XamlRequestDispatcher(_projectService, _requestHandlerProviders, _feedbackService, supportedLanguages); } private class XamlRequestDispatcher : RequestDispatcher { private readonly XamlProjectService _projectService; private readonly IXamlLanguageServerFeedbackService? _feedbackService; public XamlRequestDispatcher( XamlProjectService projectService, ImmutableArray<Lazy<AbstractRequestHandlerProvider, RequestHandlerProviderMetadataView>> requestHandlerProviders, IXamlLanguageServerFeedbackService? feedbackService, ImmutableArray<string> languageNames) : base(requestHandlerProviders, languageNames) { _projectService = projectService; _feedbackService = feedbackService; } protected override async Task<ResponseType> ExecuteRequestAsync<RequestType, ResponseType>(RequestExecutionQueue queue, RequestType request, ClientCapabilities clientCapabilities, string? clientName, string methodName, bool mutatesSolutionState, bool requiresLSPSolution, IRequestHandler<RequestType, ResponseType> handler, CancellationToken cancellationToken) { var textDocument = handler.GetTextDocumentIdentifier(request); DocumentId? documentId = null; if (textDocument is { Uri: { IsAbsoluteUri: true } documentUri }) { documentId = _projectService.TrackOpenDocument(documentUri.LocalPath); } using (var requestScope = _feedbackService?.CreateRequestScope(documentId, methodName)) { try { return await base.ExecuteRequestAsync(queue, request, clientCapabilities, clientName, methodName, mutatesSolutionState, requiresLSPSolution, handler, cancellationToken).ConfigureAwait(false); } catch (Exception e) when (e is not OperationCanceledException) { // Inform Xaml language service that the RequestScope failed. // This doesn't send the exception to Telemetry or Watson requestScope?.RecordFailure(e); throw; } } } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/CSharpTest/Diagnostics/Suppression/RemoveSuppressionTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Suppression { public abstract class CSharpRemoveSuppressionTests : CSharpSuppressionTests { protected override bool IncludeSuppressedDiagnostics => true; protected override bool IncludeUnsuppressedDiagnostics => false; protected override int CodeActionIndex => 0; protected class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly bool _reportDiagnosticsWithoutLocation; public static readonly DiagnosticDescriptor Decsciptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic Title", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Decsciptor); } } public UserDiagnosticAnalyzer(bool reportDiagnosticsWithoutLocation = false) => _reportDiagnosticsWithoutLocation = reportDiagnosticsWithoutLocation; public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; var location = _reportDiagnosticsWithoutLocation ? Location.None : classDecl.Identifier.GetLocation(); context.ReportDiagnostic(Diagnostic.Create(Decsciptor, location)); } } public class CSharpDiagnosticWithLocationRemoveSuppressionTests : CSharpRemoveSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression() { await TestAsync( @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title [|class Class|] #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } }", @" using System; class Class { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression_AdjacentTrivia() { await TestAsync( @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class1 { } #pragma warning restore InfoDiagnostic // InfoDiagnostic Title #pragma warning disable InfoDiagnostic // InfoDiagnostic Title [|class Class2|] #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } }", @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class1 { } #pragma warning restore InfoDiagnostic // InfoDiagnostic Title class Class2 { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression_TriviaWithMultipleIDs() { await TestAsync( @" using System; #pragma warning disable InfoDiagnostic, SomeOtherDiagnostic [|class Class|] #pragma warning restore InfoDiagnostic, SomeOtherDiagnostic { int Method() { int x = 0; } }", @" using System; #pragma warning disable InfoDiagnostic, SomeOtherDiagnostic #pragma warning restore InfoDiagnostic // InfoDiagnostic Title class Class #pragma warning disable InfoDiagnostic // InfoDiagnostic Title #pragma warning restore InfoDiagnostic, SomeOtherDiagnostic { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression_WithEnclosingSuppression() { await TestAsync( @" #pragma warning disable InfoDiagnostic using System; #pragma warning disable InfoDiagnostic [|class Class|] #pragma warning restore InfoDiagnostic { int Method() { int x = 0; } }", @" #pragma warning disable InfoDiagnostic using System; #pragma warning restore InfoDiagnostic class Class #pragma warning disable InfoDiagnostic { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemoveLocalAttributeSuppression() { await TestAsync( $@" using System; [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] [|class Class|] {{ int Method() {{ int x = 0; }} }}", @" using System; class Class { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemoveLocalAttributeSuppression2() { await TestAsync( $@" using System; class Class1 {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] [|class Class2|] {{ int Method() {{ int x = 0; }} }} }}", @" using System; class Class1 { class Class2 { int Method() { int x = 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemoveGlobalAttributeSuppression() { await TestAsync( $@" using System; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] [|class Class|] {{ int Method() {{ int x = 0; }} }}", @" using System; class Class { int Method() { int x = 0; } }"); } #region "Fix all occurrences tests" #region "Pragma disable tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_RemovePragmaSuppressions() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title {|FixAllInDocument:class Class1|} #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemovePragmaSuppressions() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title {|FixAllInProject:class Class1|} #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> <Document> #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class3 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title {|FixAllInSolution:class Class1|} #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> <Document> #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class3 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class1 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } #endregion #region "SuppressMessageAttribute tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_RemoveAttributeSuppressions() { var addedGlobalSuppressions = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; {|FixAllInDocument:class Class1|} { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressions + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemoveAttributeSuppressions() { var addedGlobalSuppressions = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; {|FixAllInProject:class Class1|} { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressions + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. "; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveAttributeSuppression() { var addedGlobalSuppressionsProject1 = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var addedGlobalSuppressionsProject2 = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; {|FixAllInSolution:class Class1|} { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressionsProject1 + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressionsProject2 + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. "; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } } public class CSharpDiagnosticWithoutLocationRemoveSuppressionTests : CSharpRemoveSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(reportDiagnosticsWithoutLocation: true), new CSharpSuppressionCodeFixProvider()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemoveAttributeSuppressions() { var addedGlobalSuppressions = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>{|FixAllInProject:|} using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressions + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. "; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } } #endregion #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; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Suppression { public abstract class CSharpRemoveSuppressionTests : CSharpSuppressionTests { protected override bool IncludeSuppressedDiagnostics => true; protected override bool IncludeUnsuppressedDiagnostics => false; protected override int CodeActionIndex => 0; protected class UserDiagnosticAnalyzer : DiagnosticAnalyzer { private readonly bool _reportDiagnosticsWithoutLocation; public static readonly DiagnosticDescriptor Decsciptor = new DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic Title", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Decsciptor); } } public UserDiagnosticAnalyzer(bool reportDiagnosticsWithoutLocation = false) => _reportDiagnosticsWithoutLocation = reportDiagnosticsWithoutLocation; public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ClassDeclaration); public void AnalyzeNode(SyntaxNodeAnalysisContext context) { var classDecl = (ClassDeclarationSyntax)context.Node; var location = _reportDiagnosticsWithoutLocation ? Location.None : classDecl.Identifier.GetLocation(); context.ReportDiagnostic(Diagnostic.Create(Decsciptor, location)); } } public class CSharpDiagnosticWithLocationRemoveSuppressionTests : CSharpRemoveSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(), new CSharpSuppressionCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression() { await TestAsync( @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title [|class Class|] #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } }", @" using System; class Class { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression_AdjacentTrivia() { await TestAsync( @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class1 { } #pragma warning restore InfoDiagnostic // InfoDiagnostic Title #pragma warning disable InfoDiagnostic // InfoDiagnostic Title [|class Class2|] #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } }", @" using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class1 { } #pragma warning restore InfoDiagnostic // InfoDiagnostic Title class Class2 { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression_TriviaWithMultipleIDs() { await TestAsync( @" using System; #pragma warning disable InfoDiagnostic, SomeOtherDiagnostic [|class Class|] #pragma warning restore InfoDiagnostic, SomeOtherDiagnostic { int Method() { int x = 0; } }", @" using System; #pragma warning disable InfoDiagnostic, SomeOtherDiagnostic #pragma warning restore InfoDiagnostic // InfoDiagnostic Title class Class #pragma warning disable InfoDiagnostic // InfoDiagnostic Title #pragma warning restore InfoDiagnostic, SomeOtherDiagnostic { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemovePragmaSuppression_WithEnclosingSuppression() { await TestAsync( @" #pragma warning disable InfoDiagnostic using System; #pragma warning disable InfoDiagnostic [|class Class|] #pragma warning restore InfoDiagnostic { int Method() { int x = 0; } }", @" #pragma warning disable InfoDiagnostic using System; #pragma warning restore InfoDiagnostic class Class #pragma warning disable InfoDiagnostic { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemoveLocalAttributeSuppression() { await TestAsync( $@" using System; [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] [|class Class|] {{ int Method() {{ int x = 0; }} }}", @" using System; class Class { int Method() { int x = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemoveLocalAttributeSuppression2() { await TestAsync( $@" using System; class Class1 {{ [System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] [|class Class2|] {{ int Method() {{ int x = 0; }} }} }}", @" using System; class Class1 { class Class2 { int Method() { int x = 0; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] public async Task TestRemoveGlobalAttributeSuppression() { await TestAsync( $@" using System; [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class"")] [|class Class|] {{ int Method() {{ int x = 0; }} }}", @" using System; class Class { int Method() { int x = 0; } }"); } #region "Fix all occurrences tests" #region "Pragma disable tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_RemovePragmaSuppressions() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title {|FixAllInDocument:class Class1|} #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemovePragmaSuppressions() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title {|FixAllInProject:class Class1|} #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> <Document> #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class3 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; #pragma warning disable InfoDiagnostic // InfoDiagnostic Title {|FixAllInSolution:class Class1|} #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> <Document> #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class3 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class1 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { int Method() { int x = 0; } } #pragma warning disable InfoDiagnostic // InfoDiagnostic Title class Class2 #pragma warning restore InfoDiagnostic // InfoDiagnostic Title { } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } #endregion #region "SuppressMessageAttribute tests" [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_RemoveAttributeSuppressions() { var addedGlobalSuppressions = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; {|FixAllInDocument:class Class1|} { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressions + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""member"", Target = ""~M:Class1.Method~System.Int32"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemoveAttributeSuppressions() { var addedGlobalSuppressions = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; {|FixAllInProject:class Class1|} { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressions + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. "; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_RemoveAttributeSuppression() { var addedGlobalSuppressionsProject1 = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class3"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var addedGlobalSuppressionsProject2 = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class1"")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"", Scope = ""type"", Target = ""~T:Class2"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; {|FixAllInSolution:class Class1|} { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressionsProject1 + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressionsProject2 + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. "; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } } public class CSharpDiagnosticWithoutLocationRemoveSuppressionTests : CSharpRemoveSuppressionTests { internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new UserDiagnosticAnalyzer(reportDiagnosticsWithoutLocation: true), new CSharpSuppressionCodeFixProvider()); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_RemoveAttributeSuppressions() { var addedGlobalSuppressions = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification = ""{FeaturesResources.Pending}"")] ".Replace("<", "&lt;").Replace(">", "&gt;"); var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document>{|FixAllInProject:|} using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + addedGlobalSuppressions + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; var newGlobalSuppressionsFile = $@" // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. "; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document> class Class3 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly1.cs"">" + newGlobalSuppressionsFile + @"</Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> class Class1 { int Method() { int x = 0; } } class Class2 { } </Document> <Document FilePath=""GlobalSuppressions_Assembly2.cs"">" + addedGlobalSuppressions + @"</Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected); } } #endregion #endregion } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Lowering/SynthesizedMethodBaseSymbol.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.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A base method symbol used as a base class for lambda method symbol and base method wrapper symbol. /// </summary> internal abstract class SynthesizedMethodBaseSymbol : SourceMemberMethodSymbol { protected readonly MethodSymbol BaseMethod; internal TypeMap TypeMap { get; private set; } private readonly string _name; private ImmutableArray<TypeParameterSymbol> _typeParameters; private ImmutableArray<ParameterSymbol> _parameters; private TypeWithAnnotations.Boxed _iteratorElementType; protected SynthesizedMethodBaseSymbol(NamedTypeSymbol containingType, MethodSymbol baseMethod, SyntaxReference syntaxReference, Location location, string name, DeclarationModifiers declarationModifiers) : base(containingType, syntaxReference, location, isIterator: false) { Debug.Assert((object)containingType != null); Debug.Assert((object)baseMethod != null); this.BaseMethod = baseMethod; _name = name; this.MakeFlags( methodKind: MethodKind.Ordinary, declarationModifiers: declarationModifiers, returnsVoid: baseMethod.ReturnsVoid, isExtensionMethod: false, isNullableAnalysisEnabled: false, isMetadataVirtualIgnoringModifiers: false); } protected void AssignTypeMapAndTypeParameters(TypeMap typeMap, ImmutableArray<TypeParameterSymbol> typeParameters) { Debug.Assert(typeMap != null); Debug.Assert(this.TypeMap == null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(_typeParameters.IsDefault); this.TypeMap = typeMap; _typeParameters = typeParameters; } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); // do not generate attributes for members of compiler-generated types: if (ContainingType.IsImplicitlyDeclared) { return; } var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; internal override int ParameterCount { get { return this.Parameters.Length; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { if (_parameters.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _parameters, MakeParameters()); } return _parameters; } } protected virtual ImmutableArray<TypeSymbol> ExtraSynthesizedRefParameters { get { return default(ImmutableArray<TypeSymbol>); } } protected virtual ImmutableArray<ParameterSymbol> BaseMethodParameters { get { return this.BaseMethod.Parameters; } } private ImmutableArray<ParameterSymbol> MakeParameters() { int ordinal = 0; var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); var parameters = this.BaseMethodParameters; var inheritAttributes = InheritsBaseMethodAttributes; foreach (var p in parameters) { builder.Add(SynthesizedParameterSymbol.Create( this, this.TypeMap.SubstituteType(p.OriginalDefinition.TypeWithAnnotations), ordinal++, p.RefKind, p.Name, // the synthesized parameter doesn't need to have the same ref custom modifiers as the base refCustomModifiers: default, inheritAttributes ? p as SourceComplexParameterSymbol : null)); } var extraSynthed = ExtraSynthesizedRefParameters; if (!extraSynthed.IsDefaultOrEmpty) { foreach (var extra in extraSynthed) { builder.Add(SynthesizedParameterSymbol.Create(this, this.TypeMap.SubstituteType(extra), ordinal++, RefKind.Ref)); } } return builder.ToImmutableAndFree(); } /// <summary> /// Indicates that this method inherits attributes from the base method, its parameters, return type, and type parameters. /// </summary> internal virtual bool InheritsBaseMethodAttributes => false; public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { Debug.Assert(base.GetAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } public sealed override ImmutableArray<CSharpAttributeData> GetReturnTypeAttributes() { Debug.Assert(base.GetReturnTypeAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetReturnTypeAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } #nullable enable public sealed override DllImportData? GetDllImportData() => InheritsBaseMethodAttributes ? BaseMethod.GetDllImportData() : null; internal sealed override MethodImplAttributes ImplementationAttributes => InheritsBaseMethodAttributes ? BaseMethod.ImplementationAttributes : default; internal sealed override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => InheritsBaseMethodAttributes ? BaseMethod.ReturnValueMarshallingInformation : null; internal sealed override bool HasSpecialName => InheritsBaseMethodAttributes && BaseMethod.HasSpecialName; // Synthesized methods created from a base method with [SkipLocalsInitAttribute] will also // skip locals init where applicable, even if the synthesized method does not inherit attributes. // Note that this doesn't affect BaseMethodWrapperSymbol for example because the implementation has no locals. public sealed override bool AreLocalsZeroed => !(BaseMethod is SourceMethodSymbol sourceMethod) || sourceMethod.AreLocalsZeroed; internal sealed override bool RequiresSecurityObject => InheritsBaseMethodAttributes && BaseMethod.RequiresSecurityObject; internal sealed override bool HasDeclarativeSecurity => InheritsBaseMethodAttributes && BaseMethod.HasDeclarativeSecurity; internal sealed override IEnumerable<SecurityAttribute> GetSecurityInformation() => InheritsBaseMethodAttributes ? BaseMethod.GetSecurityInformation() : SpecializedCollections.EmptyEnumerable<SecurityAttribute>(); #nullable disable public sealed override RefKind RefKind { get { return this.BaseMethod.RefKind; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { return this.TypeMap.SubstituteType(this.BaseMethod.OriginalDefinition.ReturnTypeWithAnnotations); } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => BaseMethod.ReturnTypeFlowAnalysisAnnotations; public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => BaseMethod.ReturnNotNullIfParameterNotNull; public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public sealed override bool IsVararg { get { return this.BaseMethod.IsVararg; } } public sealed override string Name { get { return _name; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { if (_iteratorElementType is null) { Interlocked.CompareExchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(TypeMap.SubstituteType(BaseMethod.IteratorElementTypeWithAnnotations.Type)), null); } return _iteratorElementType.Value; } set { Debug.Assert(!value.IsDefault); Interlocked.Exchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(value)); } } internal override bool IsIterator => BaseMethod.IsIterator; } }
// 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.Diagnostics; using System.Reflection; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A base method symbol used as a base class for lambda method symbol and base method wrapper symbol. /// </summary> internal abstract class SynthesizedMethodBaseSymbol : SourceMemberMethodSymbol { protected readonly MethodSymbol BaseMethod; internal TypeMap TypeMap { get; private set; } private readonly string _name; private ImmutableArray<TypeParameterSymbol> _typeParameters; private ImmutableArray<ParameterSymbol> _parameters; private TypeWithAnnotations.Boxed _iteratorElementType; protected SynthesizedMethodBaseSymbol(NamedTypeSymbol containingType, MethodSymbol baseMethod, SyntaxReference syntaxReference, Location location, string name, DeclarationModifiers declarationModifiers) : base(containingType, syntaxReference, location, isIterator: false) { Debug.Assert((object)containingType != null); Debug.Assert((object)baseMethod != null); this.BaseMethod = baseMethod; _name = name; this.MakeFlags( methodKind: MethodKind.Ordinary, declarationModifiers: declarationModifiers, returnsVoid: baseMethod.ReturnsVoid, isExtensionMethod: false, isNullableAnalysisEnabled: false, isMetadataVirtualIgnoringModifiers: false); } protected void AssignTypeMapAndTypeParameters(TypeMap typeMap, ImmutableArray<TypeParameterSymbol> typeParameters) { Debug.Assert(typeMap != null); Debug.Assert(this.TypeMap == null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(_typeParameters.IsDefault); this.TypeMap = typeMap; _typeParameters = typeParameters; } protected override void MethodChecks(BindingDiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); // do not generate attributes for members of compiler-generated types: if (ContainingType.IsImplicitlyDeclared) { return; } var compilation = this.DeclaringCompilation; AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return _typeParameters; } } public sealed override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() => ImmutableArray<ImmutableArray<TypeWithAnnotations>>.Empty; public sealed override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() => ImmutableArray<TypeParameterConstraintKind>.Empty; internal override int ParameterCount { get { return this.Parameters.Length; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { if (_parameters.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _parameters, MakeParameters()); } return _parameters; } } protected virtual ImmutableArray<TypeSymbol> ExtraSynthesizedRefParameters { get { return default(ImmutableArray<TypeSymbol>); } } protected virtual ImmutableArray<ParameterSymbol> BaseMethodParameters { get { return this.BaseMethod.Parameters; } } private ImmutableArray<ParameterSymbol> MakeParameters() { int ordinal = 0; var builder = ArrayBuilder<ParameterSymbol>.GetInstance(); var parameters = this.BaseMethodParameters; var inheritAttributes = InheritsBaseMethodAttributes; foreach (var p in parameters) { builder.Add(SynthesizedParameterSymbol.Create( this, this.TypeMap.SubstituteType(p.OriginalDefinition.TypeWithAnnotations), ordinal++, p.RefKind, p.Name, // the synthesized parameter doesn't need to have the same ref custom modifiers as the base refCustomModifiers: default, inheritAttributes ? p as SourceComplexParameterSymbol : null)); } var extraSynthed = ExtraSynthesizedRefParameters; if (!extraSynthed.IsDefaultOrEmpty) { foreach (var extra in extraSynthed) { builder.Add(SynthesizedParameterSymbol.Create(this, this.TypeMap.SubstituteType(extra), ordinal++, RefKind.Ref)); } } return builder.ToImmutableAndFree(); } /// <summary> /// Indicates that this method inherits attributes from the base method, its parameters, return type, and type parameters. /// </summary> internal virtual bool InheritsBaseMethodAttributes => false; public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { Debug.Assert(base.GetAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } public sealed override ImmutableArray<CSharpAttributeData> GetReturnTypeAttributes() { Debug.Assert(base.GetReturnTypeAttributes().IsEmpty); return InheritsBaseMethodAttributes ? BaseMethod.GetReturnTypeAttributes() : ImmutableArray<CSharpAttributeData>.Empty; } #nullable enable public sealed override DllImportData? GetDllImportData() => InheritsBaseMethodAttributes ? BaseMethod.GetDllImportData() : null; internal sealed override MethodImplAttributes ImplementationAttributes => InheritsBaseMethodAttributes ? BaseMethod.ImplementationAttributes : default; internal sealed override MarshalPseudoCustomAttributeData? ReturnValueMarshallingInformation => InheritsBaseMethodAttributes ? BaseMethod.ReturnValueMarshallingInformation : null; internal sealed override bool HasSpecialName => InheritsBaseMethodAttributes && BaseMethod.HasSpecialName; // Synthesized methods created from a base method with [SkipLocalsInitAttribute] will also // skip locals init where applicable, even if the synthesized method does not inherit attributes. // Note that this doesn't affect BaseMethodWrapperSymbol for example because the implementation has no locals. public sealed override bool AreLocalsZeroed => !(BaseMethod is SourceMethodSymbol sourceMethod) || sourceMethod.AreLocalsZeroed; internal sealed override bool RequiresSecurityObject => InheritsBaseMethodAttributes && BaseMethod.RequiresSecurityObject; internal sealed override bool HasDeclarativeSecurity => InheritsBaseMethodAttributes && BaseMethod.HasDeclarativeSecurity; internal sealed override IEnumerable<SecurityAttribute> GetSecurityInformation() => InheritsBaseMethodAttributes ? BaseMethod.GetSecurityInformation() : SpecializedCollections.EmptyEnumerable<SecurityAttribute>(); #nullable disable public sealed override RefKind RefKind { get { return this.BaseMethod.RefKind; } } public sealed override TypeWithAnnotations ReturnTypeWithAnnotations { get { return this.TypeMap.SubstituteType(this.BaseMethod.OriginalDefinition.ReturnTypeWithAnnotations); } } public sealed override FlowAnalysisAnnotations ReturnTypeFlowAnalysisAnnotations => BaseMethod.ReturnTypeFlowAnalysisAnnotations; public sealed override ImmutableHashSet<string> ReturnNotNullIfParameterNotNull => BaseMethod.ReturnNotNullIfParameterNotNull; public sealed override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public sealed override bool IsVararg { get { return this.BaseMethod.IsVararg; } } public sealed override string Name { get { return _name; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { if (_iteratorElementType is null) { Interlocked.CompareExchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(TypeMap.SubstituteType(BaseMethod.IteratorElementTypeWithAnnotations.Type)), null); } return _iteratorElementType.Value; } set { Debug.Assert(!value.IsDefault); Interlocked.Exchange(ref _iteratorElementType, new TypeWithAnnotations.Boxed(value)); } } internal override bool IsIterator => BaseMethod.IsIterator; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Attributes/WellKnownAttributeData/ParameterEarlyWellKnownAttributeData.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.Symbols { /// <summary> /// Information early-decoded from well-known custom attributes applied on a parameter. /// </summary> internal sealed class ParameterEarlyWellKnownAttributeData : CommonParameterEarlyWellKnownAttributeData { } }
// 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.Symbols { /// <summary> /// Information early-decoded from well-known custom attributes applied on a parameter. /// </summary> internal sealed class ParameterEarlyWellKnownAttributeData : CommonParameterEarlyWellKnownAttributeData { } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/CSharp/Portable/Structure/Providers/BlockSyntaxStructureProvider.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; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class BlockSyntaxStructureProvider : AbstractSyntaxNodeStructureProvider<BlockSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, BlockSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var parentKind = node.Parent.Kind(); // For most types of statements, just consider the block 'attached' to the // parent node. That means we'll show the parent node header when doing // things like hovering over the indent guide. // // This also works nicely as the close brace for these constructs will always // align with the start of these statements. if (IsNonBlockStatement(node.Parent) || parentKind == SyntaxKind.ElseClause) { var type = GetType(node.Parent); if (type != null) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: GetTextSpan(node), hintSpan: GetHintSpan(node), type: type, autoCollapse: parentKind == SyntaxKind.LocalFunctionStatement && node.Parent.IsParentKind(SyntaxKind.GlobalStatement))); } } // Nested blocks aren't attached to anything. Just collapse them as is. // Switch sections are also special. Say you have the following: // // case 0: // { // // } // // We don't want to consider the block parented by the case, because // that would cause us to draw the following: // // case 0: // | { // | // | } // // Which would obviously be wonky. So in this case, we just use the // spanof the block alone, without consideration for the case clause. if (parentKind is SyntaxKind.Block or SyntaxKind.SwitchSection) { var type = GetType(node.Parent); spans.Add(new BlockSpan( isCollapsible: true, textSpan: node.Span, hintSpan: node.Span, type: type)); } } private static bool IsNonBlockStatement(SyntaxNode node) => node is StatementSyntax && !node.IsKind(SyntaxKind.Block); private static TextSpan GetHintSpan(BlockSyntax node) { var parent = node.Parent; if (parent.IsKind(SyntaxKind.IfStatement) && parent.IsParentKind(SyntaxKind.ElseClause)) { parent = parent.Parent; } var start = parent.Span.Start; var end = GetEnd(node); return TextSpan.FromBounds(start, end); } private static TextSpan GetTextSpan(BlockSyntax node) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.IsKind(SyntaxKind.None)) { return node.Span; } return TextSpan.FromBounds(previousToken.Span.End, GetEnd(node)); } private static int GetEnd(BlockSyntax node) { if (node.Parent.IsKind(SyntaxKind.IfStatement)) { // For an if-statement, just collapse up to the end of the block. // We don't want collapse the whole statement just for the 'true' // portion. Also, while outlining might be ok, the Indent-Guide // would look very strange for nodes like: // // if (goo) // { // } // else // return a || // b; return node.Span.End; } else { // For all other constructs, we collapse up to the end of the parent // construct. return node.Parent.Span.End; } } private static string GetType(SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.ForStatement: return BlockTypes.Loop; case SyntaxKind.ForEachStatement: return BlockTypes.Loop; case SyntaxKind.ForEachVariableStatement: return BlockTypes.Loop; case SyntaxKind.WhileStatement: return BlockTypes.Loop; case SyntaxKind.DoStatement: return BlockTypes.Loop; case SyntaxKind.TryStatement: return BlockTypes.Statement; case SyntaxKind.CatchClause: return BlockTypes.Statement; case SyntaxKind.FinallyClause: return BlockTypes.Statement; case SyntaxKind.UnsafeStatement: return BlockTypes.Statement; case SyntaxKind.FixedStatement: return BlockTypes.Statement; case SyntaxKind.LockStatement: return BlockTypes.Statement; case SyntaxKind.UsingStatement: return BlockTypes.Statement; case SyntaxKind.IfStatement: return BlockTypes.Conditional; case SyntaxKind.ElseClause: return BlockTypes.Conditional; case SyntaxKind.SwitchSection: return BlockTypes.Conditional; case SyntaxKind.Block: return BlockTypes.Statement; case SyntaxKind.LocalFunctionStatement: return BlockTypes.Statement; } 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.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class BlockSyntaxStructureProvider : AbstractSyntaxNodeStructureProvider<BlockSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, BlockSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { var parentKind = node.Parent.Kind(); // For most types of statements, just consider the block 'attached' to the // parent node. That means we'll show the parent node header when doing // things like hovering over the indent guide. // // This also works nicely as the close brace for these constructs will always // align with the start of these statements. if (IsNonBlockStatement(node.Parent) || parentKind == SyntaxKind.ElseClause) { var type = GetType(node.Parent); if (type != null) { spans.Add(new BlockSpan( isCollapsible: true, textSpan: GetTextSpan(node), hintSpan: GetHintSpan(node), type: type, autoCollapse: parentKind == SyntaxKind.LocalFunctionStatement && node.Parent.IsParentKind(SyntaxKind.GlobalStatement))); } } // Nested blocks aren't attached to anything. Just collapse them as is. // Switch sections are also special. Say you have the following: // // case 0: // { // // } // // We don't want to consider the block parented by the case, because // that would cause us to draw the following: // // case 0: // | { // | // | } // // Which would obviously be wonky. So in this case, we just use the // spanof the block alone, without consideration for the case clause. if (parentKind is SyntaxKind.Block or SyntaxKind.SwitchSection) { var type = GetType(node.Parent); spans.Add(new BlockSpan( isCollapsible: true, textSpan: node.Span, hintSpan: node.Span, type: type)); } } private static bool IsNonBlockStatement(SyntaxNode node) => node is StatementSyntax && !node.IsKind(SyntaxKind.Block); private static TextSpan GetHintSpan(BlockSyntax node) { var parent = node.Parent; if (parent.IsKind(SyntaxKind.IfStatement) && parent.IsParentKind(SyntaxKind.ElseClause)) { parent = parent.Parent; } var start = parent.Span.Start; var end = GetEnd(node); return TextSpan.FromBounds(start, end); } private static TextSpan GetTextSpan(BlockSyntax node) { var previousToken = node.GetFirstToken().GetPreviousToken(); if (previousToken.IsKind(SyntaxKind.None)) { return node.Span; } return TextSpan.FromBounds(previousToken.Span.End, GetEnd(node)); } private static int GetEnd(BlockSyntax node) { if (node.Parent.IsKind(SyntaxKind.IfStatement)) { // For an if-statement, just collapse up to the end of the block. // We don't want collapse the whole statement just for the 'true' // portion. Also, while outlining might be ok, the Indent-Guide // would look very strange for nodes like: // // if (goo) // { // } // else // return a || // b; return node.Span.End; } else { // For all other constructs, we collapse up to the end of the parent // construct. return node.Parent.Span.End; } } private static string GetType(SyntaxNode parent) { switch (parent.Kind()) { case SyntaxKind.ForStatement: return BlockTypes.Loop; case SyntaxKind.ForEachStatement: return BlockTypes.Loop; case SyntaxKind.ForEachVariableStatement: return BlockTypes.Loop; case SyntaxKind.WhileStatement: return BlockTypes.Loop; case SyntaxKind.DoStatement: return BlockTypes.Loop; case SyntaxKind.TryStatement: return BlockTypes.Statement; case SyntaxKind.CatchClause: return BlockTypes.Statement; case SyntaxKind.FinallyClause: return BlockTypes.Statement; case SyntaxKind.UnsafeStatement: return BlockTypes.Statement; case SyntaxKind.FixedStatement: return BlockTypes.Statement; case SyntaxKind.LockStatement: return BlockTypes.Statement; case SyntaxKind.UsingStatement: return BlockTypes.Statement; case SyntaxKind.IfStatement: return BlockTypes.Conditional; case SyntaxKind.ElseClause: return BlockTypes.Conditional; case SyntaxKind.SwitchSection: return BlockTypes.Conditional; case SyntaxKind.Block: return BlockTypes.Statement; case SyntaxKind.LocalFunctionStatement: return BlockTypes.Statement; } return null; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SeparatedSyntaxList.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.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal struct SeparatedSyntaxList<TNode> : IEquatable<SeparatedSyntaxList<TNode>> where TNode : GreenNode { private readonly SyntaxList<GreenNode> _list; internal SeparatedSyntaxList(SyntaxList<GreenNode> list) { Validate(list); _list = list; } [Conditional("DEBUG")] private static void Validate(SyntaxList<GreenNode> list) { for (int i = 0; i < list.Count; i++) { var item = list.GetRequiredItem(i); if ((i & 1) == 0) { Debug.Assert(!item.IsToken, "even elements of a separated list must be nodes"); } else { Debug.Assert(item.IsToken, "odd elements of a separated list must be tokens"); } } } internal GreenNode? Node => _list.Node; public int Count { get { return (_list.Count + 1) >> 1; } } public int SeparatorCount { get { return _list.Count >> 1; } } public TNode? this[int index] { get { return (TNode?)_list[index << 1]; } } /// <summary> /// Gets the separator at the given index in this list. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public GreenNode? GetSeparator(int index) { return _list[(index << 1) + 1]; } public SyntaxList<GreenNode> GetWithSeparators() { return _list; } public static bool operator ==(in SeparatedSyntaxList<TNode> left, in SeparatedSyntaxList<TNode> right) { return left.Equals(right); } public static bool operator !=(in SeparatedSyntaxList<TNode> left, in SeparatedSyntaxList<TNode> right) { return !left.Equals(right); } public bool Equals(SeparatedSyntaxList<TNode> other) { return _list == other._list; } public override bool Equals(object? obj) { return (obj is SeparatedSyntaxList<TNode>) && Equals((SeparatedSyntaxList<TNode>)obj); } public override int GetHashCode() { return _list.GetHashCode(); } public static implicit operator SeparatedSyntaxList<GreenNode>(SeparatedSyntaxList<TNode> list) { return new SeparatedSyntaxList<GreenNode>(list.GetWithSeparators()); } #if DEBUG [Obsolete("For debugging only", true)] private TNode[] Nodes { get { int count = this.Count; TNode[] array = new TNode[count]; for (int i = 0; i < count; i++) { array[i] = this[i]!; } return array; } } #endif } }
// 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.Diagnostics; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal struct SeparatedSyntaxList<TNode> : IEquatable<SeparatedSyntaxList<TNode>> where TNode : GreenNode { private readonly SyntaxList<GreenNode> _list; internal SeparatedSyntaxList(SyntaxList<GreenNode> list) { Validate(list); _list = list; } [Conditional("DEBUG")] private static void Validate(SyntaxList<GreenNode> list) { for (int i = 0; i < list.Count; i++) { var item = list.GetRequiredItem(i); if ((i & 1) == 0) { Debug.Assert(!item.IsToken, "even elements of a separated list must be nodes"); } else { Debug.Assert(item.IsToken, "odd elements of a separated list must be tokens"); } } } internal GreenNode? Node => _list.Node; public int Count { get { return (_list.Count + 1) >> 1; } } public int SeparatorCount { get { return _list.Count >> 1; } } public TNode? this[int index] { get { return (TNode?)_list[index << 1]; } } /// <summary> /// Gets the separator at the given index in this list. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public GreenNode? GetSeparator(int index) { return _list[(index << 1) + 1]; } public SyntaxList<GreenNode> GetWithSeparators() { return _list; } public static bool operator ==(in SeparatedSyntaxList<TNode> left, in SeparatedSyntaxList<TNode> right) { return left.Equals(right); } public static bool operator !=(in SeparatedSyntaxList<TNode> left, in SeparatedSyntaxList<TNode> right) { return !left.Equals(right); } public bool Equals(SeparatedSyntaxList<TNode> other) { return _list == other._list; } public override bool Equals(object? obj) { return (obj is SeparatedSyntaxList<TNode>) && Equals((SeparatedSyntaxList<TNode>)obj); } public override int GetHashCode() { return _list.GetHashCode(); } public static implicit operator SeparatedSyntaxList<GreenNode>(SeparatedSyntaxList<TNode> list) { return new SeparatedSyntaxList<GreenNode>(list.GetWithSeparators()); } #if DEBUG [Obsolete("For debugging only", true)] private TNode[] Nodes { get { int count = this.Count; TNode[] array = new TNode[count]; for (int i = 0; i < count; i++) { array[i] = this[i]!; } return array; } } #endif } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Classification/SyntaxClassification/AbstractNameSyntaxClassifier.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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal abstract class AbstractNameSyntaxClassifier : AbstractSyntaxClassifier { protected abstract int? GetRightmostNameArity(SyntaxNode node); protected abstract bool IsParentAnAttribute(SyntaxNode node); protected ISymbol? TryGetSymbol(SyntaxNode node, SymbolInfo symbolInfo, SemanticModel semanticModel) { var symbol = symbolInfo.Symbol; if (symbol is null && symbolInfo.CandidateSymbols.Length > 0) { var firstSymbol = symbolInfo.CandidateSymbols[0]; switch (symbolInfo.CandidateReason) { case CandidateReason.NotAValue: return firstSymbol; case CandidateReason.NotCreatable: // We want to color types even if they can't be constructed. if (firstSymbol.IsConstructor() || firstSymbol is ITypeSymbol) { symbol = firstSymbol; } break; case CandidateReason.OverloadResolutionFailure: // If we couldn't bind to a constructor, still classify the type. if (firstSymbol.IsConstructor()) { symbol = firstSymbol; } break; case CandidateReason.Inaccessible: // If a constructor wasn't accessible, still classify the type if it's accessible. if (firstSymbol.IsConstructor() && semanticModel.IsAccessible(node.SpanStart, firstSymbol.ContainingType)) { symbol = firstSymbol; } break; case CandidateReason.WrongArity: var arity = GetRightmostNameArity(node); if (arity.HasValue && arity.Value == 0) { // When the user writes something like "IList" we don't want to *not* classify // just because the type bound to "IList<T>". This is also important for use // cases like "Add-using" where it can be confusing when the using is added for // "using System.Collection.Generic" but then the type name still does not classify. symbol = firstSymbol; } break; } } // Classify a reference to an attribute constructor in an attribute location // as if we were classifying the attribute type itself. if (symbol.IsConstructor() && IsParentAnAttribute(node)) { symbol = symbol.ContainingType; } return symbol; } protected static void TryClassifyStaticSymbol( ISymbol? symbol, TextSpan span, ArrayBuilder<ClassifiedSpan> result) { if (!IsStaticSymbol(symbol)) { return; } result.Add(new ClassifiedSpan(span, ClassificationTypeNames.StaticSymbol)); } protected static bool IsStaticSymbol(ISymbol? symbol) { if (symbol is null || !symbol.IsStatic) { return false; } if (symbol.IsEnumMember()) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsNamespace()) { // Namespace names are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsLocalFunction()) { // Local function names are not classified as static since the // the symbol returning true for IsStatic is an implementation detail. 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 Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal abstract class AbstractNameSyntaxClassifier : AbstractSyntaxClassifier { protected abstract int? GetRightmostNameArity(SyntaxNode node); protected abstract bool IsParentAnAttribute(SyntaxNode node); protected ISymbol? TryGetSymbol(SyntaxNode node, SymbolInfo symbolInfo, SemanticModel semanticModel) { var symbol = symbolInfo.Symbol; if (symbol is null && symbolInfo.CandidateSymbols.Length > 0) { var firstSymbol = symbolInfo.CandidateSymbols[0]; switch (symbolInfo.CandidateReason) { case CandidateReason.NotAValue: return firstSymbol; case CandidateReason.NotCreatable: // We want to color types even if they can't be constructed. if (firstSymbol.IsConstructor() || firstSymbol is ITypeSymbol) { symbol = firstSymbol; } break; case CandidateReason.OverloadResolutionFailure: // If we couldn't bind to a constructor, still classify the type. if (firstSymbol.IsConstructor()) { symbol = firstSymbol; } break; case CandidateReason.Inaccessible: // If a constructor wasn't accessible, still classify the type if it's accessible. if (firstSymbol.IsConstructor() && semanticModel.IsAccessible(node.SpanStart, firstSymbol.ContainingType)) { symbol = firstSymbol; } break; case CandidateReason.WrongArity: var arity = GetRightmostNameArity(node); if (arity.HasValue && arity.Value == 0) { // When the user writes something like "IList" we don't want to *not* classify // just because the type bound to "IList<T>". This is also important for use // cases like "Add-using" where it can be confusing when the using is added for // "using System.Collection.Generic" but then the type name still does not classify. symbol = firstSymbol; } break; } } // Classify a reference to an attribute constructor in an attribute location // as if we were classifying the attribute type itself. if (symbol.IsConstructor() && IsParentAnAttribute(node)) { symbol = symbol.ContainingType; } return symbol; } protected static void TryClassifyStaticSymbol( ISymbol? symbol, TextSpan span, ArrayBuilder<ClassifiedSpan> result) { if (!IsStaticSymbol(symbol)) { return; } result.Add(new ClassifiedSpan(span, ClassificationTypeNames.StaticSymbol)); } protected static bool IsStaticSymbol(ISymbol? symbol) { if (symbol is null || !symbol.IsStatic) { return false; } if (symbol.IsEnumMember()) { // EnumMembers are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsNamespace()) { // Namespace names are not classified as static since there is no // instance equivalent of the concept and they have their own // classification type. return false; } if (symbol.IsLocalFunction()) { // Local function names are not classified as static since the // the symbol returning true for IsStatic is an implementation detail. return false; } return true; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Remote/WellKnownSynchronizationKind.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.Serialization { // TODO: Kind might not actually needed. see whether we can get rid of this internal enum WellKnownSynchronizationKind { Null, SolutionState, ProjectState, DocumentState, ChecksumCollection, SolutionAttributes, ProjectAttributes, DocumentAttributes, SourceGeneratedDocumentIdentity, CompilationOptions, ParseOptions, ProjectReference, MetadataReference, AnalyzerReference, SourceText, OptionSet, SerializableSourceText, // SyntaxTreeIndex, SymbolTreeInfo, ProjectReferenceChecksumCollection, MetadataReferenceChecksumCollection, AnalyzerReferenceChecksumCollection, TextDocumentChecksumCollection, DocumentChecksumCollection, AnalyzerConfigDocumentChecksumCollection, ProjectChecksumCollection, SolutionStateChecksums, ProjectStateChecksums, DocumentStateChecksums, } }
// 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.Serialization { // TODO: Kind might not actually needed. see whether we can get rid of this internal enum WellKnownSynchronizationKind { Null, SolutionState, ProjectState, DocumentState, ChecksumCollection, SolutionAttributes, ProjectAttributes, DocumentAttributes, SourceGeneratedDocumentIdentity, CompilationOptions, ParseOptions, ProjectReference, MetadataReference, AnalyzerReference, SourceText, OptionSet, SerializableSourceText, // SyntaxTreeIndex, SymbolTreeInfo, ProjectReferenceChecksumCollection, MetadataReferenceChecksumCollection, AnalyzerReferenceChecksumCollection, TextDocumentChecksumCollection, DocumentChecksumCollection, AnalyzerConfigDocumentChecksumCollection, ProjectChecksumCollection, SolutionStateChecksums, ProjectStateChecksums, DocumentStateChecksums, } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/VisualBasic/Portable/Structure/Providers/StringLiteralExpressionStructureProvider.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 StringLiteralExpressionStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of LiteralExpressionSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As LiteralExpressionSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) If node.IsKind(SyntaxKind.StringLiteralExpression) AndAlso Not node.ContainsDiagnostics Then spans.Add(New BlockSpan( type:=BlockTypes.Expression, isCollapsible:=True, textSpan:=node.Span, autoCollapse:=True, isDefaultCollapsed:=False)) 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 StringLiteralExpressionStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of LiteralExpressionSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, node As LiteralExpressionSyntax, ByRef spans As TemporaryArray(Of BlockSpan), optionProvider As BlockStructureOptionProvider, cancellationToken As CancellationToken) If node.IsKind(SyntaxKind.StringLiteralExpression) AndAlso Not node.ContainsDiagnostics Then spans.Add(New BlockSpan( type:=BlockTypes.Expression, isCollapsible:=True, textSpan:=node.Span, autoCollapse:=True, isDefaultCollapsed:=False)) End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/CSharp/Portable/Simplification/Reducers/AbstractCSharpReducer.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.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal abstract partial class AbstractCSharpReducer : AbstractReducer { protected AbstractCSharpReducer(ObjectPool<IReductionRewriter> pool) : base(pool) { } } }
// 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.PooledObjects; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal abstract partial class AbstractCSharpReducer : AbstractReducer { protected AbstractCSharpReducer(ObjectPool<IReductionRewriter> pool) : base(pool) { } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Remote/RemoteServiceCallbackId.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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { [DataContract] internal readonly struct RemoteServiceCallbackId : IEquatable<RemoteServiceCallbackId> { [DataMember(Order = 0)] public readonly int Id; public RemoteServiceCallbackId(int id) => Id = id; public override bool Equals(object? obj) => obj is RemoteServiceCallbackId id && Equals(id); public bool Equals(RemoteServiceCallbackId other) => Id == other.Id; public override int GetHashCode() => Id; public static bool operator ==(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => left.Equals(right); public static bool operator !=(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => !(left == right); } }
// 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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { [DataContract] internal readonly struct RemoteServiceCallbackId : IEquatable<RemoteServiceCallbackId> { [DataMember(Order = 0)] public readonly int Id; public RemoteServiceCallbackId(int id) => Id = id; public override bool Equals(object? obj) => obj is RemoteServiceCallbackId id && Equals(id); public bool Equals(RemoteServiceCallbackId other) => Id == other.Id; public override int GetHashCode() => Id; public static bool operator ==(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => left.Equals(right); public static bool operator !=(RemoteServiceCallbackId left, RemoteServiceCallbackId right) => !(left == right); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Server/VBCSCompiler/VBCSCompiler.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.CommandLine; using System; using System.Collections.Specialized; using System.IO; namespace Microsoft.CodeAnalysis.CompilerServer { internal static class VBCSCompiler { public static int Main(string[] args) { using var logger = new CompilerServerLogger("VBCSCompiler"); NameValueCollection appSettings; try { #if BOOTSTRAP ExitingTraceListener.Install(logger); #endif #if NET472 appSettings = System.Configuration.ConfigurationManager.AppSettings; #else // Do not use AppSettings on non-desktop platforms appSettings = new NameValueCollection(); #endif } catch (Exception ex) { // It is possible for AppSettings to throw when the application or machine configuration // is corrupted. This should not prevent the server from starting, but instead just revert // to the default configuration. appSettings = new NameValueCollection(); logger.LogException(ex, "Error loading application settings"); } try { var controller = new BuildServerController(appSettings, logger); return controller.Run(args); } catch (Exception e) { // Assume the exception was the result of a missing compiler assembly. logger.LogException(e, "Cannot start server"); } return CommonCompiler.Failed; } } }
// 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.CommandLine; using System; using System.Collections.Specialized; using System.IO; namespace Microsoft.CodeAnalysis.CompilerServer { internal static class VBCSCompiler { public static int Main(string[] args) { using var logger = new CompilerServerLogger("VBCSCompiler"); NameValueCollection appSettings; try { #if BOOTSTRAP ExitingTraceListener.Install(logger); #endif #if NET472 appSettings = System.Configuration.ConfigurationManager.AppSettings; #else // Do not use AppSettings on non-desktop platforms appSettings = new NameValueCollection(); #endif } catch (Exception ex) { // It is possible for AppSettings to throw when the application or machine configuration // is corrupted. This should not prevent the server from starting, but instead just revert // to the default configuration. appSettings = new NameValueCollection(); logger.LogException(ex, "Error loading application settings"); } try { var controller = new BuildServerController(appSettings, logger); return controller.Run(args); } catch (Exception e) { // Assume the exception was the result of a missing compiler assembly. logger.LogException(e, "Cannot start server"); } return CommonCompiler.Failed; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/AddImport/References/SymbolReference.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private abstract partial class SymbolReference : Reference { public readonly SymbolResult<INamespaceOrTypeSymbol> SymbolResult; protected abstract bool ShouldAddWithExistingImport(Document document); public SymbolReference( AbstractAddImportFeatureService<TSimpleNameSyntax> provider, SymbolResult<INamespaceOrTypeSymbol> symbolResult) : base(provider, new SearchResult(symbolResult)) { SymbolResult = symbolResult; } protected abstract ImmutableArray<string> GetTags(Document document); public override bool Equals(object obj) { var equals = base.Equals(obj); if (!equals) { return false; } var name1 = SymbolResult.DesiredName; var name2 = (obj as SymbolReference)?.SymbolResult.DesiredName; return StringComparer.Ordinal.Equals(name1, name2); } public override int GetHashCode() => Hash.Combine(SymbolResult.DesiredName, base.GetHashCode()); private async Task<ImmutableArray<TextChange>> GetTextChangesAsync( Document document, SyntaxNode contextNode, bool allowInHiddenRegions, bool hasExistingImport, CancellationToken cancellationToken) { // Defer to the language to add the actual import/using. if (hasExistingImport) { return ImmutableArray<TextChange>.Empty; } (var newContextNode, var newDocument) = await ReplaceNameNodeAsync( contextNode, document, cancellationToken).ConfigureAwait(false); var updatedDocument = await provider.AddImportAsync( newContextNode, SymbolResult.Symbol, newDocument, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); var cleanedDocument = await CodeAction.CleanupDocumentAsync( updatedDocument, cancellationToken).ConfigureAwait(false); var textChanges = await cleanedDocument.GetTextChangesAsync( document, cancellationToken).ConfigureAwait(false); return textChanges.ToImmutableArray(); } public sealed override async Task<AddImportFixData> TryGetFixDataAsync( Document document, SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var (description, hasExistingImport) = GetDescription(document, options, node, semanticModel, cancellationToken); if (description == null) { return null; } if (hasExistingImport && !ShouldAddWithExistingImport(document)) { return null; } var isFuzzy = !SearchResult.DesiredNameMatchesSourceName(document); var tags = GetTags(document); if (isFuzzy) { // The name is going to change. Make it clear in the description that this is // going to happen. description = $"{SearchResult.DesiredName} - {description}"; // if we were a fuzzy match, and we didn't have any glyph to show, then add the // namespace-glyph to this item. This helps indicate that not only are we fixing // the spelling of this name we are *also* adding a namespace. This helps as we // have gotten feedback in the past that the 'using/import' addition was // unexpected. if (tags.IsDefaultOrEmpty) { tags = WellKnownTagArrays.Namespace; } } var textChanges = await GetTextChangesAsync( document, node, allowInHiddenRegions, hasExistingImport, cancellationToken).ConfigureAwait(false); return GetFixData( document, textChanges, description, tags, GetPriority(document)); } protected abstract AddImportFixData GetFixData( Document document, ImmutableArray<TextChange> textChanges, string description, ImmutableArray<string> tags, CodeActionPriority priority); protected abstract CodeActionPriority GetPriority(Document document); protected virtual (string description, bool hasExistingImport) GetDescription( Document document, OptionSet options, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) { return provider.GetDescription( document, options, SymbolResult.Symbol, semanticModel, node, 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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Tags; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private abstract partial class SymbolReference : Reference { public readonly SymbolResult<INamespaceOrTypeSymbol> SymbolResult; protected abstract bool ShouldAddWithExistingImport(Document document); public SymbolReference( AbstractAddImportFeatureService<TSimpleNameSyntax> provider, SymbolResult<INamespaceOrTypeSymbol> symbolResult) : base(provider, new SearchResult(symbolResult)) { SymbolResult = symbolResult; } protected abstract ImmutableArray<string> GetTags(Document document); public override bool Equals(object obj) { var equals = base.Equals(obj); if (!equals) { return false; } var name1 = SymbolResult.DesiredName; var name2 = (obj as SymbolReference)?.SymbolResult.DesiredName; return StringComparer.Ordinal.Equals(name1, name2); } public override int GetHashCode() => Hash.Combine(SymbolResult.DesiredName, base.GetHashCode()); private async Task<ImmutableArray<TextChange>> GetTextChangesAsync( Document document, SyntaxNode contextNode, bool allowInHiddenRegions, bool hasExistingImport, CancellationToken cancellationToken) { // Defer to the language to add the actual import/using. if (hasExistingImport) { return ImmutableArray<TextChange>.Empty; } (var newContextNode, var newDocument) = await ReplaceNameNodeAsync( contextNode, document, cancellationToken).ConfigureAwait(false); var updatedDocument = await provider.AddImportAsync( newContextNode, SymbolResult.Symbol, newDocument, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); var cleanedDocument = await CodeAction.CleanupDocumentAsync( updatedDocument, cancellationToken).ConfigureAwait(false); var textChanges = await cleanedDocument.GetTextChangesAsync( document, cancellationToken).ConfigureAwait(false); return textChanges.ToImmutableArray(); } public sealed override async Task<AddImportFixData> TryGetFixDataAsync( Document document, SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken) { var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var (description, hasExistingImport) = GetDescription(document, options, node, semanticModel, cancellationToken); if (description == null) { return null; } if (hasExistingImport && !ShouldAddWithExistingImport(document)) { return null; } var isFuzzy = !SearchResult.DesiredNameMatchesSourceName(document); var tags = GetTags(document); if (isFuzzy) { // The name is going to change. Make it clear in the description that this is // going to happen. description = $"{SearchResult.DesiredName} - {description}"; // if we were a fuzzy match, and we didn't have any glyph to show, then add the // namespace-glyph to this item. This helps indicate that not only are we fixing // the spelling of this name we are *also* adding a namespace. This helps as we // have gotten feedback in the past that the 'using/import' addition was // unexpected. if (tags.IsDefaultOrEmpty) { tags = WellKnownTagArrays.Namespace; } } var textChanges = await GetTextChangesAsync( document, node, allowInHiddenRegions, hasExistingImport, cancellationToken).ConfigureAwait(false); return GetFixData( document, textChanges, description, tags, GetPriority(document)); } protected abstract AddImportFixData GetFixData( Document document, ImmutableArray<TextChange> textChanges, string description, ImmutableArray<string> tags, CodeActionPriority priority); protected abstract CodeActionPriority GetPriority(Document document); protected virtual (string description, bool hasExistingImport) GetDescription( Document document, OptionSet options, SyntaxNode node, SemanticModel semanticModel, CancellationToken cancellationToken) { return provider.GetDescription( document, options, SymbolResult.Symbol, semanticModel, node, cancellationToken); } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/Symbols/IAliasSymbol.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 { /// <summary> /// Represents a using alias (Imports alias in Visual Basic). /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IAliasSymbol : ISymbol { /// <summary> /// Gets the <see cref="INamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> INamespaceOrTypeSymbol Target { 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a using alias (Imports alias in Visual Basic). /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IAliasSymbol : ISymbol { /// <summary> /// Gets the <see cref="INamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> INamespaceOrTypeSymbol Target { get; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/SourceGeneration/Nodes/InputNode.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.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Input nodes are the 'root' nodes in the graph, and get their values from the inputs of the driver state table /// </summary> /// <typeparam name="T">The type of the input</typeparam> internal sealed class InputNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, ImmutableArray<T>> _getInput; private readonly Action<IIncrementalGeneratorOutputNode> _registerOutput; private readonly IEqualityComparer<T> _comparer; public InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput) : this(getInput, registerOutput: null, comparer: null) { } private InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput, Action<IIncrementalGeneratorOutputNode>? registerOutput, IEqualityComparer<T>? comparer = null) { _getInput = getInput; _comparer = comparer ?? EqualityComparer<T>.Default; _registerOutput = registerOutput ?? (o => throw ExceptionUtilities.Unreachable); } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { var inputItems = _getInput(graphState); // create a mutable hashset of the new items we can check against HashSet<T> itemsSet = new HashSet<T>(); foreach (var item in inputItems) { var added = itemsSet.Add(item); Debug.Assert(added); } var builder = previousTable.ToBuilder(); // for each item in the previous table, check if its still in the new items int itemIndex = 0; foreach ((var oldItem, _) in previousTable) { if (itemsSet.Remove(oldItem)) { // we're iterating the table, so know that it has entries var usedCache = builder.TryUseCachedEntries(); Debug.Assert(usedCache); } else if (inputItems.Length == previousTable.Count) { // When the number of items matches the previous iteration, we use a heuristic to mark the input as modified // This allows us to correctly 'replace' items even when they aren't actually the same. In the case that the // item really isn't modified, but a new item, we still function correctly as we mostly treat them the same, // but will perform an extra comparison that is omitted in the pure 'added' case. var modified = builder.TryModifyEntry(inputItems[itemIndex], _comparer); Debug.Assert(modified); itemsSet.Remove(inputItems[itemIndex]); } else { builder.RemoveEntries(); } itemIndex++; } // any remaining new items are added foreach (var newItem in itemsSet) { builder.AddEntry(newItem, EntryState.Added); } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new InputNode<T>(_getInput, _registerOutput, comparer); public InputNode<T> WithRegisterOutput(Action<IIncrementalGeneratorOutputNode> registerOutput) => new InputNode<T>(_getInput, registerOutput, _comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutput(output); } }
// 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.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Input nodes are the 'root' nodes in the graph, and get their values from the inputs of the driver state table /// </summary> /// <typeparam name="T">The type of the input</typeparam> internal sealed class InputNode<T> : IIncrementalGeneratorNode<T> { private readonly Func<DriverStateTable.Builder, ImmutableArray<T>> _getInput; private readonly Action<IIncrementalGeneratorOutputNode> _registerOutput; private readonly IEqualityComparer<T> _comparer; public InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput) : this(getInput, registerOutput: null, comparer: null) { } private InputNode(Func<DriverStateTable.Builder, ImmutableArray<T>> getInput, Action<IIncrementalGeneratorOutputNode>? registerOutput, IEqualityComparer<T>? comparer = null) { _getInput = getInput; _comparer = comparer ?? EqualityComparer<T>.Default; _registerOutput = registerOutput ?? (o => throw ExceptionUtilities.Unreachable); } public NodeStateTable<T> UpdateStateTable(DriverStateTable.Builder graphState, NodeStateTable<T> previousTable, CancellationToken cancellationToken) { var inputItems = _getInput(graphState); // create a mutable hashset of the new items we can check against HashSet<T> itemsSet = new HashSet<T>(); foreach (var item in inputItems) { var added = itemsSet.Add(item); Debug.Assert(added); } var builder = previousTable.ToBuilder(); // for each item in the previous table, check if its still in the new items int itemIndex = 0; foreach ((var oldItem, _) in previousTable) { if (itemsSet.Remove(oldItem)) { // we're iterating the table, so know that it has entries var usedCache = builder.TryUseCachedEntries(); Debug.Assert(usedCache); } else if (inputItems.Length == previousTable.Count) { // When the number of items matches the previous iteration, we use a heuristic to mark the input as modified // This allows us to correctly 'replace' items even when they aren't actually the same. In the case that the // item really isn't modified, but a new item, we still function correctly as we mostly treat them the same, // but will perform an extra comparison that is omitted in the pure 'added' case. var modified = builder.TryModifyEntry(inputItems[itemIndex], _comparer); Debug.Assert(modified); itemsSet.Remove(inputItems[itemIndex]); } else { builder.RemoveEntries(); } itemIndex++; } // any remaining new items are added foreach (var newItem in itemsSet) { builder.AddEntry(newItem, EntryState.Added); } return builder.ToImmutableAndFree(); } public IIncrementalGeneratorNode<T> WithComparer(IEqualityComparer<T> comparer) => new InputNode<T>(_getInput, _registerOutput, comparer); public InputNode<T> WithRegisterOutput(Action<IIncrementalGeneratorOutputNode> registerOutput) => new InputNode<T>(_getInput, registerOutput, _comparer); public void RegisterOutput(IIncrementalGeneratorOutputNode output) => _registerOutput(output); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/CodeRefactorings/WorkspaceServices/ISymbolRenamedCodeActionOperationFactoryWorkspaceService.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.CodeActions.WorkspaceServices { internal interface ISymbolRenamedCodeActionOperationFactoryWorkspaceService : IWorkspaceService { CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution); } }
// 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.CodeActions.WorkspaceServices { internal interface ISymbolRenamedCodeActionOperationFactoryWorkspaceService : IWorkspaceService { CodeActionOperation CreateSymbolRenamedOperation(ISymbol symbol, string newName, Solution startingSolution, Solution updatedSolution); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VSPackage.resx"> <body> <trans-unit id="110"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> <trans-unit id="112"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VSPackage.resx"> <body> <trans-unit id="110"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> <trans-unit id="112"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Analyzers/CSharp/Analyzers/CSharpAnalyzers.shproj
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <ProjectGuid>{EAFFCA55-335B-4860-BB99-EFCEAD123199}</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="CSharpAnalyzers.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup Label="Globals"> <ProjectGuid>{EAFFCA55-335B-4860-BB99-EFCEAD123199}</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" /> <PropertyGroup /> <Import Project="CSharpAnalyzers.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> </Project>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/CodeStyle/VisualBasic/Analyzers/xlf/VBCodeStyleResources.fr.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../VBCodeStyleResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Supprimer cette valeur quand une autre est ajoutée.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="fr" original="../VBCodeStyleResources.resx"> <body> <trans-unit id="EmptyResource"> <source>Remove this value when another is added.</source> <target state="translated">Supprimer cette valeur quand une autre est ajoutée.</target> <note>https://github.com/Microsoft/msbuild/issues/1661</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/VisualBasicTriviaFormatter.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 Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class VisualBasicTriviaFormatter Inherits AbstractTriviaFormatter Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia("_") Private _newLine As SyntaxTrivia Private _succeeded As Boolean = True Public Sub New(context As FormattingContext, formattingRules As ChainedFormattingRules, token1 As SyntaxToken, token2 As SyntaxToken, originalString As String, lineBreaks As Integer, spaces As Integer) MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces) End Sub Protected Overrides Function Succeeded() As Boolean Return _succeeded End Function Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.WhitespaceTrivia End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsWhitespace(ch As Char) As Boolean Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch) End Function Protected Overrides Function IsNewLine(ch As Char) As Boolean Return SyntaxFacts.IsNewLine(ch) End Function Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Protected Overrides Function CreateEndOfLine() As SyntaxTrivia If _newLine = Nothing Then Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine) _newLine = SyntaxFactory.EndOfLine(text) End If Return _newLine End Function Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule ' line continuation If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1) End If If IsStartOrEndOfFile(trivia1, trivia2) Then Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0) End If ' :: case If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : after : token If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : [token] If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.ColonTrivia OrElse trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If ' [trivia] [whitespace] [token] case If trivia2.Kind = SyntaxKind.None Then Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing If insertNewLine Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' preprocessor case If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then ' if this is the first line of the file, don't put extra line 1 Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None) Dim lines = If(firstLine, 0, 1) Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0) End If ' comment before a Case Statement case If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then Return LineColumnRule.Preserve End If ' comment case If trivia2.Kind = SyntaxKind.CommentTrivia OrElse trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then ' [token] [whitespace] [trivia] case If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' skipped tokens If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then _succeeded = False End If Return LineColumnRule.Preserve End Function Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean Return False End Function Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then trivia = FormatLineContinuationTrivia(trivia) End If changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then Dim lineContinuation = FormatLineContinuationTrivia(trivia) If trivia <> lineContinuation Then changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString())) End If Return GetLineColumnDelta(lineColumn, lineContinuation) End If Return GetLineColumnDelta(lineColumn, trivia) End Function Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then Return _lineContinuationTrivia End If Return trivia End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) changes.Add(formattedTrivia) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) changes.Add(docComment) Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia( trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) If result.GetTextChanges(cancellationToken).Count = 0 Then Return GetLineColumnDelta(lineColumn, trivia) End If changes.AddRange(result.GetTextChanges(cancellationToken)) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) If docComment <> trivia Then changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString())) End If Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart) Dim text = trivia.ToFullString() ' When the doc comment is parsed from source, even if it is only one ' line long, the end-of-line will get included into the trivia text. ' If the doc comment was parsed from a text fragment, there may not be ' an end-of-line at all. We need to trim the end before we check the ' number of line breaks in the text. #If NETCOREAPP Then Dim textWithoutFinalNewLine = text.TrimEnd() #Else Dim textWithoutFinalNewLine = text.TrimEnd(Nothing) #End If If Not textWithoutFinalNewLine.ContainsLineBreak() Then Return trivia End If Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment( forceIndentation:=True, indentation:=indentation, indentationDelta:=0, useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs), tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize), newLine:=Me.Options.GetOption(FormattingOptions2.NewLine)) If text = singlelineDocComments Then Return trivia End If Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments) Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1) Return singlelineDocCommentTrivia.ElementAt(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 System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting Partial Friend Class VisualBasicTriviaFormatter Inherits AbstractTriviaFormatter Private ReadOnly _lineContinuationTrivia As SyntaxTrivia = SyntaxFactory.LineContinuationTrivia("_") Private _newLine As SyntaxTrivia Private _succeeded As Boolean = True Public Sub New(context As FormattingContext, formattingRules As ChainedFormattingRules, token1 As SyntaxToken, token2 As SyntaxToken, originalString As String, lineBreaks As Integer, spaces As Integer) MyBase.New(context, formattingRules, token1, token2, originalString, lineBreaks, spaces) End Sub Protected Overrides Function Succeeded() As Boolean Return _succeeded End Function Protected Overrides Function IsWhitespace(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.WhitespaceTrivia End Function Protected Overrides Function IsEndOfLine(trivia As SyntaxTrivia) As Boolean Return trivia.RawKind = SyntaxKind.EndOfLineTrivia End Function Protected Overrides Function IsWhitespace(ch As Char) As Boolean Return Char.IsWhiteSpace(ch) OrElse SyntaxFacts.IsWhitespace(ch) End Function Protected Overrides Function IsNewLine(ch As Char) As Boolean Return SyntaxFacts.IsNewLine(ch) End Function Protected Overrides Function CreateWhitespace(text As String) As SyntaxTrivia Return SyntaxFactory.Whitespace(text) End Function Protected Overrides Function CreateEndOfLine() As SyntaxTrivia If _newLine = Nothing Then Dim text = Me.Context.Options.GetOption(FormattingOptions2.NewLine) _newLine = SyntaxFactory.EndOfLine(text) End If Return _newLine End Function Protected Overrides Function GetLineColumnRuleBetween(trivia1 As SyntaxTrivia, existingWhitespaceBetween As LineColumnDelta, implicitLineBreak As Boolean, trivia2 As SyntaxTrivia) As LineColumnRule ' line continuation If trivia2.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.ForceSpacesOrUseAbsoluteIndentation(spacesOrIndentation:=1) End If If IsStartOrEndOfFile(trivia1, trivia2) Then Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines:=0, indentation:=0) End If ' :: case If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : after : token If Token1.Kind = SyntaxKind.ColonToken AndAlso trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=0) End If ' : [token] If trivia1.Kind = SyntaxKind.ColonTrivia AndAlso trivia2.Kind = 0 AndAlso Token2.Kind <> SyntaxKind.None AndAlso Token2.Kind <> SyntaxKind.EndOfFileToken Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.ColonTrivia OrElse trivia2.Kind = SyntaxKind.ColonTrivia Then Return LineColumnRule.ForceSpacesOrUseDefaultIndentation(spaces:=1) End If ' [trivia] [whitespace] [token] case If trivia2.Kind = SyntaxKind.None Then Dim insertNewLine = Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing If insertNewLine Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' preprocessor case If SyntaxFacts.IsPreprocessorDirective(trivia2.Kind) Then ' if this is the first line of the file, don't put extra line 1 Dim firstLine = (trivia1.RawKind = SyntaxKind.None) AndAlso (Token1.Kind = SyntaxKind.None) Dim lines = If(firstLine, 0, 1) Return LineColumnRule.PreserveLinesWithAbsoluteIndentation(lines, indentation:=0) End If ' comment before a Case Statement case If trivia2.Kind = SyntaxKind.CommentTrivia AndAlso Token2.Kind = SyntaxKind.CaseKeyword AndAlso Token2.Parent.IsKind(SyntaxKind.CaseStatement) Then Return LineColumnRule.Preserve End If ' comment case If trivia2.Kind = SyntaxKind.CommentTrivia OrElse trivia2.Kind = SyntaxKind.DocumentationCommentTrivia Then ' [token] [whitespace] [trivia] case If Me.Token1.IsLastTokenOfStatementWithEndOfLine() AndAlso trivia1.Kind = SyntaxKind.None Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If trivia1.Kind = SyntaxKind.LineContinuationTrivia Then Return LineColumnRule.PreserveSpacesOrUseDefaultIndentation(spaces:=1) End If If Me.FormattingRules.GetAdjustNewLinesOperation(Me.Token1, Me.Token2) IsNot Nothing Then Return LineColumnRule.PreserveLinesWithDefaultIndentation(lines:=0) End If Return LineColumnRule.PreserveLinesWithGivenIndentation(lines:=0) End If ' skipped tokens If trivia2.Kind = SyntaxKind.SkippedTokensTrivia Then _succeeded = False End If Return LineColumnRule.Preserve End Function Protected Overrides Function ContainsImplicitLineBreak(syntaxTrivia As SyntaxTrivia) As Boolean Return False End Function Private Function IsStartOrEndOfFile(trivia1 As SyntaxTrivia, trivia2 As SyntaxTrivia) As Boolean Return (Token1.Kind = 0 OrElse Token2.Kind = 0) AndAlso (trivia1.Kind = 0 OrElse trivia2.Kind = 0) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then trivia = FormatLineContinuationTrivia(trivia) End If changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End Function Protected Overloads Overrides Function Format(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.HasStructure Then Return FormatStructuredTrivia(lineColumn, trivia, changes, cancellationToken) End If If trivia.Kind = SyntaxKind.LineContinuationTrivia Then Dim lineContinuation = FormatLineContinuationTrivia(trivia) If trivia <> lineContinuation Then changes.Add(New TextChange(trivia.FullSpan, lineContinuation.ToFullString())) End If Return GetLineColumnDelta(lineColumn, lineContinuation) End If Return GetLineColumnDelta(lineColumn, trivia) End Function Private Function FormatLineContinuationTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.ToFullString() <> _lineContinuationTrivia.ToFullString() Then Return _lineContinuationTrivia End If Return trivia End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of SyntaxTrivia), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False changes.Add(trivia) Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia(trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) changes.Add(formattedTrivia) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) changes.Add(docComment) Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatStructuredTrivia(lineColumn As LineColumn, trivia As SyntaxTrivia, changes As ArrayBuilder(Of TextChange), cancellationToken As CancellationToken) As LineColumnDelta If trivia.Kind = SyntaxKind.SkippedTokensTrivia Then ' don't touch anything if it contains skipped tokens _succeeded = False Return GetLineColumnDelta(lineColumn, trivia) End If ' TODO : make document comment to be formatted by structured trivia formatter as well. If trivia.Kind <> SyntaxKind.DocumentationCommentTrivia Then Dim result = VisualBasicStructuredTriviaFormatEngine.FormatTrivia( trivia, Me.InitialLineColumn.Column, Me.Options, Me.FormattingRules, cancellationToken) If result.GetTextChanges(cancellationToken).Count = 0 Then Return GetLineColumnDelta(lineColumn, trivia) End If changes.AddRange(result.GetTextChanges(cancellationToken)) Dim formattedTrivia = SyntaxFactory.Trivia(DirectCast(result.GetFormattedRoot(cancellationToken), StructuredTriviaSyntax)) Return GetLineColumnDelta(lineColumn, formattedTrivia) End If Dim docComment = FormatDocumentComment(lineColumn, trivia) If docComment <> trivia Then changes.Add(New TextChange(trivia.FullSpan, docComment.ToFullString())) End If Return GetLineColumnDelta(lineColumn, docComment) End Function Private Function FormatDocumentComment(lineColumn As LineColumn, trivia As SyntaxTrivia) As SyntaxTrivia Dim indentation = Me.Context.GetBaseIndentation(trivia.SpanStart) Dim text = trivia.ToFullString() ' When the doc comment is parsed from source, even if it is only one ' line long, the end-of-line will get included into the trivia text. ' If the doc comment was parsed from a text fragment, there may not be ' an end-of-line at all. We need to trim the end before we check the ' number of line breaks in the text. #If NETCOREAPP Then Dim textWithoutFinalNewLine = text.TrimEnd() #Else Dim textWithoutFinalNewLine = text.TrimEnd(Nothing) #End If If Not textWithoutFinalNewLine.ContainsLineBreak() Then Return trivia End If Dim singlelineDocComments = text.ReindentStartOfXmlDocumentationComment( forceIndentation:=True, indentation:=indentation, indentationDelta:=0, useTab:=Me.Options.GetOption(FormattingOptions2.UseTabs), tabSize:=Me.Options.GetOption(FormattingOptions2.TabSize), newLine:=Me.Options.GetOption(FormattingOptions2.NewLine)) If text = singlelineDocComments Then Return trivia End If Dim singlelineDocCommentTrivia = SyntaxFactory.ParseLeadingTrivia(singlelineDocComments) Contract.ThrowIfFalse(singlelineDocCommentTrivia.Count = 1) Return singlelineDocCommentTrivia.ElementAt(0) End Function End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Def/xlf/Commands.vsct.ko.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../Commands.vsct"> <body> <trans-unit id="ECMD_RUNFXCOPSEL|ButtonText"> <source>Run Code &amp;Analysis on Selection</source> <target state="translated">선택 영역에 대해 코드 분석 실행(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText"> <source>&amp;Current Document</source> <target state="translated">현재 문서(&amp;C)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName"> <source>AnalysisScopeCurrentDocument</source> <target state="translated">AnalysisScopeCurrentDocument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName"> <source>Current Document</source> <target state="translated">현재 문서</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">기본값(&amp;D)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|CommandName"> <source>AnalysisScopeDefault</source> <target state="translated">AnalysisScopeDefault</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName"> <source>Default</source> <target state="translated">기본</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText"> <source>&amp;Entire Solution</source> <target state="translated">전체 솔루션(&amp;E)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName"> <source>AnalysisScopeEntireSolution</source> <target state="translated">AnalysisScopeEntireSolution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName"> <source>Entire Solution</source> <target state="translated">전체 솔루션</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText"> <source>&amp;Open Documents</source> <target state="translated">열린 문서(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName"> <source>AnalysisScopeOpenDocuments</source> <target state="translated">AnalysisScopeOpenDocuments</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName"> <source>Open Documents</source> <target state="translated">문서 열기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText"> <source>Set Analysis Scope</source> <target state="translated">분석 범위 설정</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|CommandName"> <source>Set Analysis Scope</source> <target state="translated">분석 범위 설정</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName"> <source>SetAnalysisScope</source> <target state="translated">SetAnalysisScope</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText"> <source>Sort &amp;Usings</source> <target state="translated">Using 정렬(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName"> <source>SortUsings</source> <target state="translated">SortUsings</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">제거 및 정렬(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">제거 및 정렬(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|CommandName"> <source>ErrorListSetSeverityDefault</source> <target state="new">ErrorListSetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="new">&amp;Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|CommandName"> <source>ErrorListSetSeverityError</source> <target state="new">ErrorListSetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="new">Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="new">&amp;Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|CommandName"> <source>ErrorListSetSeverityHidden</source> <target state="new">ErrorListSetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="new">Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="new">&amp;Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|CommandName"> <source>ErrorListSetSeverityInfo</source> <target state="new">ErrorListSetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="new">Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="new">&amp;None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|CommandName"> <source>ErrorListSetSeverityNone</source> <target state="new">ErrorListSetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="new">None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="new">&amp;Warning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|CommandName"> <source>ErrorListSetSeverityWarning</source> <target state="new">ErrorListSetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="new">Warning</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText"> <source>&amp;Analyzer...</source> <target state="translated">분석기(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">분석기 추가(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">분석기 추가(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">분석기 추가(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|ButtonText"> <source>&amp;Remove</source> <target state="translated">제거(&amp;R)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|CommandName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|ButtonText"> <source>&amp;Open Active Rule Set</source> <target state="translated">활성 규칙 집합 열기(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|LocCanonicalName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|CommandName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|ButtonText"> <source>Remove Unused References...</source> <target state="translated">사용하지 않는 참조 제거</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|CommandName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText"> <source>Run C&amp;ode Analysis</source> <target state="translated">코드 분석 실행(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|CommandName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">기본값(&amp;D)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="translated">기본값</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|CommandName"> <source>SetSeverityDefault</source> <target state="translated">SetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="translated">오류(&amp;E)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="translated">오류</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|CommandName"> <source>SetSeverityError</source> <target state="translated">SetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="translated">경고(&amp;W)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="translated">경고</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|CommandName"> <source>SetSeverityWarning</source> <target state="translated">SetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="translated">제안(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="translated">제안</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|CommandName"> <source>SetSeverityInfo</source> <target state="translated">SetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="translated">자동(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="translated">자동</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|CommandName"> <source>SetSeverityHidden</source> <target state="translated">SetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="translated">없음(&amp;N)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="translated">None</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|CommandName"> <source>SetSeverityNone</source> <target state="translated">SetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText"> <source>&amp;View Help...</source> <target state="translated">도움말 보기(&amp;V)...</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|ButtonText"> <source>&amp;Set as Active Rule Set</source> <target state="translated">활성 규칙 집합으로 설정(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|CommandName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|ButtonText"> <source>Remove&amp; Suppression(s)</source> <target state="translated">비표시 오류(Suppression) 제거(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|LocCanonicalName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|CommandName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|ButtonText"> <source>In &amp;Source</source> <target state="translated">소스(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|CommandName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText"> <source>In&amp; Suppression File</source> <target state="translated">비표시 오류(Suppression) 파일(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|ButtonText"> <source>Go To Implementation</source> <target state="translated">구현으로 이동</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|LocCanonicalName"> <source>GoToImplementation</source> <target state="translated">GoToImplementation</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|CommandName"> <source>Go To Implementation</source> <target state="translated">구현으로 이동</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|ButtonText"> <source>Sync &amp;Namespaces</source> <target state="translated">네임스페이스 동기화(&amp;N)</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|CommandName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|LocCanonicalName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|ButtonText"> <source>Track Value Source</source> <target state="translated">추적 값 원본</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|CommandName"> <source>ShowValueTrackingCommandName</source> <target state="translated">ShowValueTrackingCommandName</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|LocCanonicalName"> <source>ViewEditorConfigSettings</source> <target state="translated">ViewEditorConfigSettings</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Initialize Interactive with Project</source> <target state="translated">프로젝트에서 Interactive 초기화</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetC#InteractiveFromProject</source> <target state="translated">ResetC#InteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Reset Visual Basic Interactive from Project</source> <target state="translated">프로젝트에서 Visual Basic Interactive 다시 설정</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetVisualBasicInteractiveFromProject</source> <target state="translated">ResetVisualBasicInteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|ButtonText"> <source>Analyzer</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName"> <source>Analyzer</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText"> <source>Analyzers</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName"> <source>Analyzers</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|ButtonText"> <source>Diagnostic</source> <target state="translated">진단</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName"> <source>Diagnostic</source> <target state="translated">진단</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="translated">심각도 설정</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="translated">심각도 설정</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="translated">심각도 설정</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText"> <source>S&amp;uppress</source> <target state="translated">표시하지 않음(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName"> <source>S&amp;uppress</source> <target state="translated">표시하지 않음(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|CommandName"> <source>S&amp;uppress</source> <target state="translated">표시하지 않음(&amp;U)</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="ko" original="../Commands.vsct"> <body> <trans-unit id="ECMD_RUNFXCOPSEL|ButtonText"> <source>Run Code &amp;Analysis on Selection</source> <target state="translated">선택 영역에 대해 코드 분석 실행(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|ButtonText"> <source>&amp;Current Document</source> <target state="translated">현재 문서(&amp;C)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|CommandName"> <source>AnalysisScopeCurrentDocument</source> <target state="translated">AnalysisScopeCurrentDocument</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeCurrentFile|LocCanonicalName"> <source>Current Document</source> <target state="translated">현재 문서</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">기본값(&amp;D)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|CommandName"> <source>AnalysisScopeDefault</source> <target state="translated">AnalysisScopeDefault</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeDefault|LocCanonicalName"> <source>Default</source> <target state="translated">기본</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|ButtonText"> <source>&amp;Entire Solution</source> <target state="translated">전체 솔루션(&amp;E)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|CommandName"> <source>AnalysisScopeEntireSolution</source> <target state="translated">AnalysisScopeEntireSolution</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeEntireSolution|LocCanonicalName"> <source>Entire Solution</source> <target state="translated">전체 솔루션</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|ButtonText"> <source>&amp;Open Documents</source> <target state="translated">열린 문서(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|CommandName"> <source>AnalysisScopeOpenDocuments</source> <target state="translated">AnalysisScopeOpenDocuments</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeOpenFiles|LocCanonicalName"> <source>Open Documents</source> <target state="translated">문서 열기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|ButtonText"> <source>Set Analysis Scope</source> <target state="translated">분석 범위 설정</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|CommandName"> <source>Set Analysis Scope</source> <target state="translated">분석 범위 설정</target> <note /> </trans-unit> <trans-unit id="cmdidAnalysisScopeSubMenu|LocCanonicalName"> <source>SetAnalysisScope</source> <target state="translated">SetAnalysisScope</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|ButtonText"> <source>Sort &amp;Usings</source> <target state="translated">Using 정렬(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeSortUsings|LocCanonicalName"> <source>SortUsings</source> <target state="translated">SortUsings</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">제거 및 정렬(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidContextOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|ButtonText"> <source>Remove &amp;and Sort</source> <target state="translated">제거 및 정렬(&amp;A)</target> <note /> </trans-unit> <trans-unit id="cmdidCSharpOrganizeRemoveAndSort|LocCanonicalName"> <source>RemoveAndSort</source> <target state="translated">RemoveAndSort</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="new">&amp;Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|CommandName"> <source>ErrorListSetSeverityDefault</source> <target state="new">ErrorListSetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="new">Default</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="new">&amp;Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|CommandName"> <source>ErrorListSetSeverityError</source> <target state="new">ErrorListSetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="new">Error</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="new">&amp;Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|CommandName"> <source>ErrorListSetSeverityHidden</source> <target state="new">ErrorListSetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="new">Silent</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="new">&amp;Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|CommandName"> <source>ErrorListSetSeverityInfo</source> <target state="new">ErrorListSetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="new">Suggestion</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="new">&amp;None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|CommandName"> <source>ErrorListSetSeverityNone</source> <target state="new">ErrorListSetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="new">None</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="new">Set severity</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="new">&amp;Warning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|CommandName"> <source>ErrorListSetSeverityWarning</source> <target state="new">ErrorListSetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidErrorListSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="new">Warning</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|ButtonText"> <source>&amp;Analyzer...</source> <target state="translated">분석기(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">분석기 추가(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidProjectAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">분석기 추가(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidReferencesContextAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|ButtonText"> <source>Add &amp;Analyzer...</source> <target state="translated">분석기 추가(&amp;A)...</target> <note /> </trans-unit> <trans-unit id="cmdidAddAnalyzer|LocCanonicalName"> <source>AddAnalyzer</source> <target state="translated">AddAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|ButtonText"> <source>&amp;Remove</source> <target state="translated">제거(&amp;R)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|LocCanonicalName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveAnalyzer|CommandName"> <source>RemoveAnalyzer</source> <target state="translated">RemoveAnalyzer</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|ButtonText"> <source>&amp;Open Active Rule Set</source> <target state="translated">활성 규칙 집합 열기(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|LocCanonicalName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidOpenRuleSet|CommandName"> <source>OpenActiveRuleSet</source> <target state="translated">OpenActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|ButtonText"> <source>Remove Unused References...</source> <target state="translated">사용하지 않는 참조 제거</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|CommandName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveUnusedReferences|LocCanonicalName"> <source>RemoveUnusedReferences</source> <target state="translated">RemoveUnusedReferences</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|ButtonText"> <source>Run C&amp;ode Analysis</source> <target state="translated">코드 분석 실행(&amp;O)</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|CommandName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidRunCodeAnalysisForProject|LocCanonicalName"> <source>RunCodeAnalysisForProject</source> <target state="translated">RunCodeAnalysisForProject</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|ButtonText"> <source>&amp;Default</source> <target state="translated">기본값(&amp;D)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|LocCanonicalName"> <source>Default</source> <target state="translated">기본값</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityDefault|CommandName"> <source>SetSeverityDefault</source> <target state="translated">SetSeverityDefault</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|ButtonText"> <source>&amp;Error</source> <target state="translated">오류(&amp;E)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|LocCanonicalName"> <source>Error</source> <target state="translated">오류</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityError|CommandName"> <source>SetSeverityError</source> <target state="translated">SetSeverityError</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|ButtonText"> <source>&amp;Warning</source> <target state="translated">경고(&amp;W)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|LocCanonicalName"> <source>Warning</source> <target state="translated">경고</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityWarning|CommandName"> <source>SetSeverityWarning</source> <target state="translated">SetSeverityWarning</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|ButtonText"> <source>&amp;Suggestion</source> <target state="translated">제안(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|LocCanonicalName"> <source>Suggestion</source> <target state="translated">제안</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityInfo|CommandName"> <source>SetSeverityInfo</source> <target state="translated">SetSeverityInfo</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|ButtonText"> <source>&amp;Silent</source> <target state="translated">자동(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|LocCanonicalName"> <source>Silent</source> <target state="translated">자동</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityHidden|CommandName"> <source>SetSeverityHidden</source> <target state="translated">SetSeverityHidden</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|ButtonText"> <source>&amp;None</source> <target state="translated">없음(&amp;N)</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|LocCanonicalName"> <source>None</source> <target state="translated">None</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeverityNone|CommandName"> <source>SetSeverityNone</source> <target state="translated">SetSeverityNone</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|ButtonText"> <source>&amp;View Help...</source> <target state="translated">도움말 보기(&amp;V)...</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|LocCanonicalName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidOpenDiagnosticHelpLink|CommandName"> <source>ViewHelp</source> <target state="translated">ViewHelp</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|ButtonText"> <source>&amp;Set as Active Rule Set</source> <target state="translated">활성 규칙 집합으로 설정(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|LocCanonicalName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidSetActiveRuleSet|CommandName"> <source>SetAsActiveRuleSet</source> <target state="translated">SetAsActiveRuleSet</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|ButtonText"> <source>Remove&amp; Suppression(s)</source> <target state="translated">비표시 오류(Suppression) 제거(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|LocCanonicalName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidRemoveSuppressions|CommandName"> <source>RemoveSuppressions</source> <target state="translated">RemoveSuppressions</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|ButtonText"> <source>In &amp;Source</source> <target state="translated">소스(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|LocCanonicalName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSource|CommandName"> <source>AddSuppressionsInSource</source> <target state="translated">AddSuppressionsInSource</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|ButtonText"> <source>In&amp; Suppression File</source> <target state="translated">비표시 오류(Suppression) 파일(&amp;S)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|LocCanonicalName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsInSuppressionFile|CommandName"> <source>AddSuppressionsInSuppressionFile</source> <target state="translated">AddSuppressionsInSuppressionFile</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|ButtonText"> <source>Go To Implementation</source> <target state="translated">구현으로 이동</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|LocCanonicalName"> <source>GoToImplementation</source> <target state="translated">GoToImplementation</target> <note /> </trans-unit> <trans-unit id="cmdidGoToImplementation|CommandName"> <source>Go To Implementation</source> <target state="translated">구현으로 이동</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|ButtonText"> <source>Sync &amp;Namespaces</source> <target state="translated">네임스페이스 동기화(&amp;N)</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|CommandName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidSyncNamespaces|LocCanonicalName"> <source>SyncNamespaces</source> <target state="translated">SyncNamespaces</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|ButtonText"> <source>Track Value Source</source> <target state="translated">추적 값 원본</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|CommandName"> <source>ShowValueTrackingCommandName</source> <target state="translated">ShowValueTrackingCommandName</target> <note /> </trans-unit> <trans-unit id="cmdidshowValueTracking|LocCanonicalName"> <source>ViewEditorConfigSettings</source> <target state="translated">ViewEditorConfigSettings</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Initialize Interactive with Project</source> <target state="translated">프로젝트에서 Interactive 초기화</target> <note /> </trans-unit> <trans-unit id="guidCSharpInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetC#InteractiveFromProject</source> <target state="translated">ResetC#InteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|ButtonText"> <source>Reset Visual Basic Interactive from Project</source> <target state="translated">프로젝트에서 Visual Basic Interactive 다시 설정</target> <note /> </trans-unit> <trans-unit id="guidVisualBasicInteractiveCommandSet|cmdidResetInteractiveFromProject|LocCanonicalName"> <source>ResetVisualBasicInteractiveFromProject</source> <target state="translated">ResetVisualBasicInteractiveFromProject</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|ButtonText"> <source>Analyzer</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerContextMenu|LocCanonicalName"> <source>Analyzer</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|ButtonText"> <source>Analyzers</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidAnalyzerFolderContextMenu|LocCanonicalName"> <source>Analyzers</source> <target state="translated">분석기</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|ButtonText"> <source>Diagnostic</source> <target state="translated">진단</target> <note /> </trans-unit> <trans-unit id="cmdidDiagnosticContextMenu|LocCanonicalName"> <source>Diagnostic</source> <target state="translated">진단</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|ButtonText"> <source>Set severity</source> <target state="translated">심각도 설정</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|CommandName"> <source>Set severity</source> <target state="translated">심각도 설정</target> <note /> </trans-unit> <trans-unit id="cmdidSetSeveritySubMenu|LocCanonicalName"> <source>Set severity</source> <target state="translated">심각도 설정</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|ButtonText"> <source>S&amp;uppress</source> <target state="translated">표시하지 않음(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|LocCanonicalName"> <source>S&amp;uppress</source> <target state="translated">표시하지 않음(&amp;U)</target> <note /> </trans-unit> <trans-unit id="cmdidAddSuppressionsContextMenu|CommandName"> <source>S&amp;uppress</source> <target state="translated">표시하지 않음(&amp;U)</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/BoundTree/BoundOrdering.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundOrdering Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return UnderlyingExpression.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return UnderlyingExpression.ResultKind 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundOrdering Public Overrides ReadOnly Property ExpressionSymbol As Symbol Get Return UnderlyingExpression.ExpressionSymbol End Get End Property Public Overrides ReadOnly Property ResultKind As LookupResultKind Get Return UnderlyingExpression.ResultKind End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Razor/RazorLanguageServiceClientFactory.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.VisualStudio.LanguageServices.Razor { [Obsolete("Use Microsoft.CodeAnalysis.ExternalAccess.Razor.RazorRemoteHostClient instead")] internal static class RazorLanguageServiceClientFactory { public static async Task<RazorLanguageServiceClient> CreateAsync(Workspace workspace, CancellationToken cancellationToken = default) { var clientFactory = workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); var client = await clientFactory.TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); return client == null ? null : new RazorLanguageServiceClient(client, GetServiceName(workspace)); } #region support a/b testing. after a/b testing, we can remove all this code private static string s_serviceNameDoNotAccessDirectly = null; private static string GetServiceName(Workspace workspace) { if (s_serviceNameDoNotAccessDirectly == null) { var x64 = workspace.Options.GetOption(OOP64Bit); if (!x64) { x64 = workspace.Services.GetService<IExperimentationService>().IsExperimentEnabled( WellKnownExperimentNames.RoslynOOP64bit); } Interlocked.CompareExchange( ref s_serviceNameDoNotAccessDirectly, x64 ? "razorLanguageService64" : "razorLanguageService", null); } return s_serviceNameDoNotAccessDirectly; } public static readonly Option<bool> OOP64Bit = new Option<bool>( nameof(InternalFeatureOnOffOptions), nameof(OOP64Bit), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(InternalFeatureOnOffOptions.LocalRegistryPath + nameof(OOP64Bit))); private static class InternalFeatureOnOffOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; } #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. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Remote; namespace Microsoft.VisualStudio.LanguageServices.Razor { [Obsolete("Use Microsoft.CodeAnalysis.ExternalAccess.Razor.RazorRemoteHostClient instead")] internal static class RazorLanguageServiceClientFactory { public static async Task<RazorLanguageServiceClient> CreateAsync(Workspace workspace, CancellationToken cancellationToken = default) { var clientFactory = workspace.Services.GetRequiredService<IRemoteHostClientProvider>(); var client = await clientFactory.TryGetRemoteHostClientAsync(cancellationToken).ConfigureAwait(false); return client == null ? null : new RazorLanguageServiceClient(client, GetServiceName(workspace)); } #region support a/b testing. after a/b testing, we can remove all this code private static string s_serviceNameDoNotAccessDirectly = null; private static string GetServiceName(Workspace workspace) { if (s_serviceNameDoNotAccessDirectly == null) { var x64 = workspace.Options.GetOption(OOP64Bit); if (!x64) { x64 = workspace.Services.GetService<IExperimentationService>().IsExperimentEnabled( WellKnownExperimentNames.RoslynOOP64bit); } Interlocked.CompareExchange( ref s_serviceNameDoNotAccessDirectly, x64 ? "razorLanguageService64" : "razorLanguageService", null); } return s_serviceNameDoNotAccessDirectly; } public static readonly Option<bool> OOP64Bit = new Option<bool>( nameof(InternalFeatureOnOffOptions), nameof(OOP64Bit), defaultValue: false, storageLocations: new LocalUserProfileStorageLocation(InternalFeatureOnOffOptions.LocalRegistryPath + nameof(OOP64Bit))); private static class InternalFeatureOnOffOptions { internal const string LocalRegistryPath = @"Roslyn\Internal\OnOff\Features\"; } #endregion } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./docs/wiki/images/workspace-obj-relations.png
PNG  IHDR\s XsRGBgAMA a pHYsodFIDATx^ |U},", [3 x1uL_mr }M6amIS$/'K-q')qӹ8؉}Z'K[<yZ{=g^Y hn} g}5O2}^{^)ڛ^/P^5fǎOK +כf͚5vJgg+V[V;'-;#s"7nL#Ν@si_rX @7/jg':22R{:kJ^u~ӧ:uAl:zΜ9[avqgϞ'n#D\D]HpիWY:GY"U)O0tVO [,waxgjoBM&Y'> /թROljjCb9 Z8[Xmm}<[H|zыњWpep^lY_*[l9~"{'DawM_89i1zbݹ|Nٳg',K'Ξt fBNeLt!7IeIx+I<+%O:<lb</۲'1n62wܨJ'N\gtϠrm 3$9^$IB/[/=xJy4y'nذaŋMI$%cAYSYYyOצDlSIp:Ȇ>!o`0$QIOX| ,&$* K ,<lȋn eW]6~%:<<\xfǒSO='J@ԩSh+x=yulҲvuuyeUI&@ĝ;w<@'N3%Be"z=K.͌L0'EgXt/L>ئe.]6Nqa2p7 tU_־}6d>88خN8G<JID8"VIIU׮Jȍ7uPR,: V86RN|pM훈׻$RIIi tR0db1q iR2}-:zwnMwK)7z_5|~$z0J' AUU7"WGpplYp$7so輾A}E'cN$lƌJ(6zGTk'^S>r…w <tet[ŽͰ"ʼn$mz&(܀"*芁m7y uEdE"t'។) Jt [xooZHA𽁌r_W?~|x"}3F,YpSow~Q֦۠7tdiLbuOAj_XnWTN; ;n:IR$ň=YN0Z;HnUkoo%|§'L`>]644I<;<PN*dmYNt Җ5oI[Trz _g1C6B媸M(d}Ul7WOAn) =wk$XΛYfAgz[XVyfNz\rE%^}~:8ٽ{wW S[L䤔ܹs;\F#ͧpdВrwMLtU7t^JFB~ ׈Gq$ JW<ȓWe˖]ك lE< ݻwaXlo*jj[f |9_Ga{!. _O73 ~3>)| AIIW:y л<;\.,X`w91<Yn@rbx&N(<"5C---7qw InS$[p.c),->e '}j 5diB-8SJw1 Ɏ+WD%>$Sִb e4In9xJb"f8Ü0L;'>D EkP" %B ~Jz+z}>+Veqb}A]* uy$``SQW^yEɫ~^+KpkDS40rvZ41.Nܔ` ?/;X:H:_MgUPЍNAr""uFJ'PBi 9}ò*pqz&ƕi>4.H>$,9 \)84ӵ2d԰@F$S>ODqc f pEFqGM!~v:͢d E&|m۶uuu_ѷ܌O\)]]M1A#R+G dy "LW7v࢈޾}[p(7Vgt)oFѷ~[U0MqRi`4u&g:VjE:K)SD?@z{{߆M2e}uϙ0}\:{VR!i4͂ye1elQs)`[\jлPWʌ%+>}2/9oF͛mii]4 ^ho"<dA'1Kz1es"ݳgOlFŐRC7to<66\i #rs5ך~uŪ{#Z`OAB > >Ute$_:*!L'V+)$''UtAThHq]-) 2WȩwNc|͍C]mH$S˯,Y##n%+ChCVl߾}7 xDzBY-Q#S:F`<y^?~Q innDE͛"c)II5k5Hb1A7jh;Λ!a$YyvL!l8U?4"]ttNITlPW*O&uJ:xm\( s 6¢O{)JW_=$V8y Ȕ;A\ 2Ξ=N<aH .\.|:<<܈a$SN}߾}>tIJ Q|]j1#4 uNO=@JZA#*S.aaH{bs ٴi 6E#g#/Xڢxr']+B`lk/r^Mp7 zP\Tk)[\^Dy*KBظm<OqvPsIV8+0EgǎttVN*sIc fQTJv‡p#s%42bܐi}jI1T} >UeQ-MT _4fpx!<˂6Wna`-l\=== +">5$pcoMBr֭[Ջ<[>^PlIHۢYV܁y&UJH#b7 <Ƒ,][)6֭[CzX '$amAZ5z<nS"=s9D\>)&^+ӦMV^cnNA*RJoϞlJs<`UV 7}}}/KBlDv## B!0JM!OJy.3ڮjoR5.Kz+w>9>>Mwv_2R!$%0Tttt\^WķrʟoB_T\Ö-[/}Iš>l8#Id²} . C}OόЫ%6f~I|X&W}՜4ɓŁGp0=EzKgKDqɟՀ}*lC04@!KO4|O~XNOPv> +0,̧G`Q# AypKK*~lb:4$4('lJ1l.7|~`۶m Ҹ$y\lSOgRgu~XjfppZ;wn#jIqCjz^5dѾ5k_nݺu?aosxy< @c.W-HǾu1Ǽ)F̘1㯡!-TIx`ʜ9s8eʔ%]UA7/47C*i/^n\rŠ̈́'sĉyUhS*U*2!XXqC+l. nŞ O?SQhNߓ̧誊p#Vmlfu5 7 .O<G3Hde}ω}8{l]bb3گ^޾GQoh`v.cY:} AW)ܣWkΝPW`w0:S(.%;Ic?NB>w* zsCbU6)7u)?-,ny<,,2q!>Y8gIUƅtZ]+#Cc}5f;v|n<Z 555_ Oth.87|3:00vGON؆1Ve6v,b3_F?}:ȥW`0N`?ݻnܹ:AC~au QʟXRrO2tZc0!`.mTHl\uzե6W|ظRPzڌ?3o#6QW;Xc17LZøX%eABI1!)w+ rkH'BHjE`>'><=nh 0hUU7e##2EЯѸ4'c)Awc,[uuIYaÆFa{>|xӧpL5鵁 }Cz^.ce2ÎQ\h|V LlG99`o7>h-\M?G;ѱuŪ$s_Mw:ĤӸ$e%IrV.t5$>wR2\Tү NR ru[/9l\%m.7ظH(ξ ӟ_PO DݻS+WD{{{uď!)d^Li| U:06 "^ő $-PMF,^0yHxu( @ԩSo0KfgN0rQᅸ]>OŦ&%LYccŅ-̳ Z"4*ei:mڴoI?KEJk8j|;F?Sŋ{ Μ9}=vI}OABw\RP zD5pkĶѧ>wH7J'c`P$k\}HӁHT _l\&]%Io23 ƉHpg(`*0Di_?a$B;ѱAssI"ظ L>lDHun?l\ < uŪ$AeN|%nis.^e׮][ī ڿZ].!A5?w{#R ׏k4>Ŷ DQU { KkfBӧ Wc;lVpߖxU~ssiSm۶W!BJ GZM@ۡ>%(Q4OIUE~KDa-hFt/nw1-<U]]}CdtPJL@A˅[4hp $ITÂ"qXPF`XVr˓H1֟"(;X,@ "mtlvXqqtLne\ԥIR|IQym\/IKr s( WHո$%TDlۮNgc~mųq ٸW`bmmmgGϯtlvXqqtLܽ{wEArDLb<[Z[:¹IVG P%7n܈._\)~@ q6hH !풝`ĕRQ\1frp9qW" g[^tH'2GEW.+T\į]RqW_A"ͅs-T#%$f*,cBXD7o|T !Ŀ2f1+Ox̙`GcwB 8>BH) FW\3b /n煞L €fnal78 nyIln:BH*zӿ>u7Sk3:ÀIֈΎw p7v-3[zg3܎'d@،#G,eB)$e+VYq ZGV!ğĉīcZZZ~EyՈ+ !RVXz?~auVBIQZW+X )IVRp\###C %FI['|8R8.}|xsVKK_E7^%סԛ̳gϾX!/^|M݌) p~u3Z__2 sWK/)ySkהk·l}UZ(<(83ysH?.+P֭[ ?txx}zԾQ^exyfEQ/UgYEIt/s`K'&իW2{hWWWǀcVd,[2yBR;vQ ئڞ CWS:%lQ4?r_}U|f 3 3QdJ GC9yϞ==jr|}ȑrС'Nhp»t)"5rgf@N8u#ܤrIfęyMQm`ׇ}ěY\Hc;|ғ'OW-0äACCC> >~v}Ob>htUnI >M)e/4cǎ=f@Pߙ3gUo۶f_E R\pM*<plH3DMuXPOW\_X~ii`mh !Aúx,\ yElq;\d .9'78?ĭ0V"&L#FpK]}Z&Ƶ>I0+>ꋗtsqև YQ7?ԑfRHX'(?xاM6; pB8]$>* sKl" I,&Pv: E=!~Tz={~E#OO?kѢE>l'0ӁrE"1 I ].SP8 V:PT50[Xc|ʕ+ h׷S*(% H@5´S~\U& 6toT#|7r<uuuWTT|ag|Wj(e+^QwMa\Ze2GQQoJ<VUU&^<:EӏTq;K2(mqby#P*ĩ nPXz-wN7nԗ{x1j,WF5e…ooD1g%Hh)MO1J(~^hŤ޽{ף_X J@H}رiFɖ2-Wuc3?q*!9h}\pTWWgUTZqWq?Dn[Pn?A)|EM[e(q{${ d8pK]kw/}뭷tht۹!yB}FplCL;k9@5MMMQ3H>GRMF>$;R\FB}3swBZ74<8äs"o"3!ӲO).(2R2DbpwwT۷[\\).À[3!QHCqyVվ,Y\*.À[3!Q2DHXq!v;IV|MUƜ9sAcSw'&NE{ \H']*0>ED"uΜ9pQ\Hgc wKZΝ:uwy/p/H:o޼%. - o}}_|bQW& N7 /iS2DHeP."|n ?qJO$l 4?pt)u+L4222aA㪩8x;Wf}o˄<<HKtuy|dcq:$s>s`Ee+s>m|PV~R;Iv}݈` B y8pRI :1{ƍ 芇p⶯~B~7k<A/_Ρ>&XjժmgB ?}&\OڜBryV |Ʊ{MX`V=X}>3bfW֤ʏ7Qv!d̈􇲭 fjݴiIWCCC-H# o0ckZ3<ltl#/5Esf&X2 dɒ_m K.y,y0>G,9x~3WR#xķmewwt#!$07, S XoQXSc(b?z$%DOIoQjGEBHQyX)x֬Y)BD"M1a_ x3P ,o^cj&ыNŭ \ %CBʚ5k>,nǕl'>'(}= WIHɵʶ,n.*"/;PNe2 ')/ mqI7D %|T,̣T}$$Pqo& GE !C.ZqtswIysLRIH pxcҢ8Q%xe||ū.&X7aEVuuu4z{{$?>Z'2E~U hŊ?05B"X-nػ">PhȻpߖqK/c!ϔi%W*%CPHz/(?Z*-5(V͛c]Ǖ(ʟF^!B! 5 BUU7ů&۳gO›;LUGZVڲe~Nڽ{wVjEkUJ@,z(e`? (%+&ĄJl7Vf1mjj$+E&i/`ttt\ ER1 Vż _wE޽{7:L$_-c3{?׫<vMYYRs++"eN=CB^b(z==R'HAJ45#a%*;tZ\v (.kUqyW*.fR\o\vug T\m 4θt"a&4*&Y\JqӵIg4.T\$̰+CwH"$pPqQq,cKlE/]{}RZNxkj,MHp`te#_ -Ś (:cƌ;u7pW[[w޽ɔq#VfDOHqoD׮]#W@X^QsYԩSo1C{{ǐv޽"G13Ge 3g7mtuc$B&fm FD ѣG;N<@T>>}4KLaH# cyIq:_ٳg 35@A9rdQp۷om+aTp0`ٳBdS~$0N8ъ/^8 EOR@^(:<fxR36`?aaz[Ȉh7o>:o޼ߑD_ܷo_7!#>ҥKA.:ɣ \"+qcL؇i\e2(d* vTWY5 N43ΑckF8}΃_HkkBr% '===@.Bx'xKtB0|gg%У>u-Т} Ͽ.~]|/Pj璠O޽{W,.F+dD/_sy<7ynGҺ$v:WIsN?o賋&!ǓBz\+.It Ņx#,rHB>adCq%eJq%ĥrm9A*.$/e\dqtҀ\*.tθDM8'HCEDqI6=6>*.$99OHa^~]7⓮²`:W =$0Pccc 7,gֹիW~Z_|ipa]ZB!|N$( ?">ǹ|z AKm%F;a\iQ/WoL ۶mS6J$0BDC~HBE|IEɓI^T\$_."( Ņ4k[ӟ5b VH*hqip.l7W8MLI`޶I 'F4K7 PqTPqAERAE|IT\$T\wPqTPqAER!OPqTDts!vy5D q022R+NtfCHq@xAT D@(?"0?~ӧO?3LBOjmm5Fc1Sʚ&N̙3ub!ğ:uqǎ{L+1B/xLjillٳg1{X866&A_!KX!aTLsO(#uB=8QqBNj.nYQ1ox~bpQ Ӿ@Sm7Q3m pgMtssx`o;!`||<"N/.^8K!m-~gZ;̙qon~oOɀF8%J: .8#wqni0t€ٶ ΰD逽mҹu mי '>|H"$[0۷oO|!~XeN>=sxx^,X! XYDO<@2XYP`#BF3~ҥ'ݻ{׍xB|R\555_lGϟsKª5[n=4::ڬ# !_rڵCUJK[?3BQ%" ,_f͇!W%K|dԩo` ҥKaժU?6V}80yI#\&#U<!V87no}7O}7uh~uR^}}} K\Q~'$TVVҗ|+%9> ѫW=<ܼyyQq'$PqT J*LqQieHmSSMXq;wnFOOϨ抴׫}K/}藾%sW(Ƌ5I̓O>yPhmmmTMebg* }ttt\A“eЖ-[ MLz;zwKEtnJ9+vxكApT(Zm2ʤ˃{9),{5^{MC1y2Sv0 AΜ9zG*L * :Ω&$JtXlҮ/4βCX,*݌b Mܬq5ڱc6X/BP)t$ˁh,۶mۋe[?q <&o 1@QǢ+ W8CGd|3QeB] f!tvvņm;ΧVͣ>#tSӧqFg*W 9ŮǙ6{̮x#n=;UPFC0f(b%KʀqUEZZZnGwdЯfpc fihooG_ y 0mqxf,-6@`,8S2S;wn CGc'!+!^*F} es̙ ܤAz-f;Qfs ͤ`+u!]ߑ#G|3KEv}±>Eٷ4(رcaFS&Y(SJGʝO}JS.it'e?~lf =z]W1s^ُe& W++UtMB\Xǥ2 5p`z yӦM'̙ETpO"xD>l'\4B3'[U*mo5 ^7||Pg [\qƀ*3Vhec.4\D3n l? 54ZH>sʱ+ (hNҰAI=>SL'JAxpLꃕkꃂE&[a#hww^(wܙ@ @iU8E_Th, 4YfFO ^L hN!JinO| K Lj JŋC?"&7T/ +t"Pl4=řFo@>ERէ,BL%^' (1#P;<呲իW8&L`p 9,)'8 44݈@ :烂VL_\5rGoy26"ħmMAJQ0}w0<,Y߿R4,)),+.Q`ݟ\xKy~U"o eڒ|PpA466~']%*++_c< ՙ~t’:v"<^p]FdӋ5Q* ih>Q2lC7 7QJ V\oa.jѝڢz',)m9@ͤ6Pq X_4eg(K\#?yoh#-PRDVHq 冷/x>+ƠǼ}eD߿*-[vY$ *'# \<}}OrڵkCX4`Qa̋R֒xR1TR98"n%O+萏n޼f E=%x(a%`a+Q-$,|HkA<ORM[\ >W x@Q/ @ kF>^Dgz斖C{r#Ŵ}ԩot޽\$dh#6/qm1<ºSTe?O'xHk;B&AŕGp\[n}VN*"0m|"#ʠō ߢaI+.|7PO'Jqmf=HZ<.ה?۪00=k֬ooT1ye, N} W ݗv'ݻ{1.9/p^Ij7JªHh(^Byy};&p<8.}%  wxNx+I%[G2+%R#~TX0c潒pv“AQ ܂.PJ49sxU'<K :(.L$u~H (' 1 Or W1qNxR0J{ngR?\PE87/I >u_(z))z, ;5s)h` q&,VG0ڨ^T(I̾޻wOIny뭷{n{=~isFV 8.,;Ĵpk|4DBUPG)类aRq BY˿K7!ea&GpqrQc:]]ͱޓ}V\͘ |MQ .Q ǵtqp3(A 1niT pUyG#3L/Ce0t/ \q9GF}t >A^#N)&r<*.X:Ü`^qn/0&:lܾ5zy8ɦ\C6ePq}3ǭDz/ Լ*(W]X\nlM7N+3<k2>6}*,{'Y^5 06餱lc/jq%"Q wsdΛ1t…MU]dyřp7H.*,g[&̫+PSN:2&4C3!  `fS&|޼y/[DeDn&[ĶYniߙ@DVFrMx"7WPq}ڽcጳ]#fvs.BQ>=П3gΟ;vl.J|[iS >L#fepXXpsK öSLf<!8Xj IػR!O>(p1@4vmav \AUXiFq;zhY(lŅ0;I~)%nsf{̤<;K9/XBQ\ni+.J o@$MSqaUu9KLi~ΝOb;Sg >Xl.@BEfU8ӈ _+Nqc&,sd'&u7(~z}.=Qa[6۷oߍ#7aa. 9Z \5B<+mpsD!>htႊ. yPXڒx8>csR찰Vk T\EpQť?V*8΍F. >"Dϟ]cA1Ӷ :l nx䙂L1Rhp\E_079y'|r]sxqik G5$\hAq=T~"Ntppu?"7nPӱ`_yKQ]+HbڜR(LC hQt4%P0b蛋M/^|M\P gΜl?O?#G,۴iI^UUM E>B)JYaNsse[)@I>|CCCGCc}P!ZȪU~KS`uj|&.";tЊ={`2 !dL\YA9v\YO J,Ǐ_(ʩ}&6k yE(ӧOĴ0x@=+*-SB2A)+ ߰aðlǕQ+RcJ@ʆE& VfѢE)q~Cy  \v!0P`FYjҟt#Lڰҵ*>?!(LyG%iHTG?f(e0W7"qj&b6b8VSoݺYQ+FGG,P ebKo+1Dܹsy K#P .k JC[¤zEQP`"(Αno"wڵTBHhP hɒ%(qetҟZaF`_OSۛH<}&dzkgA.X+__Fo"7?DBrr%L,mmmWM=OkYAQq ) TS_Y0%9X2vѵɶmqWWWUHHXA#$waC-]%#`#<ช<!y'z54 ̗ŜmBsnN8!&DsKŅ*.*.nV\(HȶB).a$Wd[)rrMeRqSlˤ"@Nf;+7۶LcDiyLx"$ʛ-ŶL3N*.R Mqu +.N*.R duB).?BEJ(.SH U -.*.nB)B)nM><⪯Y#!s&0CBKK }^tI8.N(HB tGM0I`|ɃFyݿi;! c|(Dn"iAFI,*^uQRoo8_lV I[M!EKUӘJ+?~Q,۷A>eA͛"#2(q (O:Հ ,iȠ̰"ٲe.,{^D!$g^Z2XX⩶," FDjFGG~V2PbcӧO+2,ˡ#dZN: XHxe $Rt* JբD^<RŒM[[[O%FI(GW)۷;t XNx&^ƐW*)ݰ؆ޏ>3XbPd>/KڸĒȋB!dPVI*nݺFhl RJLo#P'3bP`Pdk׮};^lڴ!m޼JA,]8` ]xqV~1#~~~zyl51Rb@a@)W),4¨{XC^h` 2/UXc.\IIWbs"-BH0A,C0A.*( bu~1(1\UVVSO#$-huuah:ѬQ.t3^PD"\~-[IWd+Vi*1B@oo ShYY[fٳgyCCí?[f͚ǎPDt쯖a8 C,H-_D"[+1KH^@?ѫih,X\z2$r3BBRXaիi_zMx)h8 3 W___cp\ bm4zq]UL6 GEWp$$LPq"$pdϖLC|+.ɮ}0Keol۸'KK)%E]vug+:/!"W˄y-ˀ|FdSf![Ĺ2EIHVqJ|ٔY>.)V&c✮M8/ !"Se޶bL@|(._ΰT~77Y\&2 (*H"$pPqQq8 Y+UWWwf8.̮;􌊣s;wPqG%qts˗/zFuc첱#$TWW\졐iyq-'G`q ?xF߿wu?^mijj)mgהVG*2X4чCIB|U%K|D7o>jڽ{w(F±24imm}ucJ^%dRV'NhBW6---+wBQaٮcǎ-XKi :mڴoahcy2Pdןihh#\#/\,!僥" qeuYE]E; .KEńU+͟??K8{7:u, e2_vF` .F 2#D1հrd;(fΜ B czHEN<^,*ѝ;wn(Ũ4, +  Y|GݔU~B` ʕ0!!,9߁Le; .\PPbU-#`)I*($RQ& Ǐ_x/QQz!\/Z2 +HC)Aae}@aaY?AUUU}qȫʌSiӦ_SN..t(Wُj xD-/ﱚWe;* 2 L5/^>3(3(VQXLįJ LիP!>E]XN2,۷%(E咫 GP2%X'&)3aep*%K|k ׮]G^*3B0l/Ty\ s1˅rυb#G@H^R_)QWa?cY1A8`%EV[K-2ۿj97З7}oH 簿\1<u?~VTT|G,ъx{'|t}I;Zݱc6ٌ[_nplmeql׮]["?H @x#-3BpA"5q=c/`?LדeOE%WHg:x[+~BEoo8!Fn^pGŤKgƍBjkk>ttt\Q{{D,XZVM/BEʕ+;?JNAi_~Y(Hl&cMKOC1 ڹDo߾s쏶^]/g֩3vtnf?)f@U~zT'Pq! ŅKŕnlA=*.B^ʢ""W:i ^Һ(. *.(Ly|gmco'J T\$PʦL-F]^Gbq58Pq@v-M|7b~Tt KI,*.(FRrsmq!O!"W&yeRq!}"-|)vWPq@Aŕ;?T\*܁"?`R9'6b۶m:"AD7s]/P:g vm2fC?D؞v͸8_ԎLx ]B0 KBO`FWl z.&Ӏ&*-Cgg%q\*蕶S](xuB!D' g1'dikkT^P@ON!$Y 266U !71,g͚5G)lBHr(B&\w*B4!AOB .BHF HtpKC8E\nO'6anqnL팷m f30Dqni wƙmgvA4G7ɶ-ÍT8ÒO7ΐ*Mmib Y &4!A+\tj`'Jcg|txcog&|$8"d `GMas3mmsn$s۶8ܶA:aIE\>4!AB҇!$#hpBH"d .BI\E!CQZBqM˺С6@V+B wލ.X ޻u.q !PW( B( #'hEWSSM PYԼ*MQn)|Kgg祾sV B 8eNܻwF+ckYǫEU*B!ebPU>TYYmَVWWEoH\3<35B!xV )V[O?'OWjtVB!15Ӻ/Ȧ2.]###-FcB!$Cٳᡡغx,1"0tZB!!"zZQZٮz[B! m!B!YRvvʅ1`۟tt9Y: ^Ӿݏ\! WG}ԩSL:1c_5"e;S 7۶fosې(Dqn~mp wqKLmM7ęָvd~'&p!/d[ݬ3<<\q\Y27d7?/~; $J2?Y!?Hgc綍[De0C<K\y naBHaZl&nJUV[EWfHൌtÀvdlg~4qK<p7"$ B)8jďRwK 1,C&ߍ[BJz0CGGǕD"}ȑeX+pqeǼBID|pɓ'@0#ibI !BH2`XMxb̙_]bO+S«C +xB! mPU[dSںu~ׇr!BI`Uq5ʶ200+k׮-8odsq !BHj0icc$ vVGGGapvB!$ EĀzM0 uuuwرСC+;ܹs%O55E!ZqllCCCﯨG SV[[ս{nX>222_Ͻr>B!ހ1tSz(ŕa0 b! yI}ƍ͛7'g{'?6qGtR?@/^|M\l_n&dBH!{nܸ ovފ~{S__~9DU[[{ $tmB)6m](ؘ?sA18!{ۋ3$#R,|Ƀ@9G^o5GAS[10[lR8 !\WhId,2L|t䞁tQ#8 >',k}'Bc7({$rïFh> /}K\W_}U:$?-L] 0ݘK?/aX苘o qHRBH:`vhū޿_$IH?1HCCít D 8!f͚wtt\A>LiEC~'=\=\^[?u떪_WapmV!ٯ =X[lQeE<k .z36L9G~lz]2 Hc@3q @1U5"E/n!00iBj-X@!gѥ@cKO1kU# ~IELAlٲ&cN+>14UnO|TO|B[0bC@1L:`" _yfpsHc1ڵkknnٶd=П͛7w0>ڱ=\M!ր'9LJ|Uںu!|n",O eD.]9eѢEwݧ,Fx|nzO *~sFΣ[>7Iv|}Kh!'gӤ_fbOJ~-|6?>Aڞ;%t(Omn߾]|$C̘1t1hXsL2i>GՂ4^&tt&mQeӦM' _ /e*cP ԉmQ:$e !Ƅ.Ɣmnv9v`4n$%QC=1_:uwv">}Ϝ9S'7}cC;45SV\3RƄ'Q&qAIJUBO!ohh#6-K  !L:>j/LJ*y"ٞp|o6yq,C6;w>)ۮybŊF>O&m*9vcwRB>eO$8>-yIJ;OmF`ҦǏ? e;~|(_dV=!&0Ҽw^t?x`ݻ*_^J\/*«D3"O,zcLo*#p|.n\Z۷OR*f+FqvuuiӾe >|u?>яmP4̫Ego  5fJCZlØC=v e׍NSD8+ENWgϞիWa o޼']xqn Aݰa\<844Ԃ(;r21AO h!a7ĭ:F:we Y~79}or8¶فx ys4LJzPMt|8p;>$l #'Ϋd܈Dp|͸#,l=-rJ8>S\)GI%m{Ã9ȃ(_$rId #٦A8GnO\✢ns]}ƾK;1eqp.$mj%iC8ڔ^+,skp:"aZzy aB1jkkv[[r?qxES]]mcT1p`MQ$1Ojn|`83 7l0l?4܂%2, {iӿkum6P7[tn n~΄'ylw+{Q L+`,%'B:w)k%'!oSF R')J_8q-"t&;"U"Iι9>OMNea[$ǗMTI]s\5{# ap5نo?a]H=RWyXSS5WNj%E|"\kIL _mgS'Q0MPZ1ZyEҨN[mA$c{I{x-'~i+K`lK#h<--O"I[D <$nI*$TqTI$p˓H>Lt)t쏎JoPFPӜBk?&MKKt(W؀^(taHFr8=.n5`k0hp$B(=œ>!x͛$qI]c s<\ `ٱc@󪪪oJ\|z]#B}}};<uЋ)=^j8ч$ BFHh7#5VWHbp9Qmj3(>yca&toA26mB HupLJ85.}12s̯U+~V`z..ɇ zd#K#>bz`\j=WG˗CSK),S{y FJr}N9&47 Fދ UTT|]0djDmO=|lj&lǍ$\ x͂|(Bzm|k=єൌ%3}"A._qW=ˏsB‰R:a58bg/jjj^5ad/:ȌC㥺LZȜ9st~ʕ=RXn CM=@ D^u !vC]N2O04닣%nE0͍7&/~O)<K1~<ίٔ)S4~#XMSb/z`P'ʌB.|^)կ$:/u^(SncBywA`< Rpj{BV WÄ: \f!n$ws # s>}]nݿ 01 c"D`EaB=gzE‰ėUUUɶj/ӧO]>AB?۷o'AJ`bGd{Jgןt>* ޿ZSv\4v|oHAA6 o`4|`#n'1#xxc+oE|mٲx=X6&4cڨIJTofKVmqrFϧ !d5ip?sL Uᦊ+fKK6a%IQֶm؋5}eݽ>huyB-":$H" lٲݼysM+$1lp(6dɒ`bY1;Ȋ&Ed&\"_a05V4:H>wލĕ0W0" S{؃૫3I×xh}JCRks{"ۥѫQJYZ҉d38Pbx]So`B$JӯS#I!޼̟?8JA_vM։c+E6Do=~ԩo`<R SN=d8 !ABZ_փ_%|% NfUo ,IbgT\Rz(%,A֬0A+X9Ԑ$LS$Jwa :k7 fbƌ/愛<x g.Y`sO<QL\AO !@d۷o-AJ>RL2^b,922҄Ϫ1Y? :"kîxoVSSKz&x5^N]FAfB#4 rF.ŋ_fDo!)eTVVVmmC=gXK#[9~XCL 2Jb5k|QRici- pMaU~r(J͘1:sn,Sjm(WĉQ+㜒F}^`XqS#DHxD"[n3߸~z\Ao$R=sw>;$`n_L6f䩛~U跾跿w[oS܃LĽЀ\qTL۷$n@$Qdy2BQ䇻ws KeCm"QdyFOBP ƕ-a"{!@5j`Ԥ3}P`AoPkn~3XГs!vpk-oB_+H0= Ym_5 +$4kHȟ3hpaِc˸dۉYA+x"aD5 \l6\<\(6~U̫H)~3ِm~7rUf .䷱_*&7o@9\4HQ13xM|$W!Qs>|WcBY6tH7kz/sUG |·>!b\ΰD5}7hp0u .7̾9Dvop1yq" n"X6fѢEA縲7r_ S3۶fo3̉3~6v0I'Z|[祹Ǐvbp4Flܶ0{aNi vg\Eˆjԅ6l>$d*m107CLK2Iԯ1KNqoĤAX6WTYnm1i0[ŋga#G,ٻwﺶO: )K#d…<s{n +ESMmgv6Sm es GHч+lrKo 6 Kr\++ec&ٶ3xIe;Ub@ըe9ӍN`sHW;Hߤp33&X.Re/L0pcMTڵC)7o>.y"(oddV܇ŝ߿Sn䳇s'^{N6`zm }6mG]ڂxw"lۆ* mYyɔ)SS(ӉO*m1Eˆj2Lf-- am[3̹]hpx7`}3gΟ`؂> `Āq&:K,e<rRN<guʈ?~75֨LO\  yM_^x,Y\2m80n;m[3̹K|x>}7N?%jhch+h3h;ݭb[kJ[}FA->0ę<={z}_F[sSWW1b`Hr*i\#N v n0vEˆjԅ6Hf=\XK &4)Í0j`Pɍ:QHػwٞ% wUI nY'p»$r~`F[;v1wӦM'M|R$16&tGDml dmL:vBF` nmm5 ~fݛ춃5U.94HQWp.NIQ5KkzՄXcˆ:7:I |"?.ArƔqb`ccXEہ1h\+c7hp0B+`J=]@/ ,D.RBHFΉO mp h;0D&I7B+@"aWQcs{-Apxj;4 .:C+@^C1fϞ\$tttt\G5wNʭ[_aƍ\sx켄t0FPuL7nGJ E(BxxUtnOܿ?:::WBֻehq9P(mᖸaQ688)?p2MG5oIuu]mt,PmmmWz(I~Sp/C ?k֬_Cq{{ sdFM-LYUUMghii?t_~4H%rD8~B)^{[!_G͚5/%nD"ŏ41Wb.#G<GȚ۷Ce`\f3?s{P!B ,Ơ1e[B> ` 2LeǏ4a'̜^Ϟ= 7FZfݽ?o޼y/ݻw޷1B! zKUUUIC2k֬rʟ fk6 SKrePFqa!P 5tecjZn~7a͛`8rE!B Jܰ2Ȭ0?4cƌ  :𩧞cz` s =+K"cXeaI%?~0kH805dB!2 eXAa^m۶w%|a@a(cXWI 8ò.fd"]* d(C".Q05$b<zy 2`B2`<`,Sž}6${8{?GV72`؈TW}Xb* _C8īM1–ٯ!"&3g;86B!( +8d[[[ͼ4㬎;X:7J+N8kH0} אV Dy(WB!!#nXٯ{{{%zXQQ===gaXi8+1aY㬤 V^PljkPx5j8d!-Z[0B ȉB^:zZ$nׁVɽ{nDo ^p00IHNùאoC'Ɓ%{ Y__e| )e5$!#↕IW'zXSS󵶶 錳2.F@zEkH5ѳ^d!1S>^C1$B &_ ٷo_˟O4 <sKƍOmڴP@n|UOѵcǎmѳ>QL=nKcbл~S̹yEo]>s/NaÆ|щ+++-<x \&_#_BHMx'ܼ(10rh)zn׵>?+B *G)ٳgGoܸ%ҥKXQOw Likk**oƍѻwꚈ_O/&.!׆(e>88<+ߏ655e3**uVZf͇%$VZ?3>>j3uuuQ ЮDB!6ܹU;IU1Ʌo4` .B 0a6pL _ IO .B 0~2N )lÉ[XH?/\`bpٮlaDan0;ؔev:m!Yz;6a~!\N1~3,mD$+a4bgX:bH^lhpBH{-uې($+eps7x /64!$2qMDS0\#N2sK w4!$+Hzr )"f+*MhpBH<hp&4!$ 4J\`hp\ .B 0G)˗/kNLWW*++?̄e˖]GCCܻwOWB Ͽ..s7#Ν;7[lH$}u-o Uyyy}wO$<ʼn!PS'˗/N,^8ǫ+}N,X0?BH$7ޛABf̘WSN}CþQ؎K$ihh#S[@b@w^@ z:::W==="R bٳ˲7`p-Zv4Ƨ߿>yU1&0~ FϖW_@Z#2"qB!$2<<>S=@֖-[ø:tЊgϞ{!qhh ;ؑ#Gcp7mtئO gF̙ŵk>'u,~g#BHP)1sYV%,nTWWݺu~X5ѣG;N<̙3{A""(Lj{@"?~}/ 'N <!2kzvڵe?S~#G۶mۋrc#B/P=X0o߾$,nTTT|wxSCCCqmԈD`T,-0MA{ԩӧOOl3aI#ǎ[Snbb`Ǚ3g~Uʝ`W,YWB!Ab>|xicce{_wܹݼ&<~0~0S0`(xQƚ1Ĵqٳgy…wV^1{'NWnbk׭[CiӦ}Kʝp|FӦM'ql9>B! ʐAzd{1{?߰a^ `1X3a $3cŒa@e~ R`r>8v+4!2e;aaJL=/ a`,EjV tQc5[$+fhЇ/^LaC"4!@0:qw  !=F5a1d|AWLh>f!_hoM 1B!$ N{Q&%W k0  146h8_Q&K%S ҥK4J8!B|2oʕ?iX8uTzsX$5!LW ++&IWb ?sN C!7nx e;~8,Lw`k8,aX@~sB0 ?bŊ3gΟJ 0#{_}J!=4uQ+uuuY.wލwJee'| ! ,+Rgώ^v-z޽(/r.bP/1k#HҥK;w= ݻ+WDkkkHB uMމ_ٶm[+6uMį\z5htBH8 7rn߾.[2lijj)=!MfV"!A(ōWV$7sϔ/7ݫfZwĉk!ق ]]]|B34i>,p^ .B 0LN ;: \(MN>!Bp|7 qs jw#Qxа~[ .B 6LN\<F n̶ɓ(7a3Lm\#mfI\ lp^q654KZL\ ipfo's1b vq4 LW:avq16ɶs4!$@"#-4!$@ 4E!WE .B 4 .hpBH<hp@BFuu]q˗/ת[n Qٲxk2߿k"~fjhhBG)AΉ{nF[^^~dda ,GFlܸQW;vlBH8p@8q%`ht||ٶm[4|j;wnkfV.]?0O<@BzL:::7^?FV___z=nu_($FXD !(Me3<3U'N_|cc%fTQQ_f͇7۷o(;O f޼y/bS[[ǥqd̙"n޷)IY !BoPF˙3g޳y#-%ihhKS<xpճ>)Ç/=rッ?.&޽{)SSN}w@.:th.gD biooE"p̙3ȳiӦ(/aF!3a  0`Լ*q ^<c"Qc(ux?y{O:pfHէO&a⏈Ԝ?~߿y~1k֬b p=҉8::, رcIOafe9>~<C^68 z,Y~8(HfB Ñ#GZ',qFz``9pQFEb n1fJ5"U0$X2 W 1v=Fm͚5FʒtH&;mbн?,s%#0Г}>=fa}]]]?裏2 3 E0[rl۶m/ao!~&U08 `H$JX2B&Dzt̙:80v.RU8 !? (m4իL~VVV~[F#$R\W lc`0k2f8'| ŰLtNׯr?|;vxKÌ!n0$лUUUߔ8כY`0 [uG1 P$ުlqPa=Qbĩhjjz >L0pLWFdc3/^8 v8aן0KWGaW0b.\8R)Q?{^ 3B!䀸QM7t)xz}c0Өq#WQ!7LRfQn^4:+**QձAs\U??7Lh0C!|T1këV! 3(e˖]ƫ[o*uO_RSS5Z0_db_+ihB!IF!LkqAzS+| ݻ7mnx  X"0^ܘ+@$͈6EUUkb=c鑩LlLYf.\x [f? 3/Wn߿V r쿈ެJ`R3UjD'B<njᆇ/|Kcj/,[~]Ƌ 1I31NIMoU(qp/%N+1Fp~|Lrcir0 c<a;b^3f"fSe 1NA!$H+&M $F |pMSjyWTrS_[աD5 JoUp0J`Ї>4dMs0dsjx 3ma6iڵk5<L90nٲ0^J0B)EKL,7`a]A1sٵk}H>:!7{Uwll,z}nirƍ'܌⨲7tͥիWk?x7c08˗Go߾k"6nB4jkk*p3D"F4eɎ;ʼ|FGG73rQU/K&G['G)ׯkKl<7(nVW\!sN|wtt\9󊙨v۶mTnB4S`o޼.oB###Mfmp]9I\uB!\UXJ~fBABD! .mj+O .cmgX&䢌L6|i\'ÅaN dp Hm?0 0v&1e4n5~6$Jo08/iӅ! ?\f?l1ۉ . I%I^)lm{I 2-+U9@B dxgTq 3ۉ l;3=\0(ܐͶ8dqɠE!y [3,v׈pgD6v7q?\Ljې(ť\'4lp ~{6hpBH\A#(WE!yWjhp\Ń! \UXhp\'hpWaU<hpBH8yqj,_\8gyIU۷u-pƍMwP\444':{l]*I\uB!Ͽ.RW\ѪͿgTܬ9wF޽k#/r4ou<cǎmr`D䣭Bq{ U6<TVV=9AoEGGq-;]`k*jB鶥~0A!^x5=- -[Uj>;^kz0etݏRBuB)Tl"TIENDB`
PNG  IHDR\s XsRGBgAMA a pHYsodFIDATx^ |U},", [3 x1uL_mr }M6amIS$/'K-q')qӹ8؉}Z'K[<yZ{=g^Y hn} g}5O2}^{^)ڛ^/P^5fǎOK +כf͚5vJgg+V[V;'-;#s"7nL#Ν@si_rX @7/jg':22R{:kJ^u~ӧ:uAl:zΜ9[avqgϞ'n#D\D]HpիWY:GY"U)O0tVO [,waxgjoBM&Y'> /թROljjCb9 Z8[Xmm}<[H|zыњWpep^lY_*[l9~"{'DawM_89i1zbݹ|Nٳg',K'Ξt fBNeLt!7IeIx+I<+%O:<lb</۲'1n62wܨJ'N\gtϠrm 3$9^$IB/[/=xJy4y'nذaŋMI$%cAYSYYyOצDlSIp:Ȇ>!o`0$QIOX| ,&$* K ,<lȋn eW]6~%:<<\xfǒSO='J@ԩSh+x=yulҲvuuyeUI&@ĝ;w<@'N3%Be"z=K.͌L0'EgXt/L>ئe.]6Nqa2p7 tU_־}6d>88خN8G<JID8"VIIU׮Jȍ7uPR,: V86RN|pM훈׻$RIIi tR0db1q iR2}-:zwnMwK)7z_5|~$z0J' AUU7"WGpplYp$7so輾A}E'cN$lƌJ(6zGTk'^S>r…w <tet[ŽͰ"ʼn$mz&(܀"*芁m7y uEdE"t'។) Jt [xooZHA𽁌r_W?~|x"}3F,YpSow~Q֦۠7tdiLbuOAj_XnWTN; ;n:IR$ň=YN0Z;HnUkoo%|§'L`>]644I<;<PN*dmYNt Җ5oI[Trz _g1C6B媸M(d}Ul7WOAn) =wk$XΛYfAgz[XVyfNz\rE%^}~:8ٽ{wW S[L䤔ܹs;\F#ͧpdВrwMLtU7t^JFB~ ׈Gq$ JW<ȓWe˖]ك lE< ݻwaXlo*jj[f |9_Ga{!. _O73 ~3>)| AIIW:y л<;\.,X`w91<Yn@rbx&N(<"5C---7qw InS$[p.c),->e '}j 5diB-8SJw1 Ɏ+WD%>$Sִb e4In9xJb"f8Ü0L;'>D EkP" %B ~Jz+z}>+Veqb}A]* uy$``SQW^yEɫ~^+KpkDS40rvZ41.Nܔ` ?/;X:H:_MgUPЍNAr""uFJ'PBi 9}ò*pqz&ƕi>4.H>$,9 \)84ӵ2d԰@F$S>ODqc f pEFqGM!~v:͢d E&|m۶uuu_ѷ܌O\)]]M1A#R+G dy "LW7v࢈޾}[p(7Vgt)oFѷ~[U0MqRi`4u&g:VjE:K)SD?@z{{߆M2e}uϙ0}\:{VR!i4͂ye1elQs)`[\jлPWʌ%+>}2/9oF͛mii]4 ^ho"<dA'1Kz1es"ݳgOlFŐRC7to<66\i #rs5ך~uŪ{#Z`OAB > >Ute$_:*!L'V+)$''UtAThHq]-) 2WȩwNc|͍C]mH$S˯,Y##n%+ChCVl߾}7 xDzBY-Q#S:F`<y^?~Q innDE͛"c)II5k5Hb1A7jh;Λ!a$YyvL!l8U?4"]ttNITlPW*O&uJ:xm\( s 6¢O{)JW_=$V8y Ȕ;A\ 2Ξ=N<aH .\.|:<<܈a$SN}߾}>tIJ Q|]j1#4 uNO=@JZA#*S.aaH{bs ٴi 6E#g#/Xڢxr']+B`lk/r^Mp7 zP\Tk)[\^Dy*KBظm<OqvPsIV8+0EgǎttVN*sIc fQTJv‡p#s%42bܐi}jI1T} >UeQ-MT _4fpx!<˂6Wna`-l\=== +">5$pcoMBr֭[Ջ<[>^PlIHۢYV܁y&UJH#b7 <Ƒ,][)6֭[CzX '$amAZ5z<nS"=s9D\>)&^+ӦMV^cnNA*RJoϞlJs<`UV 7}}}/KBlDv## B!0JM!OJy.3ڮjoR5.Kz+w>9>>Mwv_2R!$%0Tttt\^WķrʟoB_T\Ö-[/}Iš>l8#Id²} . C}OόЫ%6f~I|X&W}՜4ɓŁGp0=EzKgKDqɟՀ}*lC04@!KO4|O~XNOPv> +0,̧G`Q# AypKK*~lb:4$4('lJ1l.7|~`۶m Ҹ$y\lSOgRgu~XjfppZ;wn#jIqCjz^5dѾ5k_nݺu?aosxy< @c.W-HǾu1Ǽ)F̘1㯡!-TIx`ʜ9s8eʔ%]UA7/47C*i/^n\rŠ̈́'sĉyUhS*U*2!XXqC+l. nŞ O?SQhNߓ̧誊p#Vmlfu5 7 .O<G3Hde}ω}8{l]bb3گ^޾GQoh`v.cY:} AW)ܣWkΝPW`w0:S(.%;Ic?NB>w* zsCbU6)7u)?-,ny<,,2q!>Y8gIUƅtZ]+#Cc}5f;v|n<Z 555_ Oth.87|3:00vGON؆1Ve6v,b3_F?}:ȥW`0N`?ݻnܹ:AC~au QʟXRrO2tZc0!`.mTHl\uzե6W|ظRPzڌ?3o#6QW;Xc17LZøX%eABI1!)w+ rkH'BHjE`>'><=nh 0hUU7e##2EЯѸ4'c)Awc,[uuIYaÆFa{>|xӧpL5鵁 }Cz^.ce2ÎQ\h|V LlG99`o7>h-\M?G;ѱuŪ$s_Mw:ĤӸ$e%IrV.t5$>wR2\Tү NR ru[/9l\%m.7ظH(ξ ӟ_PO DݻS+WD{{{uď!)d^Li| U:06 "^ő $-PMF,^0yHxu( @ԩSo0KfgN0rQᅸ]>OŦ&%LYccŅ-̳ Z"4*ei:mڴoI?KEJk8j|;F?Sŋ{ Μ9}=vI}OABw\RP zD5pkĶѧ>wH7J'c`P$k\}HӁHT _l\&]%Io23 ƉHpg(`*0Di_?a$B;ѱAssI"ظ L>lDHun?l\ < uŪ$AeN|%nis.^e׮][ī ڿZ].!A5?w{#R ׏k4>Ŷ DQU { KkfBӧ Wc;lVpߖxU~ssiSm۶W!BJ GZM@ۡ>%(Q4OIUE~KDa-hFt/nw1-<U]]}CdtPJL@A˅[4hp $ITÂ"qXPF`XVr˓H1֟"(;X,@ "mtlvXqqtLne\ԥIR|IQym\/IKr s( WHո$%TDlۮNgc~mųq ٸW`bmmmgGϯtlvXqqtLܽ{wEArDLb<[Z[:¹IVG P%7n܈._\)~@ q6hH !풝`ĕRQ\1frp9qW" g[^tH'2GEW.+T\į]RqW_A"ͅs-T#%$f*,cBXD7o|T !Ŀ2f1+Ox̙`GcwB 8>BH) FW\3b /n煞L €fnal78 nyIln:BH*zӿ>u7Sk3:ÀIֈΎw p7v-3[zg3܎'d@،#G,eB)$e+VYq ZGV!ğĉīcZZZ~EyՈ+ !RVXz?~auVBIQZW+X )IVRp\###C %FI['|8R8.}|xsVKK_E7^%סԛ̳gϾX!/^|M݌) p~u3Z__2 sWK/)ySkהk·l}UZ(<(83ysH?.+P֭[ ?txx}zԾQ^exyfEQ/UgYEIt/s`K'&իW2{hWWWǀcVd,[2yBR;vQ ئڞ CWS:%lQ4?r_}U|f 3 3QdJ GC9yϞ==jr|}ȑrС'Nhp»t)"5rgf@N8u#ܤrIfęyMQm`ׇ}ěY\Hc;|ғ'OW-0äACCC> >~v}Ob>htUnI >M)e/4cǎ=f@Pߙ3gUo۶f_E R\pM*<plH3DMuXPOW\_X~ii`mh !Aúx,\ yElq;\d .9'78?ĭ0V"&L#FpK]}Z&Ƶ>I0+>ꋗtsqև YQ7?ԑfRHX'(?xاM6; pB8]$>* sKl" I,&Pv: E=!~Tz={~E#OO?kѢE>l'0ӁrE"1 I ].SP8 V:PT50[Xc|ʕ+ h׷S*(% H@5´S~\U& 6toT#|7r<uuuWTT|ag|Wj(e+^QwMa\Ze2GQQoJ<VUU&^<:EӏTq;K2(mqby#P*ĩ nPXz-wN7nԗ{x1j,WF5e…ooD1g%Hh)MO1J(~^hŤ޽{ף_X J@H}رiFɖ2-Wuc3?q*!9h}\pTWWgUTZqWq?Dn[Pn?A)|EM[e(q{${ d8pK]kw/}뭷tht۹!yB}FplCL;k9@5MMMQ3H>GRMF>$;R\FB}3swBZ74<8äs"o"3!ӲO).(2R2DbpwwT۷[\\).À[3!QHCqyVվ,Y\*.À[3!Q2DHXq!v;IV|MUƜ9sAcSw'&NE{ \H']*0>ED"uΜ9pQ\Hgc wKZΝ:uwy/p/H:o޼%. - o}}_|bQW& N7 /iS2DHeP."|n ?qJO$l 4?pt)u+L4222aA㪩8x;Wf}o˄<<HKtuy|dcq:$s>s`Ee+s>m|PV~R;Iv}݈` B y8pRI :1{ƍ 芇p⶯~B~7k<A/_Ρ>&XjժmgB ?}&\OڜBryV |Ʊ{MX`V=X}>3bfW֤ʏ7Qv!d̈􇲭 fjݴiIWCCC-H# o0ckZ3<ltl#/5Esf&X2 dɒ_m K.y,y0>G,9x~3WR#xķmewwt#!$07, S XoQXSc(b?z$%DOIoQjGEBHQyX)x֬Y)BD"M1a_ x3P ,o^cj&ыNŭ \ %CBʚ5k>,nǕl'>'(}= WIHɵʶ,n.*"/;PNe2 ')/ mqI7D %|T,̣T}$$Pqo& GE !C.ZqtswIysLRIH pxcҢ8Q%xe||ū.&X7aEVuuu4z{{$?>Z'2E~U hŊ?05B"X-nػ">PhȻpߖqK/c!ϔi%W*%CPHz/(?Z*-5(V͛c]Ǖ(ʟF^!B! 5 BUU7ů&۳gO›;LUGZVڲe~Nڽ{wVjEkUJ@,z(e`? (%+&ĄJl7Vf1mjj$+E&i/`ttt\ ER1 Vż _wE޽{7:L$_-c3{?׫<vMYYRs++"eN=CB^b(z==R'HAJ45#a%*;tZ\v (.kUqyW*.fR\o\vug T\m 4θt"a&4*&Y\JqӵIg4.T\$̰+CwH"$pPqQq,cKlE/]{}RZNxkj,MHp`te#_ -Ś (:cƌ;u7pW[[w޽ɔq#VfDOHqoD׮]#W@X^QsYԩSo1C{{ǐv޽"G13Ge 3g7mtuc$B&fm FD ѣG;N<@T>>}4KLaH# cyIq:_ٳg 35@A9rdQp۷om+aTp0`ٳBdS~$0N8ъ/^8 EOR@^(:<fxR36`?aaz[Ȉh7o>:o޼ߑD_ܷo_7!#>ҥKA.:ɣ \"+qcL؇i\e2(d* vTWY5 N43ΑckF8}΃_HkkBr% '===@.Bx'xKtB0|gg%У>u-Т} Ͽ.~]|/Pj璠O޽{W,.F+dD/_sy<7ynGҺ$v:WIsN?o賋&!ǓBz\+.It Ņx#,rHB>adCq%eJq%ĥrm9A*.$/e\dqtҀ\*.tθDM8'HCEDqI6=6>*.$99OHa^~]7⓮²`:W =$0Pccc 7,gֹիW~Z_|ipa]ZB!|N$( ?">ǹ|z AKm%F;a\iQ/WoL ۶mS6J$0BDC~HBE|IEɓI^T\$_."( Ņ4k[ӟ5b VH*hqip.l7W8MLI`޶I 'F4K7 PqTPqAERAE|IT\$T\wPqTPqAER!OPqTDts!vy5D q022R+NtfCHq@xAT D@(?"0?~ӧO?3LBOjmm5Fc1Sʚ&N̙3ub!ğ:uqǎ{L+1B/xLjillٳg1{X866&A_!KX!aTLsO(#uB=8QqBNj.nYQ1ox~bpQ Ӿ@Sm7Q3m pgMtssx`o;!`||<"N/.^8K!m-~gZ;̙qon~oOɀF8%J: .8#wqni0t€ٶ ΰD逽mҹu mי '>|H"$[0۷oO|!~XeN>=sxx^,X! XYDO<@2XYP`#BF3~ҥ'ݻ{׍xB|R\555_lGϟsKª5[n=4::ڬ# !_rڵCUJK[?3BQ%" ,_f͇!W%K|dԩo` ҥKaժU?6V}80yI#\&#U<!V87no}7O}7uh~uR^}}} K\Q~'$TVVҗ|+%9> ѫW=<ܼyyQq'$PqT J*LqQieHmSSMXq;wnFOOϨ抴׫}K/}藾%sW(Ƌ5I̓O>yPhmmmTMebg* }ttt\A“eЖ-[ MLz;zwKEtnJ9+vxكApT(Zm2ʤ˃{9),{5^{MC1y2Sv0 AΜ9zG*L * :Ω&$JtXlҮ/4βCX,*݌b Mܬq5ڱc6X/BP)t$ˁh,۶mۋe[?q <&o 1@QǢ+ W8CGd|3QeB] f!tvvņm;ΧVͣ>#tSӧqFg*W 9ŮǙ6{̮x#n=;UPFC0f(b%KʀqUEZZZnGwdЯfpc fihooG_ y 0mqxf,-6@`,8S2S;wn CGc'!+!^*F} es̙ ܤAz-f;Qfs ͤ`+u!]ߑ#G|3KEv}±>Eٷ4(رcaFS&Y(SJGʝO}JS.it'e?~lf =z]W1s^ُe& W++UtMB\Xǥ2 5p`z yӦM'̙ETpO"xD>l'\4B3'[U*mo5 ^7||Pg [\qƀ*3Vhec.4\D3n l? 54ZH>sʱ+ (hNҰAI=>SL'JAxpLꃕkꃂE&[a#hww^(wܙ@ @iU8E_Th, 4YfFO ^L hN!JinO| K Lj JŋC?"&7T/ +t"Pl4=řFo@>ERէ,BL%^' (1#P;<呲իW8&L`p 9,)'8 44݈@ :烂VL_\5rGoy26"ħmMAJQ0}w0<,Y߿R4,)),+.Q`ݟ\xKy~U"o eڒ|PpA466~']%*++_c< ՙ~t’:v"<^p]FdӋ5Q* ih>Q2lC7 7QJ V\oa.jѝڢz',)m9@ͤ6Pq X_4eg(K\#?yoh#-PRDVHq 冷/x>+ƠǼ}eD߿*-[vY$ *'# \<}}OrڵkCX4`Qa̋R֒xR1TR98"n%O+萏n޼f E=%x(a%`a+Q-$,|HkA<ORM[\ >W x@Q/ @ kF>^Dgz斖C{r#Ŵ}ԩot޽\$dh#6/qm1<ºSTe?O'xHk;B&AŕGp\[n}VN*"0m|"#ʠō ߢaI+.|7PO'Jqmf=HZ<.ה?۪00=k֬ooT1ye, N} W ݗv'ݻ{1.9/p^Ij7JªHh(^Byy};&p<8.}%  wxNx+I%[G2+%R#~TX0c潒pv“AQ ܂.PJ49sxU'<K :(.L$u~H (' 1 Or W1qNxR0J{ngR?\PE87/I >u_(z))z, ;5s)h` q&,VG0ڨ^T(I̾޻wOIny뭷{n{=~isFV 8.,;Ĵpk|4DBUPG)类aRq BY˿K7!ea&GpqrQc:]]ͱޓ}V\͘ |MQ .Q ǵtqp3(A 1niT pUyG#3L/Ce0t/ \q9GF}t >A^#N)&r<*.X:Ü`^qn/0&:lܾ5zy8ɦ\C6ePq}3ǭDz/ Լ*(W]X\nlM7N+3<k2>6}*,{'Y^5 06餱lc/jq%"Q wsdΛ1t…MU]dyřp7H.*,g[&̫+PSN:2&4C3!  `fS&|޼y/[DeDn&[ĶYniߙ@DVFrMx"7WPq}ڽcጳ]#fvs.BQ>=П3gΟ;vl.J|[iS >L#fepXXpsK öSLf<!8Xj IػR!O>(p1@4vmav \AUXiFq;zhY(lŅ0;I~)%nsf{̤<;K9/XBQ\ni+.J o@$MSqaUu9KLi~ΝOb;Sg >Xl.@BEfU8ӈ _+Nqc&,sd'&u7(~z}.=Qa[6۷oߍ#7aa. 9Z \5B<+mpsD!>htႊ. yPXڒx8>csR찰Vk T\EpQť?V*8΍F. >"Dϟ]cA1Ӷ :l nx䙂L1Rhp\E_079y'|r]sxqik G5$\hAq=T~"Ntppu?"7nPӱ`_yKQ]+HbڜR(LC hQt4%P0b蛋M/^|M\P gΜl?O?#G,۴iI^UUM E>B)JYaNsse[)@I>|CCCGCc}P!ZȪU~KS`uj|&.";tЊ={`2 !dL\YA9v\YO J,Ǐ_(ʩ}&6k yE(ӧOĴ0x@=+*-SB2A)+ ߰aðlǕQ+RcJ@ʆE& VfѢE)q~Cy  \v!0P`FYjҟt#Lڰҵ*>?!(LyG%iHTG?f(e0W7"qj&b6b8VSoݺYQ+FGG,P ebKo+1Dܹsy K#P .k JC[¤zEQP`"(Αno"wڵTBHhP hɒ%(qetҟZaF`_OSۛH<}&dzkgA.X+__Fo"7?DBrr%L,mmmWM=OkYAQq ) TS_Y0%9X2vѵɶmqWWWUHHXA#$waC-]%#`#<ช<!y'z54 ̗ŜmBsnN8!&DsKŅ*.*.nV\(HȶB).a$Wd[)rrMeRqSlˤ"@Nf;+7۶LcDiyLx"$ʛ-ŶL3N*.R Mqu +.N*.R duB).?BEJ(.SH U -.*.nB)B)nM><⪯Y#!s&0CBKK }^tI8.N(HB tGM0I`|ɃFyݿi;! c|(Dn"iAFI,*^uQRoo8_lV I[M!EKUӘJ+?~Q,۷A>eA͛"#2(q (O:Հ ,iȠ̰"ٲe.,{^D!$g^Z2XX⩶," FDjFGG~V2PbcӧO+2,ˡ#dZN: XHxe $Rt* JբD^<RŒM[[[O%FI(GW)۷;t XNx&^ƐW*)ݰ؆ޏ>3XbPd>/KڸĒȋB!dPVI*nݺFhl RJLo#P'3bP`Pdk׮};^lڴ!m޼JA,]8` ]xqV~1#~~~zyl51Rb@a@)W),4¨{XC^h` 2/UXc.\IIWbs"-BH0A,C0A.*( bu~1(1\UVVSO#$-huuah:ѬQ.t3^PD"\~-[IWd+Vi*1B@oo ShYY[fٳgyCCí?[f͚ǎPDt쯖a8 C,H-_D"[+1KH^@?ѫih,X\z2$r3BBRXaիi_zMx)h8 3 W___cp\ bm4zq]UL6 GEWp$$LPq"$pdϖLC|+.ɮ}0Keol۸'KK)%E]vug+:/!"W˄y-ˀ|FdSf![Ĺ2EIHVqJ|ٔY>.)V&c✮M8/ !"Se޶bL@|(._ΰT~77Y\&2 (*H"$pPqQq8 Y+UWWwf8.̮;􌊣s;wPqG%qts˗/zFuc첱#$TWW\졐iyq-'G`q ?xF߿wu?^mijj)mgהVG*2X4чCIB|U%K|D7o>jڽ{w(F±24imm}ucJ^%dRV'NhBW6---+wBQaٮcǎ-XKi :mڴoahcy2Pdןihh#\#/\,!僥" qeuYE]E; .KEńU+͟??K8{7:u, e2_vF` .F 2#D1հrd;(fΜ B czHEN<^,*ѝ;wn(Ũ4, +  Y|GݔU~B` ʕ0!!,9߁Le; .\PPbU-#`)I*($RQ& Ǐ_x/QQz!\/Z2 +HC)Aae}@aaY?AUUU}qȫʌSiӦ_SN..t(Wُj xD-/ﱚWe;* 2 L5/^>3(3(VQXLįJ LիP!>E]XN2,۷%(E咫 GP2%X'&)3aep*%K|k ׮]G^*3B0l/Ty\ s1˅rυb#G@H^R_)QWa?cY1A8`%EV[K-2ۿj97З7}oH 簿\1<u?~VTT|G,ъx{'|t}I;Zݱc6ٌ[_nplmeql׮]["?H @x#-3BpA"5q=c/`?LדeOE%WHg:x[+~BEoo8!Fn^pGŤKgƍBjkk>ttt\Q{{D,XZVM/BEʕ+;?JNAi_~Y(Hl&cMKOC1 ڹDo߾s쏶^]/g֩3vtnf?)f@U~zT'Pq! ŅKŕnlA=*.B^ʢ""W:i ^Һ(. *.(Ly|gmco'J T\$PʦL-F]^Gbq58Pq@v-M|7b~Tt KI,*.(FRrsmq!O!"W&yeRq!}"-|)vWPq@Aŕ;?T\*܁"?`R9'6b۶m:"AD7s]/P:g vm2fC?D؞v͸8_ԎLx ]B0 KBO`FWl z.&Ӏ&*-Cgg%q\*蕶S](xuB!D' g1'dikkT^P@ON!$Y 266U !71,g͚5G)lBHr(B&\w*B4!AOB .BHF HtpKC8E\nO'6anqnL팷m f30Dqni wƙmgvA4G7ɶ-ÍT8ÒO7ΐ*Mmib Y &4!A+\tj`'Jcg|txcog&|$8"d `GMas3mmsn$s۶8ܶA:aIE\>4!AB҇!$#hpBH"d .BI\E!CQZBqM˺С6@V+B wލ.X ޻u.q !PW( B( #'hEWSSM PYԼ*MQn)|Kgg祾sV B 8eNܻwF+ckYǫEU*B!ebPU>TYYmَVWWEoH\3<35B!xV )V[O?'OWjtVB!15Ӻ/Ȧ2.]###-FcB!$Cٳᡡغx,1"0tZB!!"zZQZٮz[B! m!B!YRvvʅ1`۟tt9Y: ^Ӿݏ\! WG}ԩSL:1c_5"e;S 7۶fosې(Dqn~mp wqKLmM7ęָvd~'&p!/d[ݬ3<<\q\Y27d7?/~; $J2?Y!?Hgc綍[De0C<K\y naBHaZl&nJUV[EWfHൌtÀvdlg~4qK<p7"$ B)8jďRwK 1,C&ߍ[BJz0CGGǕD"}ȑeX+pqeǼBID|pɓ'@0#ibI !BH2`XMxb̙_]bO+S«C +xB! mPU[dSںu~ׇr!BI`Uq5ʶ200+k׮-8odsq !BHj0icc$ vVGGGapvB!$ EĀzM0 uuuwرСC+;ܹs%O55E!ZqllCCCﯨG SV[[ս{nX>222_Ͻr>B!ހ1tSz(ŕa0 b! yI}ƍ͛7'g{'?6qGtR?@/^|M\l_n&dBH!{nܸ ovފ~{S__~9DU[[{ $tmB)6m](ؘ?sA18!{ۋ3$#R,|Ƀ@9G^o5GAS[10[lR8 !\WhId,2L|t䞁tQ#8 >',k}'Bc7({$rïFh> /}K\W_}U:$?-L] 0ݘK?/aX苘o qHRBH:`vhū޿_$IH?1HCCít D 8!f͚wtt\A>LiEC~'=\=\^[?u떪_WapmV!ٯ =X[lQeE<k .z36L9G~lz]2 Hc@3q @1U5"E/n!00iBj-X@!gѥ@cKO1kU# ~IELAlٲ&cN+>14UnO|TO|B[0bC@1L:`" _yfpsHc1ڵkknnٶd=П͛7w0>ڱ=\M!ր'9LJ|Uںu!|n",O eD.]9eѢEwݧ,Fx|nzO *~sFΣ[>7Iv|}Kh!'gӤ_fbOJ~-|6?>Aڞ;%t(Omn߾]|$C̘1t1hXsL2i>GՂ4^&tt&mQeӦM' _ /e*cP ԉmQ:$e !Ƅ.Ɣmnv9v`4n$%QC=1_:uwv">}Ϝ9S'7}cC;45SV\3RƄ'Q&qAIJUBO!ohh#6-K  !L:>j/LJ*y"ٞp|o6yq,C6;w>)ۮybŊF>O&m*9vcwRB>eO$8>-yIJ;OmF`ҦǏ? e;~|(_dV=!&0Ҽw^t?x`ݻ*_^J\/*«D3"O,zcLo*#p|.n\Z۷OR*f+FqvuuiӾe >|u?>яmP4̫Ego  5fJCZlØC=v e׍NSD8+ENWgϞիWa o޼']xqn Aݰa\<844Ԃ(;r21AO h!a7ĭ:F:we Y~79}or8¶فx ys4LJzPMt|8p;>$l #'Ϋd܈Dp|͸#,l=-rJ8>S\)GI%m{Ã9ȃ(_$rId #٦A8GnO\✢ns]}ƾK;1eqp.$mj%iC8ڔ^+,skp:"aZzy aB1jkkv[[r?qxES]]mcT1p`MQ$1Ojn|`83 7l0l?4܂%2, {iӿkum6P7[tn n~΄'ylw+{Q L+`,%'B:w)k%'!oSF R')J_8q-"t&;"U"Iι9>OMNea[$ǗMTI]s\5{# ap5نo?a]H=RWyXSS5WNj%E|"\kIL _mgS'Q0MPZ1ZyEҨN[mA$c{I{x-'~i+K`lK#h<--O"I[D <$nI*$TqTI$p˓H>Lt)t쏎JoPFPӜBk?&MKKt(W؀^(taHFr8=.n5`k0hp$B(=œ>!x͛$qI]c s<\ `ٱc@󪪪oJ\|z]#B}}};<uЋ)=^j8ч$ BFHh7#5VWHbp9Qmj3(>yca&toA26mB HupLJ85.}12s̯U+~V`z..ɇ zd#K#>bz`\j=WG˗CSK),S{y FJr}N9&47 Fދ UTT|]0djDmO=|lj&lǍ$\ x͂|(Bzm|k=єൌ%3}"A._qW=ˏsB‰R:a58bg/jjj^5ad/:ȌC㥺LZȜ9st~ʕ=RXn CM=@ D^u !vC]N2O04닣%nE0͍7&/~O)<K1~<ίٔ)S4~#XMSb/z`P'ʌB.|^)կ$:/u^(SncBywA`< Rpj{BV WÄ: \f!n$ws # s>}]nݿ 01 c"D`EaB=gzE‰ėUUUɶj/ӧO]>AB?۷o'AJ`bGd{Jgןt>* ޿ZSv\4v|oHAA6 o`4|`#n'1#xxc+oE|mٲx=X6&4cڨIJTofKVmqrFϧ !d5ip?sL Uᦊ+fKK6a%IQֶm؋5}eݽ>huyB-":$H" lٲݼysM+$1lp(6dɒ`bY1;Ȋ&Ed&\"_a05V4:H>wލĕ0W0" S{؃૫3I×xh}JCRks{"ۥѫQJYZ҉d38Pbx]So`B$JӯS#I!޼̟?8JA_vM։c+E6Do=~ԩo`<R SN=d8 !ABZ_փ_%|% NfUo ,IbgT\Rz(%,A֬0A+X9Ԑ$LS$Jwa :k7 fbƌ/愛<x g.Y`sO<QL\AO !@d۷o-AJ>RL2^b,922҄Ϫ1Y? :"kîxoVSSKz&x5^N]FAfB#4 rF.ŋ_fDo!)eTVVVmmC=gXK#[9~XCL 2Jb5k|QRici- pMaU~r(J͘1:sn,Sjm(WĉQ+㜒F}^`XqS#DHxD"[n3߸~z\Ao$R=sw>;$`n_L6f䩛~U跾跿w[oS܃LĽЀ\qTL۷$n@$Qdy2BQ䇻ws KeCm"QdyFOBP ƕ-a"{!@5j`Ԥ3}P`AoPkn~3XГs!vpk-oB_+H0= Ym_5 +$4kHȟ3hpaِc˸dۉYA+x"aD5 \l6\<\(6~U̫H)~3ِm~7rUf .䷱_*&7o@9\4HQ13xM|$W!Qs>|WcBY6tH7kz/sUG |·>!b\ΰD5}7hp0u .7̾9Dvop1yq" n"X6fѢEA縲7r_ S3۶fo3̉3~6v0I'Z|[祹Ǐvbp4Flܶ0{aNi vg\Eˆjԅ6l>$d*m107CLK2Iԯ1KNqoĤAX6WTYnm1i0[ŋga#G,ٻwﺶO: )K#d…<s{n +ESMmgv6Sm es GHч+lrKo 6 Kr\++ec&ٶ3xIe;Ub@ըe9ӍN`sHW;Hߤp33&X.Re/L0pcMTڵC)7o>.y"(oddV܇ŝ߿Sn䳇s'^{N6`zm }6mG]ڂxw"lۆ* mYyɔ)SS(ӉO*m1Eˆj2Lf-- am[3̹]hpx7`}3gΟ`؂> `Āq&:K,e<rRN<guʈ?~75֨LO\  yM_^x,Y\2m80n;m[3̹K|x>}7N?%jhch+h3h;ݭb[kJ[}FA->0ę<={z}_F[sSWW1b`Hr*i\#N v n0vEˆjԅ6Hf=\XK &4)Í0j`Pɍ:QHػwٞ% wUI nY'p»$r~`F[;v1wӦM'M|R$16&tGDml dmL:vBF` nmm5 ~fݛ춃5U.94HQWp.NIQ5KkzՄXcˆ:7:I |"?.ArƔqb`ccXEہ1h\+c7hp0B+`J=]@/ ,D.RBHFΉO mp h;0D&I7B+@"aWQcs{-Apxj;4 .:C+@^C1fϞ\$tttt\G5wNʭ[_aƍ\sx켄t0FPuL7nGJ E(BxxUtnOܿ?:::WBֻehq9P(mᖸaQ688)?p2MG5oIuu]mt,PmmmWz(I~Sp/C ?k֬_Cq{{ sdFM-LYUUMghii?t_~4H%rD8~B)^{[!_G͚5/%nD"ŏ41Wb.#G<GȚ۷Ce`\f3?s{P!B ,Ơ1e[B> ` 2LeǏ4a'̜^Ϟ= 7FZfݽ?o޼y/ݻw޷1B! zKUUUIC2k֬rʟ fk6 SKrePFqa!P 5tecjZn~7a͛`8rE!B Jܰ2Ȭ0?4cƌ  :𩧞cz` s =+K"cXeaI%?~0kH805dB!2 eXAa^m۶w%|a@a(cXWI 8ò.fd"]* d(C".Q05$b<zy 2`B2`<`,Sž}6${8{?GV72`؈TW}Xb* _C8īM1–ٯ!"&3g;86B!( +8d[[[ͼ4㬎;X:7J+N8kH0} אV Dy(WB!!#nXٯ{{{%zXQQ===gaXi8+1aY㬤 V^PljkPx5j8d!-Z[0B ȉB^:zZ$nׁVɽ{nDo ^p00IHNùאoC'Ɓ%{ Y__e| )e5$!#↕IW'zXSS󵶶 錳2.F@zEkH5ѳ^d!1S>^C1$B &_ ٷo_˟O4 <sKƍOmڴP@n|UOѵcǎmѳ>QL=nKcbл~S̹yEo]>s/NaÆ|щ+++-<x \&_#_BHMx'ܼ(10rh)zn׵>?+B *G)ٳgGoܸ%ҥKXQOw Likk**oƍѻwꚈ_O/&.!׆(e>88<+ߏ655e3**uVZf͇%$VZ?3>>j3uuuQ ЮDB!6ܹU;IU1Ʌo4` .B 0a6pL _ IO .B 0~2N )lÉ[XH?/\`bpٮlaDan0;ؔev:m!Yz;6a~!\N1~3,mD$+a4bgX:bH^lhpBH{-uې($+eps7x /64!$2qMDS0\#N2sK w4!$+Hzr )"f+*MhpBH<hp&4!$ 4J\`hp\ .B 0G)˗/kNLWW*++?̄e˖]GCCܻwOWB Ͽ..s7#Ν;7[lH$}u-o Uyyy}wO$<ʼn!PS'˗/N,^8ǫ+}N,X0?BH$7ޛABf̘WSN}CþQ؎K$ihh#S[@b@w^@ z:::W==="R bٳ˲7`p-Zv4Ƨ߿>yU1&0~ FϖW_@Z#2"qB!$2<<>S=@֖-[ø:tЊgϞ{!qhh ;ؑ#Gcp7mtئO gF̙ŵk>'u,~g#BHP)1sYV%,nTWWݺu~X5ѣG;N<̙3{A""(Lj{@"?~}/ 'N <!2kzvڵe?S~#G۶mۋrc#B/P=X0o߾$,nTTT|wxSCCCqmԈD`T,-0MA{ԩӧOOl3aI#ǎ[Snbb`Ǚ3g~Uʝ`W,YWB!Ab>|xicce{_wܹݼ&<~0~0S0`(xQƚ1Ĵqٳgy…wV^1{'NWnbk׭[CiӦ}Kʝp|FӦM'ql9>B! ʐAzd{1{?߰a^ `1X3a $3cŒa@e~ R`r>8v+4!2e;aaJL=/ a`,EjV tQc5[$+fhЇ/^LaC"4!@0:qw  !=F5a1d|AWLh>f!_hoM 1B!$ N{Q&%W k0  146h8_Q&K%S ҥK4J8!B|2oʕ?iX8uTzsX$5!LW ++&IWb ?sN C!7nx e;~8,Lw`k8,aX@~sB0 ?bŊ3gΟJ 0#{_}J!=4uQ+uuuY.wލwJee'| ! ,+Rgώ^v-z޽(/r.bP/1k#HҥK;w= ݻ+WDkkkHB uMމ_ٶm[+6uMį\z5htBH8 7rn߾.[2lijj)=!MfV"!A(ōWV$7sϔ/7ݫfZwĉk!ق ]]]|B34i>,p^ .B 0LN ;: \(MN>!Bp|7 qs jw#Qxа~[ .B 6LN\<F n̶ɓ(7a3Lm\#mfI\ lp^q654KZL\ ipfo's1b vq4 LW:avq16ɶs4!$@"#-4!$@ 4E!WE .B 4 .hpBH<hp@BFuu]q˗/ת[n Qٲxk2߿k"~fjhhBG)AΉ{nF[^^~dda ,GFlܸQW;vlBH8p@8q%`ht||ٶm[4|j;wnkfV.]?0O<@BzL:::7^?FV___z=nu_($FXD !(Me3<3U'N_|cc%fTQQ_f͇7۷o(;O f޼y/bS[[ǥqd̙"n޷)IY !BoPF˙3g޳y#-%ihhKS<xpճ>)Ç/=rッ?.&޽{)SSN}w@.:th.gD biooE"p̙3ȳiӦ(/aF!3a  0`Լ*q ^<c"Qc(ux?y{O:pfHէO&a⏈Ԝ?~߿y~1k֬b p=҉8::, رcIOafe9>~<C^68 z,Y~8(HfB Ñ#GZ',qFz``9pQFEb n1fJ5"U0$X2 W 1v=Fm͚5FʒtH&;mbн?,s%#0Г}>=fa}]]]?裏2 3 E0[rl۶m/ao!~&U08 `H$JX2B&Dzt̙:80v.RU8 !? (m4իL~VVV~[F#$R\W lc`0k2f8'| ŰLtNׯr?|;vxKÌ!n0$лUUUߔ8כY`0 [uG1 P$ުlqPa=Qbĩhjjz >L0pLWFdc3/^8 v8aן0KWGaW0b.\8R)Q?{^ 3B!䀸QM7t)xz}c0Өq#WQ!7LRfQn^4:+**QձAs\U??7Lh0C!|T1këV! 3(e˖]ƫ[o*uO_RSS5Z0_db_+ihB!IF!LkqAzS+| ݻ7mnx  X"0^ܘ+@$͈6EUUkb=c鑩LlLYf.\x [f? 3/Wn߿V r쿈ެJ`R3UjD'B<njᆇ/|Kcj/,[~]Ƌ 1I31NIMoU(qp/%N+1Fp~|Lrcir0 c<a;b^3f"fSe 1NA!$H+&M $F |pMSjyWTrS_[աD5 JoUp0J`Ї>4dMs0dsjx 3ma6iڵk5<L90nٲ0^J0B)EKL,7`a]A1sٵk}H>:!7{Uwll,z}nirƍ'܌⨲7tͥիWk?x7c08˗Go߾k"6nB4jkk*p3D"F4eɎ;ʼ|FGG73rQU/K&G['G)ׯkKl<7(nVW\!sN|wtt\9󊙨v۶mTnB4S`o޼.oB###Mfmp]9I\uB!\UXJ~fBABD! .mj+O .cmgX&䢌L6|i\'ÅaN dp Hm?0 0v&1e4n5~6$Jo08/iӅ! ?\f?l1ۉ . I%I^)lm{I 2-+U9@B dxgTq 3ۉ l;3=\0(ܐͶ8dqɠE!y [3,v׈pgD6v7q?\Ljې(ť\'4lp ~{6hpBH\A#(WE!yWjhp\Ń! \UXhp\'hpWaU<hpBH8yqj,_\8gyIU۷u-pƍMwP\444':{l]*I\uB!Ͽ.RW\ѪͿgTܬ9wF޽k#/r4ou<cǎmr`D䣭Bq{ U6<TVV=9AoEGGq-;]`k*jB鶥~0A!^x5=- -[Uj>;^kz0etݏRBuB)Tl"TIENDB`
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/TestUtilities/Threading/ConditionalWpfFactAttribute.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 Roslyn.Test.Utilities { public class ConditionalWpfFactAttribute : WpfFactAttribute { public ConditionalWpfFactAttribute(Type skipCondition) { var condition = Activator.CreateInstance(skipCondition) as ExecutionCondition; if (condition.ShouldSkip) { Skip = condition.SkipReason; } } } }
// 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 Roslyn.Test.Utilities { public class ConditionalWpfFactAttribute : WpfFactAttribute { public ConditionalWpfFactAttribute(Type skipCondition) { var condition = Activator.CreateInstance(skipCondition) as ExecutionCondition; if (condition.ShouldSkip) { Skip = condition.SkipReason; } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/VisualBasicTest/CodeActions/MoveType/MoveTypeTests.RenameType.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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Partial Public Class MoveTypeTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function SingleClassInFileWithNoContainerNamespace_RenameType() As Task Dim code = <File> [||]Class Class1 End Class </File> Dim codeAfterRenamingType = <File> Class [|test1|] End Class </File> Await TestRenameTypeToMatchFileAsync(code, codeAfterRenamingType) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_TypeNameMatchesFileName_RenameType() As Task ' testworkspace creates files Like test1.cs, test2.cs And so on.. ' so type name matches filename here And rename file action should Not be offered. Dim code = <File> [||]Class test1 End Class </File> Await TestRenameTypeToMatchFileAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameType() As Task Dim code = <File> [||]Class Class1 End Class Class test1 End Class </File> Await TestRenameTypeToMatchFileAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameType() As Task Dim code = <File> [||]Class Class1 End Class Class Class2 End Class </File> Dim codeAfterRenamingType = <File> Class [|test1|] End Class Class Class2 End Class </File> Await TestRenameTypeToMatchFileAsync(code, codeAfterRenamingType) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> <WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")> Public Async Function NothingOfferedWhenTypeHasNoNameYet1() As Task Dim code = "Class[||]" Await TestMissingAsync(code) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> <WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")> Public Async Function NothingOfferedWhenTypeHasNoNameYet() As Task Dim code = "Class[||] End Class" Await TestMissingAsync(code) 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings.MoveType Partial Public Class MoveTypeTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function SingleClassInFileWithNoContainerNamespace_RenameType() As Task Dim code = <File> [||]Class Class1 End Class </File> Dim codeAfterRenamingType = <File> Class [|test1|] End Class </File> Await TestRenameTypeToMatchFileAsync(code, codeAfterRenamingType) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_TypeNameMatchesFileName_RenameType() As Task ' testworkspace creates files Like test1.cs, test2.cs And so on.. ' so type name matches filename here And rename file action should Not be offered. Dim code = <File> [||]Class test1 End Class </File> Await TestRenameTypeToMatchFileAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function TestMissing_MultipleTopLevelTypesInFileAndAtleastOneMatchesFileName_RenameType() As Task Dim code = <File> [||]Class Class1 End Class Class test1 End Class </File> Await TestRenameTypeToMatchFileAsync(code, expectedCodeAction:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> Public Async Function MultipleTopLevelTypesInFileAndNoneMatchFileName1_RenameType() As Task Dim code = <File> [||]Class Class1 End Class Class Class2 End Class </File> Dim codeAfterRenamingType = <File> Class [|test1|] End Class Class Class2 End Class </File> Await TestRenameTypeToMatchFileAsync(code, codeAfterRenamingType) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> <WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")> Public Async Function NothingOfferedWhenTypeHasNoNameYet1() As Task Dim code = "Class[||]" Await TestMissingAsync(code) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveType)> <WorkItem(40043, "https://github.com/dotnet/roslyn/issues/40043")> Public Async Function NothingOfferedWhenTypeHasNoNameYet() As Task Dim code = "Class[||] End Class" Await TestMissingAsync(code) End Function End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./docs/wiki/images/how-to-investigate-ci-test-failures-figure6.png
PNG  IHDRUsRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N 3IDATx^|S6xco[5%k/kYee[{Lf $L hFSMՑd[aD~~>:<9sxΗ)q[^\<,%e^\<,%e^\<,%e^\<,%e^\<,px.gU -؊gX8gEدϋ\览iFrz <T 01x(Ǣ&UiY^E1DXcX YCT4W([*Um.uͥjVh::]ޖ➶Ҿv[cmw庞}UCj=ӫU>7?;g?A@@B+Aı#̜]|e \87vټا)ˈI Oc_@]3*pNJ)#RN$*X%6wer[j?*U*wZ]-Z]{X\jn**TZ_3νW?n z et"29q ϟbe "{<voP󙙋)kbD$!iJ ܬ}. փ Z+׊j]0p*yf~eTJm.)W9QWWj]jCsX\blvt:{*z\{7j[d. H%(-yWzuc]aC^\Oy]PHXof42iyzە}g+ )h) Q؊<(&Ny1Y"(V*W]LY].VUipjLM %Mf[[KY{:+T0# OryzribCJ3jU 2Ґ[QOJX'E43\ť~#çֺĄT\f ǕZMǴ6#V,E6^"-HYUᴹ,SW9 ]jP2ט̍FksuVy3r e`NBؼ^6wUدs'<SNLlj:|@9lfOW+_p~txmٽHLL$DPs\xQ(BiDc Lz *6&IIq~Yf)YK6V; X2UՔjKklƲFYភM. \_.ub _47ag,"j#zV5u{!mMUJU+qj?yag]& (RVbUXN+$FdRͅŪڴ2a(+7UN*)je \|/cgy1 7Ȩhqt[դ:ƨ!o!oEۦ֒Zʄǜ ݖ ]?vk3ٸd>%Mʐ` F$ċ%ti>S(<e@-Rk$EZBW zSѬ6hMblӕXX riWje \_.s#ˊD=#s?2Gy;m%vO娍bdSztq#6U8<B *ayYr1p.\UbF(Wi:Z F֤-*.*2)̅BEcje \౸R 67# ت'Wƀ 6*;LwF ̝ZH>fM٧)$P7Э-q_&S.2S.s\ǥt(/ BP |L+JNizBV:H,C*| 2POP.KXE/x,ɌU-/ia 6]KP ]\X =Je;-y]Qll!b42I<2KcyB6[8 W)rZ!V+0_7he&X$kEEZje \wK_s2JZlاeaN!z)s#E O V.bXY med VA&$Jw9 i.!0H<C'XT!&2,P 8BFZ@W"4XRC)gr6_ $ˈ5QOx<~Esք.~o67)fUġ.!̈ -bL-2 ㍸BTl 1qr^ g M% e l' D*UPj604L])Ko388F'WZŵTm5<gbK|Y\ e$FKE͉[xc?Iy%@ eҴpv252Fl԰OUk+(;SMcCU2V +Õ2AEx(DrDEi)J=DӖ zq:Z˱l2wVIÈW. 22.KƥLXxdؼs6jܔŸ QO"b',\nBFPscHKruʏ??î$ȸ0 G)'H-Ra\/(&uvnv1KklyeMGa*')j{5,E2ZgpH'y1NJe'.},j%b=6/f,+ϊ֔5xnuiNx%&ԓY:j]/-lIk˥*AFR*x>%)4xPPBX:BRr FDq9y6;@2hh&r̓LlZgpH'y9N֬x"bUy⹘̸0'jq؁|t;MM%R8ٛub1x}^f-ʂ:5?K+Fx8.' MâR19ɹdTf;TtF6; M@!H$ aT<gQ l:r\"~ۓ Hh%(Q *KK\=5jf"cr)Ӗ ۔q3OoAEvS왫Q͸# * /=/+aRҢW'e'Ғi)Ȍ ,, p2.BBiX:bXv˥8T&etˀ@@2922LI]jcⷎX[F4n~-u(?w]CPSrcZ0qM$;,֘4kV-TfKf [VTrfBJvRZvZ"337C"\ C'cY MBU$KL\qtMPZ.Uj><2 e4: $إWckӗs6I[$!vN'1ٕY΍@ƕ#뉉$%z65HZ'IEJbffLzNj& PslWK B9Q$'ITpNFꨓU4(kdvRnVwwk;d]ZGm"%I/]|)9ߩd/O^r_dw>e=}Op.dѨDD6#6e],QS5:> k&g. "ՕJ\B3#3bc[+j.Ћ$(]=33. Htit2LTc9`_R),k9 2WXSlY*UyuSV58^wd{=2۟Mn6}['\Pwp٬]܇a& 9M"0&PK"׬^d1 e"uq3Hʍ5S,2v,}o}'zq>?XʊB琥BI$]jZI5YlElT4*+mmڳw[q}U5kmvIe _3{2¬CQ<F+?-]\@b<ݔMuٕ];jEN}<ANI#Qt c C* BB`I XVQ26zz5ŜnAFՑSZ!6j8}6::Tn嚵,Xf CWQtzi˳5SZ/o [{2}=Bc^!,K+5Z}|.[ !w} .e2s 6xN#PA,IXvn& J䥕x&+>.bH1Pq5Zjj-%Qm<X 9[=`彷:=Ivmѹ]a4Sek:ZxNU^sՕ4Zk,GzuW^ՍKFJdniMwde&sˠcy 4{S}ޏK{_FCRh($6+@adc eYI8d&MecD >_1#J6Ll 5ړOϸbx[ݹ2G(AiK5L{KC6ul5vbK(kՐ)={u)5yy&UFE_3}=eڛ'Dt87o(L:ek4>C.gn0|:m+tf]>eP@o}3KwfZ-չ#M|[g)xwsn"~eCx/CpW] } ^;r$]y\I34QrRS<ZDDh;.Dž7,b WJB>eR YZõ7˜ k67jֹtKJf֚μW'69ZT u њr o~eW$@Z{^gmN*{79!n {L^lz?÷i`HJPv_5]n @ૡZpov 4[ĽwҞ h+u0{:~ OSwyw:/CW4|i</@SP'xgwJz[v!(2g#0h, &IT7)eT:RONngÌUpEvd!"B֣b,*BB9RIMr2t<Q4+v# F]Vh2F>۫{qce"]%kk7<Tk뾺zÏ^RԶuIJj|ޑ3ǟ2BC_<o|_޺sKWa=_vp.=| ^yGsAhD%n-eo|Wgͼ9MI7<=NW?n<sWWTݡ+hI:xipݠ=w5-N-4=ϜGe4Ġ p6 r! KDr&( 5RSMͨg533,0;)DpUF63܊L"x K8E!<h-[[]|KrPN.((kX9Q^{w\kWo{տV߳oDӽWݸ:wUh 6]opeyl^ S^Ǿv[a:uyq[5=c@&H맴EA=2 1)IޞZU@\v&[ʌq(h N[\i_ػdڿcsMcas9(,K)2AfpdLV + ψW¢K z1֘.U\dv /T7VlvHw7畋R"%%nj_yi{o8yv/_qkϞPlKgg\+S"4,4Dʊyg}QRR<m7f3eceC@dRf;u53]ɍg2h䒠NsŜ9S/׏4ApX"H)H2 If9B^CXYnB8scpsJkvx-:v=+LԦ!n]UpWY{^d5ҪҾBbkYe^,W{d@s5ۯ~}+/\|n:}ރ='山Xqh100ޭwקGi^wy,=,gu_coͰf,3 i?y6M'OVwO@ݡ7/ (xӕwS.̙z~ eLƻ]~tpSaB\-9%KHaS1I+)++ %ȘJdL#:fyĔ|}Jh~ّ}EJqAY囐J|$JjuɩwzzӷF_>Sw{G|=gIWkf|H"?#z@ 2]zJ_]oy[}V h6ÚtO~z^=P,ljޜj$;u5A[tbƁ}q g/wR{M3rfpX22%H(<Ef L$Ce2A$ "^Mǧ,g&/eE02W~`c#O{ȥ훶6wl&;FͤrVZ^g :qRUOH7۷>~T_߇{zyR:=(Ю2su."pX5@rrnh &6E_u>>:쭆&}ތ|?{c/NC̠{ /o <M1zB\滀={3m q 94X.̙z~ n^fq xj."Rj9WF!n EB6]DܤP2#U緷m;5TP '⑋Gv _9<ryGl`Tl#lE[kJ٩RbT)Eno\}ґc-יXdG/<yeّrϠq+iޯnӜnp~[j[lFS ;\63;~pWs {nt|pkk4Az'6&0{~,~Ԕ; :Lz^śSoNh_a;n&mr,2w<o0oN'yNs]W~<Z.csx"!"Q4:Hóe6JUqUQ 5rxl :MLQa|ڎ#w k7u]:lmő}Q-=}8!cZ b&Y Gkxkӭ闶4=7v6n(f«I$3Ռ|{dc\<APX @),UڵVBca>֬j.SaVj:GQO,UC[l<oね=Ƿgњ}}<-<?")3ćU0̄Mݔ?6\v?xuC͎͛7Zje X˦ųyMFHb yzqS<Բ}skwmlq-宍m:gGkޡ{s_< Ә,Oq񊁄(;*H*[3#jQmoV: ^-?yt^STZgp#alġ(V]Pcji(pvVol6ܾsKώMCֆ6Gx]mæ.dٍ=v߳ \<unݿ|Q[\[lSZ.tE-DT3ufƐ nħe%  թX+uV<b.q>ǓX2JEp^*+.X[eytKk:ghHoSXYv׶G6rf˧w=󹃛=oxowA,p\E;âw-],3<b0}MSU5+pWt61RD1ZbY\ eBI,!)[*$)EdSXZjTn5ט M)a]"NNf\g  .|צ];_>O^|>gn=<@%\wlUtixgbHjp|ȕ'G%`+ 9Iᚬnnn :9!je ޗѲR M g)tSfufKt"Jƫ :ٱQeeHpѵ;˵M];7_87N\pIPY; 4ʡ 1'%٨}WlZdֿrVTzVZ 5ϊ6c6ޖbzMc| 2POP.E Md+ ]We46O2INehk47ln^]f0PwAo066;rhPg/_8_oi?>@<DgǡwQѩ1!Qv9~YT`XuU& :+@@B=AOH.9*-)k4N)1WT[,ξ:=Ñ[ʶvPPu a[I;P,v:,rÞ_i3'3HԑR"Z%ZeY{hj ^?%je \GKH82JCpe<<,*$JZ:$䕕ږ&KWbm톁[<yt۞?ޡomh(XHY^65|ժ#䩘W%/|IRz߻&%% 6n&$( lK֩yyY\ e4v/20jBLRSRJN-*dLUԺu6<4kﶞM#]ՃUEunZem]ܔǖ}&9q<r??ɷ_v_n>br^<^!٪Ú)4iVQL `} 2PO.KhxJAȌ吳 4.ϧ$dR1MF՜o+7 !dg' -4B\m)jԶW8夗i=%RCɽʒ{qEEַŷ9׆,>ܡ&.+`dY\ elrPJő3 Wɨ*@PSBDqni t%ʺ Fΰeۻ?^(诒w .&c^ֿ?W_>iGsӯ.A\]i4U^k/ܺ~kf`|JJV| 2POP.cSDR%ga*RASh|DHpqBN@CQ5Ĉ|"V 47jϛ}UݭN|жf z2<{ac??Y}'t'^eH"`;'nߺ|탳 V/uVzr,d-RJJAI)r 9+I$)$4A\V24ՕTmԾwt{w$.Ing᧖eg_#??ttS?s>Xxʅ߾~W Y Y\ eBPBǑ`pLWȩ EOqO䬔Ȱ~G#8\\T$-n_W?4ܴmSѵmxs>gv7E \E\dSảoq~]i]OS??ɼOB ܽonouhCG0O w&@@B=AOዩXbN%eRFDX|ҧVYLzCflv.+ T쒒ݱmc]u&FSbc,fݜб8|ӑ/>oү} ̍gHV>d_oVo}ʻgJufG?uVz *Ae˹xtҪ0*&Ds NXLDJR:f/tUZCu[7 w6wVw}UgG34T-oeo(&FrK>jXEd%z'6J۾?/緿# fN_uVzr S.a2)T$ xTy'b<BvUuCIk{EOO@]G(9z6 8yd˅*K%ZrM|X@Xh2ĠYBա7Ō;?/n}mSZgpH'(Y2 CDfa218XKgR!I("x㞑]&PE<sX,-,K$22NFmǎn={gWrmJ-ܞVY ^Q|jt_u+>3~lk_}cdžխ/.:+@@B=A+g\$SsdK(be.c48E!e qaQ&`RMK׵es=Glz?sj/U5BRN,%iw)ћϭ~q;ϵSyG❃;z|p_>oW~uVzr.K,<1D">5\ DRqؔeJ &P4[׭:=-{v;|dW ۉY<M\K+U0{,$}u[}rS=hyHݥnKU9[@@B=2pB>  u P  u P  u P  u P  u P  u P  u P  u P  u P  u P  u P  u P "\vsw~zMpukMKMK?.|o2hktkK廿@W*KX39u !nvȺ̏j[ Po[p٣ pqY eeppُ2 >c~C4|"_yxzs[o.ϘqkTDK m} *xA`~sQ1 ӹ4M|{|n_Npg][߿x~ҜR !\" # #. ,]}kr|1s&?zT5iˠ <LvG=jqc :00f2OT2ҳ8xe3xA ynir/]gliȫi $7eoI. hAU,]<;y5VC "De+ֻ>ALqФY`x|',\Hf04>M9;MP9?L7c1 p#27EL+z54)e%MZ.xg%D AOeS&hXv Qs뮅A)o. J~Lps{},`.xD]:4' 5nx:e^]Sewyf/ȳ.#ee0Ϡ]f3i9@=-?Tz7y7jwŁ *o:+M0˼S⤭'Jf.@.x.LF2_N T{GC{{,{,Vw.s$OƼ'7Lg޼w{ĬN$e?e84'r֏ 2;?xb+ee~\ x6 xAω ^..e菱o?-/K+ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\q郯>˷A|ys|t.e>:s 2(\%7>o<@%e^\<,%e^\<,%e^\<,%e.$IENDB`
PNG  IHDRUsRGBgAMA a pHYsodtEXtSoftwarepaint.net 4.1.6N 3IDATx^|S6xco[5%k/kYee[{Lf $L hFSMՑd[aD~~>:<9sxΗ)q[^\<,%e^\<,%e^\<,%e^\<,%e^\<,px.gU -؊gX8gEدϋ\览iFrz <T 01x(Ǣ&UiY^E1DXcX YCT4W([*Um.uͥjVh::]ޖ➶Ҿv[cmw庞}UCj=ӫU>7?;g?A@@B+Aı#̜]|e \87vټا)ˈI Oc_@]3*pNJ)#RN$*X%6wer[j?*U*wZ]-Z]{X\jn**TZ_3νW?n z et"29q ϟbe "{<voP󙙋)kbD$!iJ ܬ}. փ Z+׊j]0p*yf~eTJm.)W9QWWj]jCsX\blvt:{*z\{7j[d. H%(-yWzuc]aC^\Oy]PHXof42iyzە}g+ )h) Q؊<(&Ny1Y"(V*W]LY].VUipjLM %Mf[[KY{:+T0# OryzribCJ3jU 2Ґ[QOJX'E43\ť~#çֺĄT\f ǕZMǴ6#V,E6^"-HYUᴹ,SW9 ]jP2ט̍FksuVy3r e`NBؼ^6wUدs'<SNLlj:|@9lfOW+_p~txmٽHLL$DPs\xQ(BiDc Lz *6&IIq~Yf)YK6V; X2UՔjKklƲFYភM. \_.ub _47ag,"j#zV5u{!mMUJU+qj?yag]& (RVbUXN+$FdRͅŪڴ2a(+7UN*)je \|/cgy1 7Ȩhqt[դ:ƨ!o!oEۦ֒Zʄǜ ݖ ]?vk3ٸd>%Mʐ` F$ċ%ti>S(<e@-Rk$EZBW zSѬ6hMblӕXX riWje \_.s#ˊD=#s?2Gy;m%vO娍bdSztq#6U8<B *ayYr1p.\UbF(Wi:Z F֤-*.*2)̅BEcje \౸R 67# ت'Wƀ 6*;LwF ̝ZH>fM٧)$P7Э-q_&S.2S.s\ǥt(/ BP |L+JNizBV:H,C*| 2POP.KXE/x,ɌU-/ia 6]KP ]\X =Je;-y]Qll!b42I<2KcyB6[8 W)rZ!V+0_7he&X$kEEZje \wK_s2JZlاeaN!z)s#E O V.bXY med VA&$Jw9 i.!0H<C'XT!&2,P 8BFZ@W"4XRC)gr6_ $ˈ5QOx<~Esք.~o67)fUġ.!̈ -bL-2 ㍸BTl 1qr^ g M% e l' D*UPj604L])Ko388F'WZŵTm5<gbK|Y\ e$FKE͉[xc?Iy%@ eҴpv252Fl԰OUk+(;SMcCU2V +Õ2AEx(DrDEi)J=DӖ zq:Z˱l2wVIÈW. 22.KƥLXxdؼs6jܔŸ QO"b',\nBFPscHKruʏ??î$ȸ0 G)'H-Ra\/(&uvnv1KklyeMGa*')j{5,E2ZgpH'y1NJe'.},j%b=6/f,+ϊ֔5xnuiNx%&ԓY:j]/-lIk˥*AFR*x>%)4xPPBX:BRr FDq9y6;@2hh&r̓LlZgpH'y9N֬x"bUy⹘̸0'jq؁|t;MM%R8ٛub1x}^f-ʂ:5?K+Fx8.' MâR19ɹdTf;TtF6; M@!H$ aT<gQ l:r\"~ۓ Hh%(Q *KK\=5jf"cr)Ӗ ۔q3OoAEvS왫Q͸# * /=/+aRҢW'e'Ғi)Ȍ ,, p2.BBiX:bXv˥8T&etˀ@@2922LI]jcⷎX[F4n~-u(?w]CPSrcZ0qM$;,֘4kV-TfKf [VTrfBJvRZvZ"337C"\ C'cY MBU$KL\qtMPZ.Uj><2 e4: $إWckӗs6I[$!vN'1ٕY΍@ƕ#뉉$%z65HZ'IEJbffLzNj& PslWK B9Q$'ITpNFꨓU4(kdvRnVwwk;d]ZGm"%I/]|)9ߩd/O^r_dw>e=}Op.dѨDD6#6e],QS5:> k&g. "ՕJ\B3#3bc[+j.Ћ$(]=33. Htit2LTc9`_R),k9 2WXSlY*UyuSV58^wd{=2۟Mn6}['\Pwp٬]܇a& 9M"0&PK"׬^d1 e"uq3Hʍ5S,2v,}o}'zq>?XʊB琥BI$]jZI5YlElT4*+mmڳw[q}U5kmvIe _3{2¬CQ<F+?-]\@b<ݔMuٕ];jEN}<ANI#Qt c C* BB`I XVQ26zz5ŜnAFՑSZ!6j8}6::Tn嚵,Xf CWQtzi˳5SZ/o [{2}=Bc^!,K+5Z}|.[ !w} .e2s 6xN#PA,IXvn& J䥕x&+>.bH1Pq5Zjj-%Qm<X 9[=`彷:=Ivmѹ]a4Sek:ZxNU^sՕ4Zk,GzuW^ՍKFJdniMwde&sˠcy 4{S}ޏK{_FCRh($6+@adc eYI8d&MecD >_1#J6Ll 5ړOϸbx[ݹ2G(AiK5L{KC6ul5vbK(kՐ)={u)5yy&UFE_3}=eڛ'Dt87o(L:ek4>C.gn0|:m+tf]>eP@o}3KwfZ-չ#M|[g)xwsn"~eCx/CpW] } ^;r$]y\I34QrRS<ZDDh;.Dž7,b WJB>eR YZõ7˜ k67jֹtKJf֚μW'69ZT u њr o~eW$@Z{^gmN*{79!n {L^lz?÷i`HJPv_5]n @ૡZpov 4[ĽwҞ h+u0{:~ OSwyw:/CW4|i</@SP'xgwJz[v!(2g#0h, &IT7)eT:RONngÌUpEvd!"B֣b,*BB9RIMr2t<Q4+v# F]Vh2F>۫{qce"]%kk7<Tk뾺zÏ^RԶuIJj|ޑ3ǟ2BC_<o|_޺sKWa=_vp.=| ^yGsAhD%n-eo|Wgͼ9MI7<=NW?n<sWWTݡ+hI:xipݠ=w5-N-4=ϜGe4Ġ p6 r! KDr&( 5RSMͨg533,0;)DpUF63܊L"x K8E!<h-[[]|KrPN.((kX9Q^{w\kWo{տV߳oDӽWݸ:wUh 6]opeyl^ S^Ǿv[a:uyq[5=c@&H맴EA=2 1)IޞZU@\v&[ʌq(h N[\i_ػdڿcsMcas9(,K)2AfpdLV + ψW¢K z1֘.U\dv /T7VlvHw7畋R"%%nj_yi{o8yv/_qkϞPlKgg\+S"4,4Dʊyg}QRR<m7f3eceC@dRf;u53]ɍg2h䒠NsŜ9S/׏4ApX"H)H2 If9B^CXYnB8scpsJkvx-:v=+LԦ!n]UpWY{^d5ҪҾBbkYe^,W{d@s5ۯ~}+/\|n:}ރ='山Xqh100ޭwקGi^wy,=,gu_coͰf,3 i?y6M'OVwO@ݡ7/ (xӕwS.̙z~ eLƻ]~tpSaB\-9%KHaS1I+)++ %ȘJdL#:fyĔ|}Jh~ّ}EJqAY囐J|$JjuɩwzzӷF_>Sw{G|=gIWkf|H"?#z@ 2]zJ_]oy[}V h6ÚtO~z^=P,ljޜj$;u5A[tbƁ}q g/wR{M3rfpX22%H(<Ef L$Ce2A$ "^Mǧ,g&/eE02W~`c#O{ȥ훶6wl&;FͤrVZ^g :qRUOH7۷>~T_߇{zyR:=(Ю2su."pX5@rrnh &6E_u>>:쭆&}ތ|?{c/NC̠{ /o <M1zB\滀={3m q 94X.̙z~ n^fq xj."Rj9WF!n EB6]DܤP2#U緷m;5TP '⑋Gv _9<ryGl`Tl#lE[kJ٩RbT)Eno\}ґc-יXdG/<yeّrϠq+iޯnӜnp~[j[lFS ;\63;~pWs {nt|pkk4Az'6&0{~,~Ԕ; :Lz^śSoNh_a;n&mr,2w<o0oN'yNs]W~<Z.csx"!"Q4:Hóe6JUqUQ 5rxl :MLQa|ڎ#w k7u]:lmő}Q-=}8!cZ b&Y Gkxkӭ闶4=7v6n(f«I$3Ռ|{dc\<APX @),UڵVBca>֬j.SaVj:GQO,UC[l<oね=Ƿgњ}}<-<?")3ćU0̄Mݔ?6\v?xuC͎͛7Zje X˦ųyMFHb yzqS<Բ}skwmlq-宍m:gGkޡ{s_< Ә,Oq񊁄(;*H*[3#jQmoV: ^-?yt^STZgp#alġ(V]Pcji(pvVol6ܾsKώMCֆ6Gx]mæ.dٍ=v߳ \<unݿ|Q[\[lSZ.tE-DT3ufƐ nħe%  թX+uV<b.q>ǓX2JEp^*+.X[eytKk:ghHoSXYv׶G6rf˧w=󹃛=oxowA,p\E;âw-],3<b0}MSU5+pWt61RD1ZbY\ eBI,!)[*$)EdSXZjTn5ט M)a]"NNf\g  .|צ];_>O^|>gn=<@%\wlUtixgbHjp|ȕ'G%`+ 9Iᚬnnn :9!je ޗѲR M g)tSfufKt"Jƫ :ٱQeeHpѵ;˵M];7_87N\pIPY; 4ʡ 1'%٨}WlZdֿrVTzVZ 5ϊ6c6ޖbzMc| 2POP.E Md+ ]We46O2INehk47ln^]f0PwAo066;rhPg/_8_oi?>@<DgǡwQѩ1!Qv9~YT`XuU& :+@@B=AOH.9*-)k4N)1WT[,ξ:=Ñ[ʶvPPu a[I;P,v:,rÞ_i3'3HԑR"Z%ZeY{hj ^?%je \GKH82JCpe<<,*$JZ:$䕕ږ&KWbm톁[<yt۞?ޡomh(XHY^65|ժ#䩘W%/|IRz߻&%% 6n&$( lK֩yyY\ e4v/20jBLRSRJN-*dLUԺu6<4kﶞM#]ՃUEunZem]ܔǖ}&9q<r??ɷ_v_n>br^<^!٪Ú)4iVQL `} 2PO.KhxJAȌ吳 4.ϧ$dR1MF՜o+7 !dg' -4B\m)jԶW8夗i=%RCɽʒ{qEEַŷ9׆,>ܡ&.+`dY\ elrPJő3 Wɨ*@PSBDqni t%ʺ Fΰeۻ?^(诒w .&c^ֿ?W_>iGsӯ.A\]i4U^k/ܺ~kf`|JJV| 2POP.cSDR%ga*RASh|DHpqBN@CQ5Ĉ|"V 47jϛ}UݭN|жf z2<{ac??Y}'t'^eH"`;'nߺ|탳 V/uVzr,d-RJJAI)r 9+I$)$4A\V24ՕTmԾwt{w$.Ing᧖eg_#??ttS?s>Xxʅ߾~W Y Y\ eBPBǑ`pLWȩ EOqO䬔Ȱ~G#8\\T$-n_W?4ܴmSѵmxs>gv7E \E\dSảoq~]i]OS??ɼOB ܽonouhCG0O w&@@B=AOዩXbN%eRFDX|ҧVYLzCflv.+ T쒒ݱmc]u&FSbc,fݜб8|ӑ/>oү} ̍gHV>d_oVo}ʻgJufG?uVz *Ae˹xtҪ0*&Ds NXLDJR:f/tUZCu[7 w6wVw}UgG34T-oeo(&FrK>jXEd%z'6J۾?/緿# fN_uVzr S.a2)T$ xTy'b<BvUuCIk{EOO@]G(9z6 8yd˅*K%ZrM|X@Xh2ĠYBա7Ō;?/n}mSZgpH'(Y2 CDfa218XKgR!I("x㞑]&PE<sX,-,K$22NFmǎn={gWrmJ-ܞVY ^Q|jt_u+>3~lk_}cdžխ/.:+@@B=A+g\$SsdK(be.c48E!e qaQ&`RMK׵es=Glz?sj/U5BRN,%iw)ћϭ~q;ϵSyG❃;z|p_>oW~uVzr.K,<1D">5\ DRqؔeJ &P4[׭:=-{v;|dW ۉY<M\K+U0{,$}u[}rS=hyHݥnKU9[@@B=2pB>  u P  u P  u P  u P  u P  u P  u P  u P  u P  u P  u P  u P "\vsw~zMpukMKMK?.|o2hktkK廿@W*KX39u !nvȺ̏j[ Po[p٣ pqY eeppُ2 >c~C4|"_yxzs[o.ϘqkTDK m} *xA`~sQ1 ӹ4M|{|n_Npg][߿x~ҜR !\" # #. ,]}kr|1s&?zT5iˠ <LvG=jqc :00f2OT2ҳ8xe3xA ynir/]gliȫi $7eoI. hAU,]<;y5VC "De+ֻ>ALqФY`x|',\Hf04>M9;MP9?L7c1 p#27EL+z54)e%MZ.xg%D AOeS&hXv Qs뮅A)o. J~Lps{},`.xD]:4' 5nx:e^]Sewyf/ȳ.#ee0Ϡ]f3i9@=-?Tz7y7jwŁ *o:+M0˼S⤭'Jf.@.x.LF2_N T{GC{{,{,Vw.s$OƼ'7Lg޼w{ĬN$e?e84'r֏ 2;?xb+ee~\ x6 xAω ^..e菱o?-/K+ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\\:ee@\q郯>˷A|ys|t.e>:s 2(\%7>o<@%e^\<,%e^\<,%e^\<,%e.$IENDB`
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/CSharpTest2/Recommendations/ClassKeywordRecommenderTests.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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ClassKeywordRecommenderTests : 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 TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [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 VerifyKeywordAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyKeywordAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyKeywordAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyKeywordAsync( @"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 TestAfterRecord() { await VerifyKeywordAsync( @"record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttributeFileScopedNamespace() { await VerifyKeywordAsync( @"namespace NS; [Attr] $$"); } } }
// 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.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ClassKeywordRecommenderTests : 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 TestAfterPartial() { await VerifyKeywordAsync( @"partial $$"); } [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 VerifyKeywordAsync( @"class C<T> where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClassTypeParameterConstraint2() { await VerifyKeywordAsync( @"class C<T> where T : $$ where U : U"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint() { await VerifyKeywordAsync( @"class C { void Goo<T>() where T : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodTypeParameterConstraint2() { await VerifyKeywordAsync( @"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 TestAfterRecord() { await VerifyKeywordAsync( @"record $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAttributeFileScopedNamespace() { await VerifyKeywordAsync( @"namespace NS; [Attr] $$"); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/Symbols/Attributes/CommonTypeEarlyWellKnownAttributeData.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; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from early well-known custom attributes applied on a type. /// </summary> internal abstract class CommonTypeEarlyWellKnownAttributeData : EarlyWellKnownAttributeData { #region AttributeUsageAttribute private AttributeUsageInfo _attributeUsageInfo = AttributeUsageInfo.Null; public AttributeUsageInfo AttributeUsageInfo { get { return _attributeUsageInfo; } set { VerifySealed(expected: false); Debug.Assert(_attributeUsageInfo.IsNull); Debug.Assert(!value.IsNull); _attributeUsageInfo = value; SetDataStored(); } } #endregion #region ComImportAttribute private bool _hasComImportAttribute; public bool HasComImportAttribute { get { VerifySealed(expected: true); return _hasComImportAttribute; } set { VerifySealed(expected: false); _hasComImportAttribute = value; SetDataStored(); } } #endregion #region ConditionalAttribute private ImmutableArray<string> _lazyConditionalSymbols = ImmutableArray<string>.Empty; public void AddConditionalSymbol(string name) { VerifySealed(expected: false); _lazyConditionalSymbols = _lazyConditionalSymbols.Add(name); SetDataStored(); } public ImmutableArray<string> ConditionalSymbols { get { VerifySealed(expected: true); return _lazyConditionalSymbols; } } #endregion #region ObsoleteAttribute private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; public ObsoleteAttributeData ObsoleteAttributeData { get { VerifySealed(expected: true); return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData; } set { VerifySealed(expected: false); Debug.Assert(value != null); Debug.Assert(!value.IsUninitialized); _obsoleteAttributeData = value; SetDataStored(); } } #endregion #region CodeAnalysisEmbeddedAttribute private bool _hasCodeAnalysisEmbeddedAttribute; public bool HasCodeAnalysisEmbeddedAttribute { get { VerifySealed(expected: true); return _hasCodeAnalysisEmbeddedAttribute; } set { VerifySealed(expected: false); _hasCodeAnalysisEmbeddedAttribute = value; SetDataStored(); } } #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.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from early well-known custom attributes applied on a type. /// </summary> internal abstract class CommonTypeEarlyWellKnownAttributeData : EarlyWellKnownAttributeData { #region AttributeUsageAttribute private AttributeUsageInfo _attributeUsageInfo = AttributeUsageInfo.Null; public AttributeUsageInfo AttributeUsageInfo { get { return _attributeUsageInfo; } set { VerifySealed(expected: false); Debug.Assert(_attributeUsageInfo.IsNull); Debug.Assert(!value.IsNull); _attributeUsageInfo = value; SetDataStored(); } } #endregion #region ComImportAttribute private bool _hasComImportAttribute; public bool HasComImportAttribute { get { VerifySealed(expected: true); return _hasComImportAttribute; } set { VerifySealed(expected: false); _hasComImportAttribute = value; SetDataStored(); } } #endregion #region ConditionalAttribute private ImmutableArray<string> _lazyConditionalSymbols = ImmutableArray<string>.Empty; public void AddConditionalSymbol(string name) { VerifySealed(expected: false); _lazyConditionalSymbols = _lazyConditionalSymbols.Add(name); SetDataStored(); } public ImmutableArray<string> ConditionalSymbols { get { VerifySealed(expected: true); return _lazyConditionalSymbols; } } #endregion #region ObsoleteAttribute private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized; public ObsoleteAttributeData ObsoleteAttributeData { get { VerifySealed(expected: true); return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData; } set { VerifySealed(expected: false); Debug.Assert(value != null); Debug.Assert(!value.IsUninitialized); _obsoleteAttributeData = value; SetDataStored(); } } #endregion #region CodeAnalysisEmbeddedAttribute private bool _hasCodeAnalysisEmbeddedAttribute; public bool HasCodeAnalysisEmbeddedAttribute { get { VerifySealed(expected: true); return _hasCodeAnalysisEmbeddedAttribute; } set { VerifySealed(expected: false); _hasCodeAnalysisEmbeddedAttribute = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/VisualBasic/Impl/xlf/BasicVSResources.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../BasicVSResources.resx"> <body> <trans-unit id="Add_missing_imports_on_paste"> <source>Add missing imports on paste</source> <target state="translated">在貼上時新增缺少的 import</target> <note>'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</source> <target state="translated">在關係運算子中: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</target> <note /> </trans-unit> <trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments"> <source>Insert ' at the start of new lines when writing ' comments</source> <target state="translated">撰寫 ' 註解時,於新行開頭插入 '</target> <note /> </trans-unit> <trans-unit id="Microsoft_Visual_Basic"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">插入程式碼片段</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members"> <source>Automatic _insertion of Interface and MustOverride members</source> <target state="translated">自動插入 Interface 及 MustOverride 成員(_I)</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">永不</target> <note /> </trans-unit> <trans-unit id="Prefer_IsNot_expression"> <source>Prefer 'IsNot' expression</source> <target state="translated">建議使用 'IsNot' 運算式</target> <note /> </trans-unit> <trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks"> <source>Prefer 'Is Nothing' for reference equality checks</source> <target state="translated">參考相等檢查最好使用 'Is Nothing'</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_object_creation"> <source>Prefer simplified object creation</source> <target state="translated">偏好簡易物件建立</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_Imports"> <source>Remove unnecessary Imports</source> <target state="translated">移除不必要的 Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Show_hints_for_New_expressions"> <source>Show hints for 'New' expressions</source> <target state="translated">顯示 'New' 運算式的提示</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">顯示來自未匯入命名空間的項目</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">顯示程序行分隔符號(_S)</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ByRef_on_custom_structure"> <source>_Don't put ByRef on custom structure</source> <target state="translated">請勿將 ByRef 置於自訂結構(_D)</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">編輯器說明</target> <note /> </trans-unit> <trans-unit id="A_utomatic_insertion_of_end_constructs"> <source>A_utomatic insertion of end constructs</source> <target state="translated">自動插入 End 建構(_U)</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">反白資料指標下的相關關鍵字(_K)</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">反白顯示資料指標下符號的參考項目(_H)</target> <note /> </trans-unit> <trans-unit id="Pretty_listing_reformatting_of_code"> <source>_Pretty listing (reformatting) of code</source> <target state="translated">程式碼美化排列 (重新格式化)(_P)</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>_Enter outlining mode when files open</source> <target state="translated">開啟檔案時進入大綱模式(_E)</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">擷取方法</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for '''</source> <target state="translated">產生 ''' 的 XML 文件註解(_G)</target> <note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">反白</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">最佳化方案大小</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">大</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">一般</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">在快速諮詢中顯示備註</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">小</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">效能</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">顯示預覽以追蹤重新命名(_T)</target> <note /> </trans-unit> <trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata"> <source>_Navigate to Object Browser for symbols defined in metadata</source> <target state="translated">巡覽至定義於中繼資料內符號的物件瀏覽器(_N)</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">移至定義</target> <note /> </trans-unit> <trans-unit id="Import_Directives"> <source>Import Directives</source> <target state="translated">Import 指示詞</target> <note /> </trans-unit> <trans-unit id="Sort_imports"> <source>Sort imports</source> <target state="translated">排序 Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_NuGet_packages"> <source>Suggest imports for types in _NuGet packages</source> <target state="translated">為 NuGet 套件中的類型建議 Import(_N)</target> <note /> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_reference_assemblies"> <source>Suggest imports for types in _reference assemblies</source> <target state="translated">為參考組件中的類型建議 Import(_R)</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_imports"> <source>_Place 'System' directives first when sorting imports</source> <target state="translated">排序 Import 時,先置入 'System' 指示詞(_P)</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_Me"> <source>Qualify event access with 'Me'</source> <target state="translated">以 'Me' 限定事件存取</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_Me"> <source>Qualify field access with 'Me'</source> <target state="translated">以 'Me' 限定欄位存取</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_Me"> <source>Qualify method access with 'Me'</source> <target state="translated">以 'Me' 限定方法存取</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_Me"> <source>Qualify property access with 'Me'</source> <target state="translated">以 'Me' 限定屬性存取</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_Me"> <source>Do not prefer 'Me.'</source> <target state="translated">不要選擇 'Me'。</target> <note /> </trans-unit> <trans-unit id="Prefer_Me"> <source>Prefer 'Me.'</source> <target state="translated">選擇 'Me.'</target> <note /> </trans-unit> <trans-unit id="Me_preferences_colon"> <source>'Me.' preferences:</source> <target state="translated">'Me.' 喜好設定:</target> <note /> </trans-unit> <trans-unit id="Predefined_type_preferences_colon"> <source>Predefined type preferences:</source> <target state="translated">預先定義的類型喜好設定:</target> <note /> </trans-unit> <trans-unit id="Highlight_matching_portions_of_completion_list_items"> <source>_Highlight matching portions of completion list items</source> <target state="translated">反白完成清單項目的相符部分(_H)</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">顯示完成項目篩選(_F)</target> <note /> </trans-unit> <trans-unit id="Completion_Lists"> <source>Completion Lists</source> <target state="translated">完成清單</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Enter 鍵行為:</target> <note /> </trans-unit> <trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word"> <source>_Only add new line on enter after end of fully typed word</source> <target state="translated">僅在完整輸入的字結尾處按 Enter 鍵時加入新行(_O)</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">一律在按下 Enter 鍵時加入新行(_A)</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">永不在按下 Enter 鍵時加入新行(_N)</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">一律包含程式碼片段</target> <note /> </trans-unit> <trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier"> <source>Include snippets when ?-Tab is typed after an identifier</source> <target state="translated">在識別碼後輸入 ?-Tab 時包含程式碼片段</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">一律不包含程式碼片段</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">程式碼片段行為</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_deleted"> <source>Show completion list after a character is _deleted</source> <target state="translated">刪除一個字元後顯示完成清單(_D)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_typed"> <source>_Show completion list after a character is typed</source> <target state="translated">輸入一個字元後顯示完成清單(_S)</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">未使用的區域函式</target> <note /> </trans-unit> <trans-unit id="VB_Coding_Conventions"> <source>VB Coding Conventions</source> <target state="translated">VB 編碼慣例</target> <note /> </trans-unit> <trans-unit id="nothing_checking_colon"> <source>'nothing' checking:</source> <target state="translated">'nothing' 檢查:</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_imports"> <source>Fade out unused imports</source> <target state="translated">淡出未使用的匯入</target> <note /> </trans-unit> <trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls"> <source>Report invalid placeholders in 'String.Format' calls</source> <target state="translated">報告 'String.Format' 呼叫中無效的預留位置</target> <note /> </trans-unit> <trans-unit id="Separate_import_directive_groups"> <source>Separate import directive groups</source> <target state="translated">分隔匯入指示詞群組</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</source> <target state="translated">在算術運算子中: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: And AndAlso Or OrElse</source> <target state="translated">其他二元運算子中: And AndAlso Or OrElse</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../BasicVSResources.resx"> <body> <trans-unit id="Add_missing_imports_on_paste"> <source>Add missing imports on paste</source> <target state="translated">在貼上時新增缺少的 import</target> <note>'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</source> <target state="translated">在關係運算子中: = &lt;&gt; &lt; &gt; &lt;= &gt;= Like Is</target> <note /> </trans-unit> <trans-unit id="Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments"> <source>Insert ' at the start of new lines when writing ' comments</source> <target state="translated">撰寫 ' 註解時,於新行開頭插入 '</target> <note /> </trans-unit> <trans-unit id="Microsoft_Visual_Basic"> <source>Microsoft Visual Basic</source> <target state="translated">Microsoft Visual Basic</target> <note /> </trans-unit> <trans-unit id="Insert_Snippet"> <source>Insert Snippet</source> <target state="translated">插入程式碼片段</target> <note /> </trans-unit> <trans-unit id="IntelliSense"> <source>IntelliSense</source> <target state="translated">IntelliSense</target> <note /> </trans-unit> <trans-unit id="Automatic_insertion_of_Interface_and_MustOverride_members"> <source>Automatic _insertion of Interface and MustOverride members</source> <target state="translated">自動插入 Interface 及 MustOverride 成員(_I)</target> <note /> </trans-unit> <trans-unit id="Never"> <source>Never</source> <target state="translated">永不</target> <note /> </trans-unit> <trans-unit id="Prefer_IsNot_expression"> <source>Prefer 'IsNot' expression</source> <target state="translated">建議使用 'IsNot' 運算式</target> <note /> </trans-unit> <trans-unit id="Prefer_Is_Nothing_for_reference_equality_checks"> <source>Prefer 'Is Nothing' for reference equality checks</source> <target state="translated">參考相等檢查最好使用 'Is Nothing'</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_object_creation"> <source>Prefer simplified object creation</source> <target state="translated">偏好簡易物件建立</target> <note /> </trans-unit> <trans-unit id="Remove_unnecessary_Imports"> <source>Remove unnecessary Imports</source> <target state="translated">移除不必要的 Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Show_hints_for_New_expressions"> <source>Show hints for 'New' expressions</source> <target state="translated">顯示 'New' 運算式的提示</target> <note /> </trans-unit> <trans-unit id="Show_items_from_unimported_namespaces"> <source>Show items from unimported namespaces</source> <target state="translated">顯示來自未匯入命名空間的項目</target> <note /> </trans-unit> <trans-unit id="Show_procedure_line_separators"> <source>_Show procedure line separators</source> <target state="translated">顯示程序行分隔符號(_S)</target> <note /> </trans-unit> <trans-unit id="Don_t_put_ByRef_on_custom_structure"> <source>_Don't put ByRef on custom structure</source> <target state="translated">請勿將 ByRef 置於自訂結構(_D)</target> <note /> </trans-unit> <trans-unit id="Editor_Help"> <source>Editor Help</source> <target state="translated">編輯器說明</target> <note /> </trans-unit> <trans-unit id="A_utomatic_insertion_of_end_constructs"> <source>A_utomatic insertion of end constructs</source> <target state="translated">自動插入 End 建構(_U)</target> <note /> </trans-unit> <trans-unit id="Highlight_related_keywords_under_cursor"> <source>Highlight related _keywords under cursor</source> <target state="translated">反白資料指標下的相關關鍵字(_K)</target> <note /> </trans-unit> <trans-unit id="Highlight_references_to_symbol_under_cursor"> <source>_Highlight references to symbol under cursor</source> <target state="translated">反白顯示資料指標下符號的參考項目(_H)</target> <note /> </trans-unit> <trans-unit id="Pretty_listing_reformatting_of_code"> <source>_Pretty listing (reformatting) of code</source> <target state="translated">程式碼美化排列 (重新格式化)(_P)</target> <note /> </trans-unit> <trans-unit id="Enter_outlining_mode_when_files_open"> <source>_Enter outlining mode when files open</source> <target state="translated">開啟檔案時進入大綱模式(_E)</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">擷取方法</target> <note /> </trans-unit> <trans-unit id="Generate_XML_documentation_comments_for"> <source>_Generate XML documentation comments for '''</source> <target state="translated">產生 ''' 的 XML 文件註解(_G)</target> <note>{Locked="'''"} "'''" is a VB keyword and should not be localized.</note> </trans-unit> <trans-unit id="Highlighting"> <source>Highlighting</source> <target state="translated">反白</target> <note /> </trans-unit> <trans-unit id="Optimize_for_solution_size"> <source>Optimize for solution size</source> <target state="translated">最佳化方案大小</target> <note /> </trans-unit> <trans-unit id="Large"> <source>Large</source> <target state="translated">大</target> <note /> </trans-unit> <trans-unit id="Regular"> <source>Regular</source> <target state="translated">一般</target> <note /> </trans-unit> <trans-unit id="Show_remarks_in_Quick_Info"> <source>Show remarks in Quick Info</source> <target state="translated">在快速諮詢中顯示備註</target> <note /> </trans-unit> <trans-unit id="Small"> <source>Small</source> <target state="translated">小</target> <note /> </trans-unit> <trans-unit id="Performance"> <source>Performance</source> <target state="translated">效能</target> <note /> </trans-unit> <trans-unit id="Show_preview_for_rename_tracking"> <source>Show preview for rename _tracking</source> <target state="translated">顯示預覽以追蹤重新命名(_T)</target> <note /> </trans-unit> <trans-unit id="Navigate_to_Object_Browser_for_symbols_defined_in_metadata"> <source>_Navigate to Object Browser for symbols defined in metadata</source> <target state="translated">巡覽至定義於中繼資料內符號的物件瀏覽器(_N)</target> <note /> </trans-unit> <trans-unit id="Go_to_Definition"> <source>Go to Definition</source> <target state="translated">移至定義</target> <note /> </trans-unit> <trans-unit id="Import_Directives"> <source>Import Directives</source> <target state="translated">Import 指示詞</target> <note /> </trans-unit> <trans-unit id="Sort_imports"> <source>Sort imports</source> <target state="translated">排序 Import</target> <note>{Locked="Import"} 'import' is a Visual Basic keyword and should not be localized</note> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_NuGet_packages"> <source>Suggest imports for types in _NuGet packages</source> <target state="translated">為 NuGet 套件中的類型建議 Import(_N)</target> <note /> </trans-unit> <trans-unit id="Suggest_imports_for_types_in_reference_assemblies"> <source>Suggest imports for types in _reference assemblies</source> <target state="translated">為參考組件中的類型建議 Import(_R)</target> <note /> </trans-unit> <trans-unit id="Place_System_directives_first_when_sorting_imports"> <source>_Place 'System' directives first when sorting imports</source> <target state="translated">排序 Import 時,先置入 'System' 指示詞(_P)</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_Me"> <source>Qualify event access with 'Me'</source> <target state="translated">以 'Me' 限定事件存取</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_Me"> <source>Qualify field access with 'Me'</source> <target state="translated">以 'Me' 限定欄位存取</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_Me"> <source>Qualify method access with 'Me'</source> <target state="translated">以 'Me' 限定方法存取</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_Me"> <source>Qualify property access with 'Me'</source> <target state="translated">以 'Me' 限定屬性存取</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_Me"> <source>Do not prefer 'Me.'</source> <target state="translated">不要選擇 'Me'。</target> <note /> </trans-unit> <trans-unit id="Prefer_Me"> <source>Prefer 'Me.'</source> <target state="translated">選擇 'Me.'</target> <note /> </trans-unit> <trans-unit id="Me_preferences_colon"> <source>'Me.' preferences:</source> <target state="translated">'Me.' 喜好設定:</target> <note /> </trans-unit> <trans-unit id="Predefined_type_preferences_colon"> <source>Predefined type preferences:</source> <target state="translated">預先定義的類型喜好設定:</target> <note /> </trans-unit> <trans-unit id="Highlight_matching_portions_of_completion_list_items"> <source>_Highlight matching portions of completion list items</source> <target state="translated">反白完成清單項目的相符部分(_H)</target> <note /> </trans-unit> <trans-unit id="Show_completion_item_filters"> <source>Show completion item _filters</source> <target state="translated">顯示完成項目篩選(_F)</target> <note /> </trans-unit> <trans-unit id="Completion_Lists"> <source>Completion Lists</source> <target state="translated">完成清單</target> <note /> </trans-unit> <trans-unit id="Enter_key_behavior_colon"> <source>Enter key behavior:</source> <target state="translated">Enter 鍵行為:</target> <note /> </trans-unit> <trans-unit id="Only_add_new_line_on_enter_after_end_of_fully_typed_word"> <source>_Only add new line on enter after end of fully typed word</source> <target state="translated">僅在完整輸入的字結尾處按 Enter 鍵時加入新行(_O)</target> <note /> </trans-unit> <trans-unit id="Always_add_new_line_on_enter"> <source>_Always add new line on enter</source> <target state="translated">一律在按下 Enter 鍵時加入新行(_A)</target> <note /> </trans-unit> <trans-unit id="Never_add_new_line_on_enter"> <source>_Never add new line on enter</source> <target state="translated">永不在按下 Enter 鍵時加入新行(_N)</target> <note /> </trans-unit> <trans-unit id="Always_include_snippets"> <source>Always include snippets</source> <target state="translated">一律包含程式碼片段</target> <note /> </trans-unit> <trans-unit id="Include_snippets_when_Tab_is_typed_after_an_identifier"> <source>Include snippets when ?-Tab is typed after an identifier</source> <target state="translated">在識別碼後輸入 ?-Tab 時包含程式碼片段</target> <note /> </trans-unit> <trans-unit id="Never_include_snippets"> <source>Never include snippets</source> <target state="translated">一律不包含程式碼片段</target> <note /> </trans-unit> <trans-unit id="Snippets_behavior"> <source>Snippets behavior</source> <target state="translated">程式碼片段行為</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_deleted"> <source>Show completion list after a character is _deleted</source> <target state="translated">刪除一個字元後顯示完成清單(_D)</target> <note /> </trans-unit> <trans-unit id="Show_completion_list_after_a_character_is_typed"> <source>_Show completion list after a character is typed</source> <target state="translated">輸入一個字元後顯示完成清單(_S)</target> <note /> </trans-unit> <trans-unit id="Unused_local"> <source>Unused local</source> <target state="translated">未使用的區域函式</target> <note /> </trans-unit> <trans-unit id="VB_Coding_Conventions"> <source>VB Coding Conventions</source> <target state="translated">VB 編碼慣例</target> <note /> </trans-unit> <trans-unit id="nothing_checking_colon"> <source>'nothing' checking:</source> <target state="translated">'nothing' 檢查:</target> <note /> </trans-unit> <trans-unit id="Fade_out_unused_imports"> <source>Fade out unused imports</source> <target state="translated">淡出未使用的匯入</target> <note /> </trans-unit> <trans-unit id="Report_invalid_placeholders_in_string_dot_format_calls"> <source>Report invalid placeholders in 'String.Format' calls</source> <target state="translated">報告 'String.Format' 呼叫中無效的預留位置</target> <note /> </trans-unit> <trans-unit id="Separate_import_directive_groups"> <source>Separate import directive groups</source> <target state="translated">分隔匯入指示詞群組</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</source> <target state="translated">在算術運算子中: ^ * / \ Mod + - &amp; &lt;&lt; &gt;&gt;</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators: And AndAlso Or OrElse</source> <target state="translated">其他二元運算子中: And AndAlso Or OrElse</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedLambdaSymbol.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.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a synthesized lambda. ''' </summary> Friend NotInheritable Class SynthesizedLambdaSymbol Inherits LambdaSymbol Private ReadOnly _kind As SynthesizedLambdaKind Public Sub New( kind As SynthesizedLambdaKind, syntaxNode As SyntaxNode, parameters As ImmutableArray(Of BoundLambdaParameterSymbol), returnType As TypeSymbol, binder As Binder) MyBase.New(syntaxNode, parameters, returnType, binder) Debug.Assert((returnType Is ReturnTypePendingDelegate) = kind.IsQueryLambda) _kind = kind End Sub Public Overrides ReadOnly Property SynthesizedKind As SynthesizedLambdaKind Get Return _kind End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether the symbol was generated by the compiler ''' rather than declared explicitly. ''' </summary> Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Return obj Is Me End Function Public Overrides Function GetHashCode() As Integer Return RuntimeHelpers.GetHashCode(Me) End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get ' Delegate relaxation stub contains no user code, only a synthesized call to the target method. ' ' Late-bound AddressOf lambda contains user code, but we don't allow debugging it. ' It shouldn't really contain the code but to be backward compatible we need to replicate Dev12 behavior. Return _kind <> SynthesizedLambdaKind.DelegateRelaxationStub AndAlso _kind <> SynthesizedLambdaKind.LateBoundAddressOfLambda End Get End Property Public Sub SetQueryLambdaReturnType(returnType As TypeSymbol) Debug.Assert(_kind.IsQueryLambda) Debug.Assert(m_ReturnType Is ReturnTypePendingDelegate) m_ReturnType = returnType 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.CompilerServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a synthesized lambda. ''' </summary> Friend NotInheritable Class SynthesizedLambdaSymbol Inherits LambdaSymbol Private ReadOnly _kind As SynthesizedLambdaKind Public Sub New( kind As SynthesizedLambdaKind, syntaxNode As SyntaxNode, parameters As ImmutableArray(Of BoundLambdaParameterSymbol), returnType As TypeSymbol, binder As Binder) MyBase.New(syntaxNode, parameters, returnType, binder) Debug.Assert((returnType Is ReturnTypePendingDelegate) = kind.IsQueryLambda) _kind = kind End Sub Public Overrides ReadOnly Property SynthesizedKind As SynthesizedLambdaKind Get Return _kind End Get End Property Public Overrides ReadOnly Property IsAsync As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsIterator As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether the symbol was generated by the compiler ''' rather than declared explicitly. ''' </summary> Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides Function Equals(obj As Object) As Boolean Return obj Is Me End Function Public Overrides Function GetHashCode() As Integer Return RuntimeHelpers.GetHashCode(Me) End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get ' Delegate relaxation stub contains no user code, only a synthesized call to the target method. ' ' Late-bound AddressOf lambda contains user code, but we don't allow debugging it. ' It shouldn't really contain the code but to be backward compatible we need to replicate Dev12 behavior. Return _kind <> SynthesizedLambdaKind.DelegateRelaxationStub AndAlso _kind <> SynthesizedLambdaKind.LateBoundAddressOfLambda End Get End Property Public Sub SetQueryLambdaReturnType(returnType As TypeSymbol) Debug.Assert(_kind.IsQueryLambda) Debug.Assert(m_ReturnType Is ReturnTypePendingDelegate) m_ReturnType = returnType End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core/Shared/Tagging/Tags/PreviewWarningTag.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.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal class PreviewWarningTag : TextMarkerTag { public const string TagId = "RoslynPreviewWarningTag"; public static readonly PreviewWarningTag Instance = new(); private PreviewWarningTag() : base(TagId) { } } }
// 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.VisualStudio.Text.Tagging; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal class PreviewWarningTag : TextMarkerTag { public const string TagId = "RoslynPreviewWarningTag"; public static readonly PreviewWarningTag Instance = new(); private PreviewWarningTag() : base(TagId) { } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/Emit/ExpressionTrees/Results/CheckedAndUncheckedNothingConversions.txt
-=-=-=-=-=-=-=-=- Nothing -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- Nothing -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- Nothing -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- Nothing -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- Nothing -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- Nothing -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Nothing -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- Nothing -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Nothing -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- Nothing -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Nothing -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- Nothing -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Nothing -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- Nothing -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Nothing -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- CType(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- Nothing -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- CType(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- Nothing -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- Nothing -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] )
-=-=-=-=-=-=-=-=- Nothing -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte) -> SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.SByte ) } return type: System.SByte type: System.Func`1[System.SByte] ) -=-=-=-=-=-=-=-=- Nothing -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, SByte?) -> SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.SByte] ) } return type: System.Nullable`1[System.SByte] type: System.Func`1[System.Nullable`1[System.SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte) -> E_SByte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_SByte ) } return type: E_SByte type: System.Func`1[E_SByte] ) -=-=-=-=-=-=-=-=- Nothing -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_SByte?) -> E_SByte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_SByte] ) } return type: System.Nullable`1[E_SByte] type: System.Func`1[System.Nullable`1[E_SByte]] ) -=-=-=-=-=-=-=-=- Nothing -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte) -> Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Byte ) } return type: System.Byte type: System.Func`1[System.Byte] ) -=-=-=-=-=-=-=-=- Nothing -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Byte?) -> Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Byte] ) } return type: System.Nullable`1[System.Byte] type: System.Func`1[System.Nullable`1[System.Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte) -> E_Byte -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Byte ) } return type: E_Byte type: System.Func`1[E_Byte] ) -=-=-=-=-=-=-=-=- Nothing -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Byte?) -> E_Byte? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Byte] ) } return type: System.Nullable`1[E_Byte] type: System.Func`1[System.Nullable`1[E_Byte]] ) -=-=-=-=-=-=-=-=- Nothing -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short) -> Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int16 ) } return type: System.Int16 type: System.Func`1[System.Int16] ) -=-=-=-=-=-=-=-=- Nothing -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Short?) -> Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int16] ) } return type: System.Nullable`1[System.Int16] type: System.Func`1[System.Nullable`1[System.Int16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short) -> E_Short -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Short ) } return type: E_Short type: System.Func`1[E_Short] ) -=-=-=-=-=-=-=-=- Nothing -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Short?) -> E_Short? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Short] ) } return type: System.Nullable`1[E_Short] type: System.Func`1[System.Nullable`1[E_Short]] ) -=-=-=-=-=-=-=-=- Nothing -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort) -> UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt16 ) } return type: System.UInt16 type: System.Func`1[System.UInt16] ) -=-=-=-=-=-=-=-=- Nothing -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UShort?) -> UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt16] ) } return type: System.Nullable`1[System.UInt16] type: System.Func`1[System.Nullable`1[System.UInt16]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort) -> E_UShort -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UShort ) } return type: E_UShort type: System.Func`1[E_UShort] ) -=-=-=-=-=-=-=-=- Nothing -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UShort?) -> E_UShort? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UShort] ) } return type: System.Nullable`1[E_UShort] type: System.Func`1[System.Nullable`1[E_UShort]] ) -=-=-=-=-=-=-=-=- Nothing -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer) -> Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int32 ) } return type: System.Int32 type: System.Func`1[System.Int32] ) -=-=-=-=-=-=-=-=- Nothing -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Integer?) -> Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int32] ) } return type: System.Nullable`1[System.Int32] type: System.Func`1[System.Nullable`1[System.Int32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer) -> E_Integer -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Integer ) } return type: E_Integer type: System.Func`1[E_Integer] ) -=-=-=-=-=-=-=-=- Nothing -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Integer?) -> E_Integer? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Integer] ) } return type: System.Nullable`1[E_Integer] type: System.Func`1[System.Nullable`1[E_Integer]] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger) -> UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.UInt32 ) } return type: System.UInt32 type: System.Func`1[System.UInt32] ) -=-=-=-=-=-=-=-=- Nothing -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- CType(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, UInteger?) -> UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.UInt32] ) } return type: System.Nullable`1[System.UInt32] type: System.Func`1[System.Nullable`1[System.UInt32]] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger) -> E_UInteger -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_UInteger ) } return type: E_UInteger type: System.Func`1[E_UInteger] ) -=-=-=-=-=-=-=-=- Nothing -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_UInteger?) -> E_UInteger? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_UInteger] ) } return type: System.Nullable`1[E_UInteger] type: System.Func`1[System.Nullable`1[E_UInteger]] ) -=-=-=-=-=-=-=-=- Nothing -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long) -> Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Int64 ) } return type: System.Int64 type: System.Func`1[System.Int64] ) -=-=-=-=-=-=-=-=- Nothing -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Long?) -> Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Int64] ) } return type: System.Nullable`1[System.Int64] type: System.Func`1[System.Nullable`1[System.Int64]] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long) -> E_Long -=-=-=-=-=-=-=-=- Lambda( body { Constant( Dummy type: E_Long ) } return type: E_Long type: System.Func`1[E_Long] ) -=-=-=-=-=-=-=-=- Nothing -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- CType(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, E_Long?) -> E_Long? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[E_Long] ) } return type: System.Nullable`1[E_Long] type: System.Func`1[System.Nullable`1[E_Long]] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean) -> Boolean -=-=-=-=-=-=-=-=- Lambda( body { Constant( False type: System.Boolean ) } return type: System.Boolean type: System.Func`1[System.Boolean] ) -=-=-=-=-=-=-=-=- Nothing -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Boolean?) -> Boolean? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Boolean] ) } return type: System.Nullable`1[System.Boolean] type: System.Func`1[System.Nullable`1[System.Boolean]] ) -=-=-=-=-=-=-=-=- Nothing -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single) -> Single -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Single ) } return type: System.Single type: System.Func`1[System.Single] ) -=-=-=-=-=-=-=-=- Nothing -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Single?) -> Single? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Single] ) } return type: System.Nullable`1[System.Single] type: System.Func`1[System.Nullable`1[System.Single]] ) -=-=-=-=-=-=-=-=- Nothing -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double) -> Double -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Double ) } return type: System.Double type: System.Func`1[System.Double] ) -=-=-=-=-=-=-=-=- Nothing -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Double?) -> Double? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Double] ) } return type: System.Nullable`1[System.Double] type: System.Func`1[System.Nullable`1[System.Double]] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal) -> Decimal -=-=-=-=-=-=-=-=- Lambda( body { Constant( 0 type: System.Decimal ) } return type: System.Decimal type: System.Func`1[System.Decimal] ) -=-=-=-=-=-=-=-=- Nothing -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Decimal?) -> Decimal? -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Nullable`1[System.Decimal] ) } return type: System.Nullable`1[System.Decimal] type: System.Func`1[System.Nullable`1[System.Decimal]] ) -=-=-=-=-=-=-=-=- Nothing -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- CType(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- Nothing -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- CType(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- Nothing -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct1) -> Struct1 -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct1 ) } return type: Struct1 type: System.Func`1[Struct1] ) -=-=-=-=-=-=-=-=- Nothing -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] ) -=-=-=-=-=-=-=-=- Nothing -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- CType(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- DirectCast(Nothing, Struct2(Of Struct1)) -> Struct2(Of Struct1) -=-=-=-=-=-=-=-=- Lambda( body { New( <.ctor>( ) type: Struct2`1[Struct1] ) } return type: Struct2`1[Struct1] type: System.Func`1[Struct2`1[Struct1]] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, String) -> String -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.String ) } return type: System.String type: System.Func`1[System.String] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Object) -> Object -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: System.Object ) } return type: System.Object type: System.Func`1[System.Object] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz1) -> Clazz1 -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz1 ) } return type: Clazz1 type: System.Func`1[Clazz1] ) -=-=-=-=-=-=-=-=- TryCast(Nothing, Clazz2(Of Clazz1, String)) -> Clazz2(Of Clazz1, String) -=-=-=-=-=-=-=-=- Lambda( body { Constant( null type: Clazz2`2[Clazz1,System.String] ) } return type: Clazz2`2[Clazz1,System.String] type: System.Func`1[Clazz2`2[Clazz1,System.String]] )
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core.Wpf/SignatureHelp/Presentation/Signature.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.ObjectModel; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal class Signature : ISignature { private const int MaxParamColumnCount = 100; private readonly SignatureHelpItem _signatureHelpItem; public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem signatureHelpItem, int selectedParameterIndex) { if (selectedParameterIndex < -1 || selectedParameterIndex >= signatureHelpItem.Parameters.Length) { throw new ArgumentOutOfRangeException(nameof(selectedParameterIndex)); } this.ApplicableToSpan = applicableToSpan; _signatureHelpItem = signatureHelpItem; _parameterIndex = selectedParameterIndex; } private bool _isInitialized; private void EnsureInitialized() { if (!_isInitialized) { _isInitialized = true; Initialize(); } } private Signature InitializedThis { get { EnsureInitialized(); return this; } } private IList<TaggedText> _displayParts; internal IList<TaggedText> DisplayParts => InitializedThis._displayParts; public ITrackingSpan ApplicableToSpan { get; } private string _content; public string Content => InitializedThis._content; private readonly int _parameterIndex = -1; public IParameter CurrentParameter { get { EnsureInitialized(); return _parameterIndex >= 0 && _parameters != null ? _parameters[_parameterIndex] : null; } } /// <remarks> /// The documentation is included in <see cref="Content"/> so that it will be classified. /// </remarks> public string Documentation => null; private ReadOnlyCollection<IParameter> _parameters; public ReadOnlyCollection<IParameter> Parameters => InitializedThis._parameters; private string _prettyPrintedContent; public string PrettyPrintedContent => InitializedThis._prettyPrintedContent; // This event is required by the ISignature interface but it's not actually used // (once created the CurrentParameter property cannot change) public event EventHandler<CurrentParameterChangedEventArgs> CurrentParameterChanged { add { } remove { } } private IList<TaggedText> _prettyPrintedDisplayParts; internal IList<TaggedText> PrettyPrintedDisplayParts => InitializedThis._prettyPrintedDisplayParts; private void Initialize() { var content = new StringBuilder(); var prettyPrintedContent = new StringBuilder(); var parts = new List<TaggedText>(); var prettyPrintedParts = new List<TaggedText>(); var parameters = new List<IParameter>(); var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts; var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText(); AddRange(signaturePrefixParts, parts, prettyPrintedParts); Append(signaturePrefixContent, content, prettyPrintedContent); var separatorParts = _signatureHelpItem.SeparatorDisplayParts; var separatorContent = separatorParts.GetFullText(); var newLinePart = new TaggedText(TextTags.LineBreak, "\r\n"); var newLineContent = newLinePart.ToString(); var spacerPart = new TaggedText(TextTags.Space, new string(' ', signaturePrefixContent.Length)); var spacerContent = spacerPart.ToString(); var paramColumnCount = 0; for (var i = 0; i < _signatureHelpItem.Parameters.Length; i++) { var sigHelpParameter = _signatureHelpItem.Parameters[i]; var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts; var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText(); var parameterParts = AddOptionalBrackets( sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts); var parameterContent = parameterParts.GetFullText(); var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts; var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText(); paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length; if (i > 0) { AddRange(separatorParts, parts, prettyPrintedParts); Append(separatorContent, content, prettyPrintedContent); if (paramColumnCount > MaxParamColumnCount) { prettyPrintedParts.Add(newLinePart); prettyPrintedParts.Add(spacerPart); prettyPrintedContent.Append(newLineContent); prettyPrintedContent.Append(spacerContent); paramColumnCount = 0; } } AddRange(parameterPrefixParts, parts, prettyPrintedParts); Append(parameterPrefixContext, content, prettyPrintedContent); parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length)); AddRange(parameterParts, parts, prettyPrintedParts); Append(parameterContent, content, prettyPrintedContent); AddRange(parameterSuffixParts, parts, prettyPrintedParts); Append(parameterSuffixContext, content, prettyPrintedContent); } AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts); Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent); if (_parameterIndex >= 0) { var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex]; AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts); Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent); } AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts); Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent); var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList(); if (documentation.Count > 0) { AddRange(new[] { newLinePart }, parts, prettyPrintedParts); Append(newLineContent, content, prettyPrintedContent); AddRange(documentation, parts, prettyPrintedParts); Append(documentation.GetFullText(), content, prettyPrintedContent); } _content = content.ToString(); _prettyPrintedContent = prettyPrintedContent.ToString(); _displayParts = parts.ToImmutableArrayOrEmpty(); _prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty(); _parameters = parameters.ToReadOnlyCollection(); } private static void AddRange(IList<TaggedText> values, List<TaggedText> parts, List<TaggedText> prettyPrintedParts) { parts.AddRange(values); prettyPrintedParts.AddRange(values); } private static void Append(string text, StringBuilder content, StringBuilder prettyPrintedContent) { content.Append(text); prettyPrintedContent.Append(text); } private static IList<TaggedText> AddOptionalBrackets(bool isOptional, IList<TaggedText> list) { if (isOptional) { var result = new List<TaggedText>(); result.Add(new TaggedText(TextTags.Punctuation, "[")); result.AddRange(list); result.Add(new TaggedText(TextTags.Punctuation, "]")); return result; } return list; } } }
// 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.ObjectModel; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation { internal class Signature : ISignature { private const int MaxParamColumnCount = 100; private readonly SignatureHelpItem _signatureHelpItem; public Signature(ITrackingSpan applicableToSpan, SignatureHelpItem signatureHelpItem, int selectedParameterIndex) { if (selectedParameterIndex < -1 || selectedParameterIndex >= signatureHelpItem.Parameters.Length) { throw new ArgumentOutOfRangeException(nameof(selectedParameterIndex)); } this.ApplicableToSpan = applicableToSpan; _signatureHelpItem = signatureHelpItem; _parameterIndex = selectedParameterIndex; } private bool _isInitialized; private void EnsureInitialized() { if (!_isInitialized) { _isInitialized = true; Initialize(); } } private Signature InitializedThis { get { EnsureInitialized(); return this; } } private IList<TaggedText> _displayParts; internal IList<TaggedText> DisplayParts => InitializedThis._displayParts; public ITrackingSpan ApplicableToSpan { get; } private string _content; public string Content => InitializedThis._content; private readonly int _parameterIndex = -1; public IParameter CurrentParameter { get { EnsureInitialized(); return _parameterIndex >= 0 && _parameters != null ? _parameters[_parameterIndex] : null; } } /// <remarks> /// The documentation is included in <see cref="Content"/> so that it will be classified. /// </remarks> public string Documentation => null; private ReadOnlyCollection<IParameter> _parameters; public ReadOnlyCollection<IParameter> Parameters => InitializedThis._parameters; private string _prettyPrintedContent; public string PrettyPrintedContent => InitializedThis._prettyPrintedContent; // This event is required by the ISignature interface but it's not actually used // (once created the CurrentParameter property cannot change) public event EventHandler<CurrentParameterChangedEventArgs> CurrentParameterChanged { add { } remove { } } private IList<TaggedText> _prettyPrintedDisplayParts; internal IList<TaggedText> PrettyPrintedDisplayParts => InitializedThis._prettyPrintedDisplayParts; private void Initialize() { var content = new StringBuilder(); var prettyPrintedContent = new StringBuilder(); var parts = new List<TaggedText>(); var prettyPrintedParts = new List<TaggedText>(); var parameters = new List<IParameter>(); var signaturePrefixParts = _signatureHelpItem.PrefixDisplayParts; var signaturePrefixContent = _signatureHelpItem.PrefixDisplayParts.GetFullText(); AddRange(signaturePrefixParts, parts, prettyPrintedParts); Append(signaturePrefixContent, content, prettyPrintedContent); var separatorParts = _signatureHelpItem.SeparatorDisplayParts; var separatorContent = separatorParts.GetFullText(); var newLinePart = new TaggedText(TextTags.LineBreak, "\r\n"); var newLineContent = newLinePart.ToString(); var spacerPart = new TaggedText(TextTags.Space, new string(' ', signaturePrefixContent.Length)); var spacerContent = spacerPart.ToString(); var paramColumnCount = 0; for (var i = 0; i < _signatureHelpItem.Parameters.Length; i++) { var sigHelpParameter = _signatureHelpItem.Parameters[i]; var parameterPrefixParts = sigHelpParameter.PrefixDisplayParts; var parameterPrefixContext = sigHelpParameter.PrefixDisplayParts.GetFullText(); var parameterParts = AddOptionalBrackets( sigHelpParameter.IsOptional, sigHelpParameter.DisplayParts); var parameterContent = parameterParts.GetFullText(); var parameterSuffixParts = sigHelpParameter.SuffixDisplayParts; var parameterSuffixContext = sigHelpParameter.SuffixDisplayParts.GetFullText(); paramColumnCount += separatorContent.Length + parameterPrefixContext.Length + parameterContent.Length + parameterSuffixContext.Length; if (i > 0) { AddRange(separatorParts, parts, prettyPrintedParts); Append(separatorContent, content, prettyPrintedContent); if (paramColumnCount > MaxParamColumnCount) { prettyPrintedParts.Add(newLinePart); prettyPrintedParts.Add(spacerPart); prettyPrintedContent.Append(newLineContent); prettyPrintedContent.Append(spacerContent); paramColumnCount = 0; } } AddRange(parameterPrefixParts, parts, prettyPrintedParts); Append(parameterPrefixContext, content, prettyPrintedContent); parameters.Add(new Parameter(this, sigHelpParameter, parameterContent, content.Length, prettyPrintedContent.Length)); AddRange(parameterParts, parts, prettyPrintedParts); Append(parameterContent, content, prettyPrintedContent); AddRange(parameterSuffixParts, parts, prettyPrintedParts); Append(parameterSuffixContext, content, prettyPrintedContent); } AddRange(_signatureHelpItem.SuffixDisplayParts, parts, prettyPrintedParts); Append(_signatureHelpItem.SuffixDisplayParts.GetFullText(), content, prettyPrintedContent); if (_parameterIndex >= 0) { var sigHelpParameter = _signatureHelpItem.Parameters[_parameterIndex]; AddRange(sigHelpParameter.SelectedDisplayParts, parts, prettyPrintedParts); Append(sigHelpParameter.SelectedDisplayParts.GetFullText(), content, prettyPrintedContent); } AddRange(_signatureHelpItem.DescriptionParts, parts, prettyPrintedParts); Append(_signatureHelpItem.DescriptionParts.GetFullText(), content, prettyPrintedContent); var documentation = _signatureHelpItem.DocumentationFactory(CancellationToken.None).ToList(); if (documentation.Count > 0) { AddRange(new[] { newLinePart }, parts, prettyPrintedParts); Append(newLineContent, content, prettyPrintedContent); AddRange(documentation, parts, prettyPrintedParts); Append(documentation.GetFullText(), content, prettyPrintedContent); } _content = content.ToString(); _prettyPrintedContent = prettyPrintedContent.ToString(); _displayParts = parts.ToImmutableArrayOrEmpty(); _prettyPrintedDisplayParts = prettyPrintedParts.ToImmutableArrayOrEmpty(); _parameters = parameters.ToReadOnlyCollection(); } private static void AddRange(IList<TaggedText> values, List<TaggedText> parts, List<TaggedText> prettyPrintedParts) { parts.AddRange(values); prettyPrintedParts.AddRange(values); } private static void Append(string text, StringBuilder content, StringBuilder prettyPrintedContent) { content.Append(text); prettyPrintedContent.Append(text); } private static IList<TaggedText> AddOptionalBrackets(bool isOptional, IList<TaggedText> list) { if (isOptional) { var result = new List<TaggedText>(); result.Add(new TaggedText(TextTags.Punctuation, "[")); result.AddRange(list); result.Add(new TaggedText(TextTags.Punctuation, "]")); return result; } return list; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/BoundTree/BoundTreeVisitors.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 System; using Roslyn.Utilities; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeVisitor<A, R> { protected BoundTreeVisitor() { } public virtual R Visit(BoundNode node, A arg) { if (node == null) { return default(R); } // this switch contains fewer than 50 of the most common node kinds switch (node.Kind) { case BoundKind.TypeExpression: return VisitTypeExpression(node as BoundTypeExpression, arg); case BoundKind.NamespaceExpression: return VisitNamespaceExpression(node as BoundNamespaceExpression, arg); case BoundKind.UnaryOperator: return VisitUnaryOperator(node as BoundUnaryOperator, arg); case BoundKind.IncrementOperator: return VisitIncrementOperator(node as BoundIncrementOperator, arg); case BoundKind.BinaryOperator: return VisitBinaryOperator(node as BoundBinaryOperator, arg); case BoundKind.CompoundAssignmentOperator: return VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg); case BoundKind.AssignmentOperator: return VisitAssignmentOperator(node as BoundAssignmentOperator, arg); case BoundKind.NullCoalescingOperator: return VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg); case BoundKind.ConditionalOperator: return VisitConditionalOperator(node as BoundConditionalOperator, arg); case BoundKind.ArrayAccess: return VisitArrayAccess(node as BoundArrayAccess, arg); case BoundKind.TypeOfOperator: return VisitTypeOfOperator(node as BoundTypeOfOperator, arg); case BoundKind.DefaultLiteral: return VisitDefaultLiteral(node as BoundDefaultLiteral, arg); case BoundKind.DefaultExpression: return VisitDefaultExpression(node as BoundDefaultExpression, arg); case BoundKind.IsOperator: return VisitIsOperator(node as BoundIsOperator, arg); case BoundKind.AsOperator: return VisitAsOperator(node as BoundAsOperator, arg); case BoundKind.Conversion: return VisitConversion(node as BoundConversion, arg); case BoundKind.SequencePointExpression: return VisitSequencePointExpression(node as BoundSequencePointExpression, arg); case BoundKind.SequencePoint: return VisitSequencePoint(node as BoundSequencePoint, arg); case BoundKind.SequencePointWithSpan: return VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg); case BoundKind.Block: return VisitBlock(node as BoundBlock, arg); case BoundKind.LocalDeclaration: return VisitLocalDeclaration(node as BoundLocalDeclaration, arg); case BoundKind.MultipleLocalDeclarations: return VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg); case BoundKind.Sequence: return VisitSequence(node as BoundSequence, arg); case BoundKind.NoOpStatement: return VisitNoOpStatement(node as BoundNoOpStatement, arg); case BoundKind.ReturnStatement: return VisitReturnStatement(node as BoundReturnStatement, arg); case BoundKind.ThrowStatement: return VisitThrowStatement(node as BoundThrowStatement, arg); case BoundKind.ExpressionStatement: return VisitExpressionStatement(node as BoundExpressionStatement, arg); case BoundKind.BreakStatement: return VisitBreakStatement(node as BoundBreakStatement, arg); case BoundKind.ContinueStatement: return VisitContinueStatement(node as BoundContinueStatement, arg); case BoundKind.IfStatement: return VisitIfStatement(node as BoundIfStatement, arg); case BoundKind.ForEachStatement: return VisitForEachStatement(node as BoundForEachStatement, arg); case BoundKind.TryStatement: return VisitTryStatement(node as BoundTryStatement, arg); case BoundKind.Literal: return VisitLiteral(node as BoundLiteral, arg); case BoundKind.ThisReference: return VisitThisReference(node as BoundThisReference, arg); case BoundKind.Local: return VisitLocal(node as BoundLocal, arg); case BoundKind.Parameter: return VisitParameter(node as BoundParameter, arg); case BoundKind.LabelStatement: return VisitLabelStatement(node as BoundLabelStatement, arg); case BoundKind.GotoStatement: return VisitGotoStatement(node as BoundGotoStatement, arg); case BoundKind.LabeledStatement: return VisitLabeledStatement(node as BoundLabeledStatement, arg); case BoundKind.StatementList: return VisitStatementList(node as BoundStatementList, arg); case BoundKind.ConditionalGoto: return VisitConditionalGoto(node as BoundConditionalGoto, arg); case BoundKind.Call: return VisitCall(node as BoundCall, arg); case BoundKind.ObjectCreationExpression: return VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg); case BoundKind.DelegateCreationExpression: return VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg); case BoundKind.FieldAccess: return VisitFieldAccess(node as BoundFieldAccess, arg); case BoundKind.PropertyAccess: return VisitPropertyAccess(node as BoundPropertyAccess, arg); case BoundKind.Lambda: return VisitLambda(node as BoundLambda, arg); case BoundKind.NameOfOperator: return VisitNameOfOperator(node as BoundNameOfOperator, arg); } return VisitInternal(node, arg); } public virtual R DefaultVisit(BoundNode node, A arg) { return default(R); } } internal abstract partial class BoundTreeVisitor { protected BoundTreeVisitor() { } [DebuggerHidden] public virtual BoundNode Visit(BoundNode node) { if (node != null) { return node.Accept(this); } return null; } [DebuggerHidden] public virtual BoundNode DefaultVisit(BoundNode node) { return null; } public class CancelledByStackGuardException : Exception { public readonly BoundNode Node; public CancelledByStackGuardException(Exception inner, BoundNode node) : base(inner.Message, inner) { Node = node; } public void AddAnError(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public void AddAnError(BindingDiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) { SyntaxNode syntax = node.Syntax; if (!(syntax is ExpressionSyntax)) { syntax = syntax.DescendantNodes(n => !(n is ExpressionSyntax)).OfType<ExpressionSyntax>().FirstOrDefault() ?? syntax; } return syntax.GetFirstToken().GetLocation(); } } /// <summary> /// Consumers must provide implementation for <see cref="VisitExpressionWithoutStackGuard"/>. /// </summary> [DebuggerStepThrough] protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) { BoundExpression result; recursionDepth++; #if DEBUG int saveRecursionDepth = recursionDepth; #endif if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) { EnsureSufficientExecutionStack(recursionDepth); result = VisitExpressionWithoutStackGuard(node); } else { result = VisitExpressionWithStackGuard(node); } #if DEBUG Debug.Assert(saveRecursionDepth == recursionDepth); #endif recursionDepth--; return result; } protected virtual void EnsureSufficientExecutionStack(int recursionDepth) { StackGuard.EnsureSufficientExecutionStack(recursionDepth); } protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } #nullable enable [DebuggerStepThrough] private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) { try { return VisitExpressionWithoutStackGuard(node); } catch (InsufficientExecutionStackException ex) { throw new CancelledByStackGuardException(ex, node); } } /// <summary> /// We should be intentional about behavior of derived classes regarding guarding against stack overflow. /// </summary> protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); #nullable disable } }
// 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 System; using Roslyn.Utilities; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class BoundTreeVisitor<A, R> { protected BoundTreeVisitor() { } public virtual R Visit(BoundNode node, A arg) { if (node == null) { return default(R); } // this switch contains fewer than 50 of the most common node kinds switch (node.Kind) { case BoundKind.TypeExpression: return VisitTypeExpression(node as BoundTypeExpression, arg); case BoundKind.NamespaceExpression: return VisitNamespaceExpression(node as BoundNamespaceExpression, arg); case BoundKind.UnaryOperator: return VisitUnaryOperator(node as BoundUnaryOperator, arg); case BoundKind.IncrementOperator: return VisitIncrementOperator(node as BoundIncrementOperator, arg); case BoundKind.BinaryOperator: return VisitBinaryOperator(node as BoundBinaryOperator, arg); case BoundKind.CompoundAssignmentOperator: return VisitCompoundAssignmentOperator(node as BoundCompoundAssignmentOperator, arg); case BoundKind.AssignmentOperator: return VisitAssignmentOperator(node as BoundAssignmentOperator, arg); case BoundKind.NullCoalescingOperator: return VisitNullCoalescingOperator(node as BoundNullCoalescingOperator, arg); case BoundKind.ConditionalOperator: return VisitConditionalOperator(node as BoundConditionalOperator, arg); case BoundKind.ArrayAccess: return VisitArrayAccess(node as BoundArrayAccess, arg); case BoundKind.TypeOfOperator: return VisitTypeOfOperator(node as BoundTypeOfOperator, arg); case BoundKind.DefaultLiteral: return VisitDefaultLiteral(node as BoundDefaultLiteral, arg); case BoundKind.DefaultExpression: return VisitDefaultExpression(node as BoundDefaultExpression, arg); case BoundKind.IsOperator: return VisitIsOperator(node as BoundIsOperator, arg); case BoundKind.AsOperator: return VisitAsOperator(node as BoundAsOperator, arg); case BoundKind.Conversion: return VisitConversion(node as BoundConversion, arg); case BoundKind.SequencePointExpression: return VisitSequencePointExpression(node as BoundSequencePointExpression, arg); case BoundKind.SequencePoint: return VisitSequencePoint(node as BoundSequencePoint, arg); case BoundKind.SequencePointWithSpan: return VisitSequencePointWithSpan(node as BoundSequencePointWithSpan, arg); case BoundKind.Block: return VisitBlock(node as BoundBlock, arg); case BoundKind.LocalDeclaration: return VisitLocalDeclaration(node as BoundLocalDeclaration, arg); case BoundKind.MultipleLocalDeclarations: return VisitMultipleLocalDeclarations(node as BoundMultipleLocalDeclarations, arg); case BoundKind.Sequence: return VisitSequence(node as BoundSequence, arg); case BoundKind.NoOpStatement: return VisitNoOpStatement(node as BoundNoOpStatement, arg); case BoundKind.ReturnStatement: return VisitReturnStatement(node as BoundReturnStatement, arg); case BoundKind.ThrowStatement: return VisitThrowStatement(node as BoundThrowStatement, arg); case BoundKind.ExpressionStatement: return VisitExpressionStatement(node as BoundExpressionStatement, arg); case BoundKind.BreakStatement: return VisitBreakStatement(node as BoundBreakStatement, arg); case BoundKind.ContinueStatement: return VisitContinueStatement(node as BoundContinueStatement, arg); case BoundKind.IfStatement: return VisitIfStatement(node as BoundIfStatement, arg); case BoundKind.ForEachStatement: return VisitForEachStatement(node as BoundForEachStatement, arg); case BoundKind.TryStatement: return VisitTryStatement(node as BoundTryStatement, arg); case BoundKind.Literal: return VisitLiteral(node as BoundLiteral, arg); case BoundKind.ThisReference: return VisitThisReference(node as BoundThisReference, arg); case BoundKind.Local: return VisitLocal(node as BoundLocal, arg); case BoundKind.Parameter: return VisitParameter(node as BoundParameter, arg); case BoundKind.LabelStatement: return VisitLabelStatement(node as BoundLabelStatement, arg); case BoundKind.GotoStatement: return VisitGotoStatement(node as BoundGotoStatement, arg); case BoundKind.LabeledStatement: return VisitLabeledStatement(node as BoundLabeledStatement, arg); case BoundKind.StatementList: return VisitStatementList(node as BoundStatementList, arg); case BoundKind.ConditionalGoto: return VisitConditionalGoto(node as BoundConditionalGoto, arg); case BoundKind.Call: return VisitCall(node as BoundCall, arg); case BoundKind.ObjectCreationExpression: return VisitObjectCreationExpression(node as BoundObjectCreationExpression, arg); case BoundKind.DelegateCreationExpression: return VisitDelegateCreationExpression(node as BoundDelegateCreationExpression, arg); case BoundKind.FieldAccess: return VisitFieldAccess(node as BoundFieldAccess, arg); case BoundKind.PropertyAccess: return VisitPropertyAccess(node as BoundPropertyAccess, arg); case BoundKind.Lambda: return VisitLambda(node as BoundLambda, arg); case BoundKind.NameOfOperator: return VisitNameOfOperator(node as BoundNameOfOperator, arg); } return VisitInternal(node, arg); } public virtual R DefaultVisit(BoundNode node, A arg) { return default(R); } } internal abstract partial class BoundTreeVisitor { protected BoundTreeVisitor() { } [DebuggerHidden] public virtual BoundNode Visit(BoundNode node) { if (node != null) { return node.Accept(this); } return null; } [DebuggerHidden] public virtual BoundNode DefaultVisit(BoundNode node) { return null; } public class CancelledByStackGuardException : Exception { public readonly BoundNode Node; public CancelledByStackGuardException(Exception inner, BoundNode node) : base(inner.Message, inner) { Node = node; } public void AddAnError(DiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public void AddAnError(BindingDiagnosticBag diagnostics) { diagnostics.Add(ErrorCode.ERR_InsufficientStack, GetTooLongOrComplexExpressionErrorLocation(Node)); } public static Location GetTooLongOrComplexExpressionErrorLocation(BoundNode node) { SyntaxNode syntax = node.Syntax; if (!(syntax is ExpressionSyntax)) { syntax = syntax.DescendantNodes(n => !(n is ExpressionSyntax)).OfType<ExpressionSyntax>().FirstOrDefault() ?? syntax; } return syntax.GetFirstToken().GetLocation(); } } /// <summary> /// Consumers must provide implementation for <see cref="VisitExpressionWithoutStackGuard"/>. /// </summary> [DebuggerStepThrough] protected BoundExpression VisitExpressionWithStackGuard(ref int recursionDepth, BoundExpression node) { BoundExpression result; recursionDepth++; #if DEBUG int saveRecursionDepth = recursionDepth; #endif if (recursionDepth > 1 || !ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException()) { EnsureSufficientExecutionStack(recursionDepth); result = VisitExpressionWithoutStackGuard(node); } else { result = VisitExpressionWithStackGuard(node); } #if DEBUG Debug.Assert(saveRecursionDepth == recursionDepth); #endif recursionDepth--; return result; } protected virtual void EnsureSufficientExecutionStack(int recursionDepth) { StackGuard.EnsureSufficientExecutionStack(recursionDepth); } protected virtual bool ConvertInsufficientExecutionStackExceptionToCancelledByStackGuardException() { return true; } #nullable enable [DebuggerStepThrough] private BoundExpression? VisitExpressionWithStackGuard(BoundExpression node) { try { return VisitExpressionWithoutStackGuard(node); } catch (InsufficientExecutionStackException ex) { throw new CancelledByStackGuardException(ex, node); } } /// <summary> /// We should be intentional about behavior of derived classes regarding guarding against stack overflow. /// </summary> protected abstract BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node); #nullable disable } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Binder/Binder.WithQueryLambdaParametersBinder.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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { // A binder that finds query variables (BoundRangeVariableSymbol) and can bind them // to the appropriate rewriting involving lambda parameters when transparent identifiers are involved. private sealed class WithQueryLambdaParametersBinder : WithLambdaParametersBinder { private readonly RangeVariableMap _rangeVariableMap; private readonly MultiDictionary<string, RangeVariableSymbol> _parameterMap; public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next) : base(lambdaSymbol, next) { _rangeVariableMap = rangeVariableMap; _parameterMap = new MultiDictionary<string, RangeVariableSymbol>(); foreach (var qv in rangeVariableMap.Keys) { _parameterMap.Add(qv.Name, qv); } } protected override BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { Debug.Assert(!qv.IsTransparent); BoundExpression translation; ImmutableArray<string> path; if (_rangeVariableMap.TryGetValue(qv, out path)) { if (path.IsEmpty) { // the range variable maps directly to a use of the parameter of that name var value = base.parameterMap[qv.Name]; Debug.Assert(value.Count == 1); translation = new BoundParameter(node, value.Single()); } else { // if the query variable map for this variable is non empty, we always start with the current // lambda's first parameter, which is a transparent identifier. Debug.Assert(base.lambdaSymbol.Parameters[0].Name.StartsWith(transparentIdentifierPrefix, StringComparison.Ordinal)); translation = new BoundParameter(node, base.lambdaSymbol.Parameters[0]); for (int i = path.Length - 1; i >= 0; i--) { translation.WasCompilerGenerated = true; var nextField = path[i]; translation = SelectField(node, translation, nextField, diagnostics); } } return new BoundRangeVariable(node, qv, translation, translation.Type); } return base.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, BindingDiagnosticBag diagnostics) { var receiverType = receiver.Type as NamedTypeSymbol; if ((object)receiverType == null || !receiverType.IsAnonymousType) { // We only construct transparent query variables using anonymous types, so if we're trying to navigate through // some other type, we must have some query API where the types don't match up as expected. var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType); if (receiver.Type?.IsErrorType() != true) { Error(diagnostics, info, node); } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray.Create<Symbol>(receiver.ExpressionSymbol), ImmutableArray.Create(BindToTypeForErrorRecovery(receiver)), new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info)); } LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.MustBeInstance; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(node, useSiteInfo); var result = BindMemberOfType(node, node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeWithAnnotations>), lookupResult, BoundMethodGroupFlags.None, diagnostics); lookupResult.Free(); return result; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } foreach (var rangeVariable in _parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(rangeVariable, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var kvp in _parameterMap) { result.AddSymbol(null, kvp.Key, 0); } } } } } }
// 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.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { // A binder that finds query variables (BoundRangeVariableSymbol) and can bind them // to the appropriate rewriting involving lambda parameters when transparent identifiers are involved. private sealed class WithQueryLambdaParametersBinder : WithLambdaParametersBinder { private readonly RangeVariableMap _rangeVariableMap; private readonly MultiDictionary<string, RangeVariableSymbol> _parameterMap; public WithQueryLambdaParametersBinder(LambdaSymbol lambdaSymbol, RangeVariableMap rangeVariableMap, Binder next) : base(lambdaSymbol, next) { _rangeVariableMap = rangeVariableMap; _parameterMap = new MultiDictionary<string, RangeVariableSymbol>(); foreach (var qv in rangeVariableMap.Keys) { _parameterMap.Add(qv.Name, qv); } } protected override BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { Debug.Assert(!qv.IsTransparent); BoundExpression translation; ImmutableArray<string> path; if (_rangeVariableMap.TryGetValue(qv, out path)) { if (path.IsEmpty) { // the range variable maps directly to a use of the parameter of that name var value = base.parameterMap[qv.Name]; Debug.Assert(value.Count == 1); translation = new BoundParameter(node, value.Single()); } else { // if the query variable map for this variable is non empty, we always start with the current // lambda's first parameter, which is a transparent identifier. Debug.Assert(base.lambdaSymbol.Parameters[0].Name.StartsWith(transparentIdentifierPrefix, StringComparison.Ordinal)); translation = new BoundParameter(node, base.lambdaSymbol.Parameters[0]); for (int i = path.Length - 1; i >= 0; i--) { translation.WasCompilerGenerated = true; var nextField = path[i]; translation = SelectField(node, translation, nextField, diagnostics); } } return new BoundRangeVariable(node, qv, translation, translation.Type); } return base.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SelectField(SimpleNameSyntax node, BoundExpression receiver, string name, BindingDiagnosticBag diagnostics) { var receiverType = receiver.Type as NamedTypeSymbol; if ((object)receiverType == null || !receiverType.IsAnonymousType) { // We only construct transparent query variables using anonymous types, so if we're trying to navigate through // some other type, we must have some query API where the types don't match up as expected. var info = new CSDiagnosticInfo(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, name, receiver.ExpressionSymbol ?? receiverType); if (receiver.Type?.IsErrorType() != true) { Error(diagnostics, info, node); } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray.Create<Symbol>(receiver.ExpressionSymbol), ImmutableArray.Create(BindToTypeForErrorRecovery(receiver)), new ExtendedErrorTypeSymbol(this.Compilation, "", 0, info)); } LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.MustBeInstance; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); LookupMembersWithFallback(lookupResult, receiver.Type, name, 0, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(node, useSiteInfo); var result = BindMemberOfType(node, node, name, 0, indexed: false, receiver, default(SeparatedSyntaxList<TypeSyntax>), default(ImmutableArray<TypeWithAnnotations>), lookupResult, BoundMethodGroupFlags.None, diagnostics); lookupResult.Free(); return result; } internal override void LookupSymbolsInSingleBinder( LookupResult result, string name, int arity, ConsList<TypeSymbol> basesBeingResolved, LookupOptions options, Binder originalBinder, bool diagnose, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(result.IsClear); if ((options & LookupOptions.NamespaceAliasesOnly) != 0) { return; } foreach (var rangeVariable in _parameterMap[name]) { result.MergeEqual(originalBinder.CheckViability(rangeVariable, arity, options, null, diagnose, ref useSiteInfo)); } } protected override void AddLookupSymbolsInfoInSingleBinder(LookupSymbolsInfo result, LookupOptions options, Binder originalBinder) { if (options.CanConsiderMembers()) { foreach (var kvp in _parameterMap) { result.AddSymbol(null, kvp.Key, 0); } } } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/DocumentHighlighting/AbstractDocumentHighlightsService.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.DocumentHighlighting { internal abstract partial class AbstractDocumentHighlightsService : IDocumentHighlightsService { public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var solution = document.Project.Solution; var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { // Call the project overload. We don't need the full solution synchronized over to the OOP // in order to highlight values in this document. var result = await client.TryInvokeAsync<IRemoteDocumentHighlightsService, ImmutableArray<SerializableDocumentHighlights>>( document.Project, (service, solutionInfo, cancellationToken) => service.GetDocumentHighlightsAsync(solutionInfo, document.Id, position, documentsToSearch.SelectAsArray(d => d.Id), cancellationToken), cancellationToken).ConfigureAwait(false); if (!result.HasValue) { return ImmutableArray<DocumentHighlights>.Empty; } return await result.Value.SelectAsArrayAsync(h => h.RehydrateAsync(solution)).ConfigureAwait(false); } return await GetDocumentHighlightsInCurrentProcessAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsInCurrentProcessAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var result = await TryGetEmbeddedLanguageHighlightsAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (!result.IsDefaultOrEmpty) return result; var solution = document.Project.Solution; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) return ImmutableArray<DocumentHighlights>.Empty; // Get unique tags for referenced symbols var tags = await GetTagsForReferencedSymbolAsync( symbol, document, documentsToSearch, cancellationToken).ConfigureAwait(false); // Only accept these highlights if at least one of them actually intersected with the // position the caller was asking for. For example, if the user had `$$new X();` then // SymbolFinder will consider that the symbol `X`. However, the doc highlights won't include // the `new` part, so it's not appropriate for us to highlight `X` in that case. if (!tags.Any(t => t.HighlightSpans.Any(hs => hs.TextSpan.IntersectsWith(position)))) return ImmutableArray<DocumentHighlights>.Empty; return tags; } private static async Task<ImmutableArray<DocumentHighlights>> TryGetEmbeddedLanguageHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var languagesProvider = document.GetLanguageService<IEmbeddedLanguagesProvider>(); if (languagesProvider != null) { foreach (var language in languagesProvider.Languages) { var highlighter = (language as IEmbeddedLanguageFeatures)?.DocumentHighlightsService; if (highlighter != null) { var highlights = await highlighter.GetDocumentHighlightsAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (!highlights.IsDefaultOrEmpty) { return highlights; } } } } return default; } private async Task<ImmutableArray<DocumentHighlights>> GetTagsForReferencedSymbolAsync( ISymbol symbol, Document document, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { Contract.ThrowIfNull(symbol); if (ShouldConsiderSymbol(symbol)) { var progress = new StreamingProgressCollector(); var options = FindSymbols.FindReferencesSearchOptions.GetFeatureOptionsForStartingSymbol(symbol); await SymbolFinder.FindReferencesAsync( symbol, document.Project.Solution, progress, documentsToSearch, options, cancellationToken).ConfigureAwait(false); return await FilterAndCreateSpansAsync( progress.GetReferencedSymbols(), document, documentsToSearch, symbol, options, cancellationToken).ConfigureAwait(false); } return ImmutableArray<DocumentHighlights>.Empty; } private static bool ShouldConsiderSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: switch (((IMethodSymbol)symbol).MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: return false; default: return true; } default: return true; } } private async Task<ImmutableArray<DocumentHighlights>> FilterAndCreateSpansAsync( ImmutableArray<ReferencedSymbol> references, Document startingDocument, IImmutableSet<Document> documentsToSearch, ISymbol symbol, FindSymbols.FindReferencesSearchOptions options, CancellationToken cancellationToken) { var solution = startingDocument.Project.Solution; references = references.FilterToItemsToShow(options); references = references.FilterNonMatchingMethodNames(solution, symbol); references = references.FilterToAliasMatches(symbol as IAliasSymbol); if (symbol.IsConstructor()) { references = references.WhereAsArray(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition)); } using var _ = ArrayBuilder<Location>.GetInstance(out var additionalReferences); foreach (var currentDocument in documentsToSearch) { // 'documentsToSearch' may contain documents from languages other than our own // (for example cshtml files when we're searching the cs document). Since we're // delegating to a virtual method for this language type, we have to make sure // we only process the document if it's also our language. if (currentDocument.Project.Language == startingDocument.Project.Language) { additionalReferences.AddRange(await GetAdditionalReferencesAsync(currentDocument, symbol, cancellationToken).ConfigureAwait(false)); } } return await CreateSpansAsync( solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false); } protected virtual Task<ImmutableArray<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { return SpecializedTasks.EmptyImmutableArray<Location>(); } private static async Task<ImmutableArray<DocumentHighlights>> CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable<ReferencedSymbol> references, ArrayBuilder<Location> additionalReferences, IImmutableSet<Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet<DocumentSpan>(); var tagMap = new MultiDictionary<Document, HighlightSpan>(); var addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpanAsync(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind is WorkspaceKind.Interactive or WorkspaceKind.MiscellaneousFiles); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpanAsync(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpanAsync(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpanAsync(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } using var listDisposer = ArrayBuilder<DocumentHighlights>.GetInstance(tagMap.Count, out var list); foreach (var kvp in tagMap) { using var spansDisposer = ArrayBuilder<HighlightSpan>.GetInstance(kvp.Value.Count, out var spans); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutable())); } return list.ToImmutable(); } private static bool ShouldIncludeDefinition(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return false; case SymbolKind.NamedType: return !((INamedTypeSymbol)symbol).IsScriptClass; } return true; } private static async Task AddLocationSpanAsync(Location location, Solution solution, HashSet<DocumentSpan> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Document, new HighlightSpan(span.Value.SourceSpan, kind)); } } private static async Task<DocumentSpan?> GetLocationSpanAsync( Solution solution, Location location, CancellationToken cancellationToken) { try { if (location != null && location.IsInSource) { var tree = location.SourceTree; var document = solution.GetRequiredDocument(tree); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts != null) { // Specify findInsideTrivia: true to ensure that we search within XML doc comments. var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true); return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent) ? new DocumentSpan(document, token.Span) : new DocumentSpan(document, location.SourceSpan); } } } catch (NullReferenceException e) when (FatalError.ReportAndCatch(e)) { // We currently are seeing a strange null references crash in this code. We have // a strong belief that this is recoverable, but we'd like to know why it is // happening. This exception filter allows us to report the issue and continue // without damaging the user experience. Once we get more crash reports, we // can figure out the root cause and address appropriately. This is preferable // to just using conditionl access operators to be resilient (as we won't actually // know why this is happening). } 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. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Features.EmbeddedLanguages; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.DocumentHighlighting { internal abstract partial class AbstractDocumentHighlightsService : IDocumentHighlightsService { public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var solution = document.Project.Solution; var client = await RemoteHostClient.TryGetClientAsync(document.Project, cancellationToken).ConfigureAwait(false); if (client != null) { // Call the project overload. We don't need the full solution synchronized over to the OOP // in order to highlight values in this document. var result = await client.TryInvokeAsync<IRemoteDocumentHighlightsService, ImmutableArray<SerializableDocumentHighlights>>( document.Project, (service, solutionInfo, cancellationToken) => service.GetDocumentHighlightsAsync(solutionInfo, document.Id, position, documentsToSearch.SelectAsArray(d => d.Id), cancellationToken), cancellationToken).ConfigureAwait(false); if (!result.HasValue) { return ImmutableArray<DocumentHighlights>.Empty; } return await result.Value.SelectAsArrayAsync(h => h.RehydrateAsync(solution)).ConfigureAwait(false); } return await GetDocumentHighlightsInCurrentProcessAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); } private async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsInCurrentProcessAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var result = await TryGetEmbeddedLanguageHighlightsAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (!result.IsDefaultOrEmpty) return result; var solution = document.Project.Solution; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = await SymbolFinder.FindSymbolAtPositionAsync( semanticModel, position, solution.Workspace, cancellationToken).ConfigureAwait(false); if (symbol == null) return ImmutableArray<DocumentHighlights>.Empty; // Get unique tags for referenced symbols var tags = await GetTagsForReferencedSymbolAsync( symbol, document, documentsToSearch, cancellationToken).ConfigureAwait(false); // Only accept these highlights if at least one of them actually intersected with the // position the caller was asking for. For example, if the user had `$$new X();` then // SymbolFinder will consider that the symbol `X`. However, the doc highlights won't include // the `new` part, so it's not appropriate for us to highlight `X` in that case. if (!tags.Any(t => t.HighlightSpans.Any(hs => hs.TextSpan.IntersectsWith(position)))) return ImmutableArray<DocumentHighlights>.Empty; return tags; } private static async Task<ImmutableArray<DocumentHighlights>> TryGetEmbeddedLanguageHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var languagesProvider = document.GetLanguageService<IEmbeddedLanguagesProvider>(); if (languagesProvider != null) { foreach (var language in languagesProvider.Languages) { var highlighter = (language as IEmbeddedLanguageFeatures)?.DocumentHighlightsService; if (highlighter != null) { var highlights = await highlighter.GetDocumentHighlightsAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (!highlights.IsDefaultOrEmpty) { return highlights; } } } } return default; } private async Task<ImmutableArray<DocumentHighlights>> GetTagsForReferencedSymbolAsync( ISymbol symbol, Document document, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { Contract.ThrowIfNull(symbol); if (ShouldConsiderSymbol(symbol)) { var progress = new StreamingProgressCollector(); var options = FindSymbols.FindReferencesSearchOptions.GetFeatureOptionsForStartingSymbol(symbol); await SymbolFinder.FindReferencesAsync( symbol, document.Project.Solution, progress, documentsToSearch, options, cancellationToken).ConfigureAwait(false); return await FilterAndCreateSpansAsync( progress.GetReferencedSymbols(), document, documentsToSearch, symbol, options, cancellationToken).ConfigureAwait(false); } return ImmutableArray<DocumentHighlights>.Empty; } private static bool ShouldConsiderSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Method: switch (((IMethodSymbol)symbol).MethodKind) { case MethodKind.AnonymousFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: return false; default: return true; } default: return true; } } private async Task<ImmutableArray<DocumentHighlights>> FilterAndCreateSpansAsync( ImmutableArray<ReferencedSymbol> references, Document startingDocument, IImmutableSet<Document> documentsToSearch, ISymbol symbol, FindSymbols.FindReferencesSearchOptions options, CancellationToken cancellationToken) { var solution = startingDocument.Project.Solution; references = references.FilterToItemsToShow(options); references = references.FilterNonMatchingMethodNames(solution, symbol); references = references.FilterToAliasMatches(symbol as IAliasSymbol); if (symbol.IsConstructor()) { references = references.WhereAsArray(r => r.Definition.OriginalDefinition.Equals(symbol.OriginalDefinition)); } using var _ = ArrayBuilder<Location>.GetInstance(out var additionalReferences); foreach (var currentDocument in documentsToSearch) { // 'documentsToSearch' may contain documents from languages other than our own // (for example cshtml files when we're searching the cs document). Since we're // delegating to a virtual method for this language type, we have to make sure // we only process the document if it's also our language. if (currentDocument.Project.Language == startingDocument.Project.Language) { additionalReferences.AddRange(await GetAdditionalReferencesAsync(currentDocument, symbol, cancellationToken).ConfigureAwait(false)); } } return await CreateSpansAsync( solution, symbol, references, additionalReferences, documentsToSearch, cancellationToken).ConfigureAwait(false); } protected virtual Task<ImmutableArray<Location>> GetAdditionalReferencesAsync( Document document, ISymbol symbol, CancellationToken cancellationToken) { return SpecializedTasks.EmptyImmutableArray<Location>(); } private static async Task<ImmutableArray<DocumentHighlights>> CreateSpansAsync( Solution solution, ISymbol symbol, IEnumerable<ReferencedSymbol> references, ArrayBuilder<Location> additionalReferences, IImmutableSet<Document> documentToSearch, CancellationToken cancellationToken) { var spanSet = new HashSet<DocumentSpan>(); var tagMap = new MultiDictionary<Document, HighlightSpan>(); var addAllDefinitions = true; // Add definitions // Filter out definitions that cannot be highlighted. e.g: alias symbols defined via project property pages. if (symbol.Kind == SymbolKind.Alias && symbol.Locations.Length > 0) { addAllDefinitions = false; if (symbol.Locations.First().IsInSource) { // For alias symbol we want to get the tag only for the alias definition, not the target symbol's definition. await AddLocationSpanAsync(symbol.Locations.First(), solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } // Add references and definitions foreach (var reference in references) { if (addAllDefinitions && ShouldIncludeDefinition(reference.Definition)) { foreach (var location in reference.Definition.Locations) { if (location.IsInSource) { var document = solution.GetDocument(location.SourceTree); // GetDocument will return null for locations in #load'ed trees. // TODO: Remove this check and add logic to fetch the #load'ed tree's // Document once https://github.com/dotnet/roslyn/issues/5260 is fixed. if (document == null) { Debug.Assert(solution.Workspace.Kind is WorkspaceKind.Interactive or WorkspaceKind.MiscellaneousFiles); continue; } if (documentToSearch.Contains(document)) { await AddLocationSpanAsync(location, solution, spanSet, tagMap, HighlightSpanKind.Definition, cancellationToken).ConfigureAwait(false); } } } } foreach (var referenceLocation in reference.Locations) { var referenceKind = referenceLocation.IsWrittenTo ? HighlightSpanKind.WrittenReference : HighlightSpanKind.Reference; await AddLocationSpanAsync(referenceLocation.Location, solution, spanSet, tagMap, referenceKind, cancellationToken).ConfigureAwait(false); } } // Add additional references foreach (var location in additionalReferences) { await AddLocationSpanAsync(location, solution, spanSet, tagMap, HighlightSpanKind.Reference, cancellationToken).ConfigureAwait(false); } using var listDisposer = ArrayBuilder<DocumentHighlights>.GetInstance(tagMap.Count, out var list); foreach (var kvp in tagMap) { using var spansDisposer = ArrayBuilder<HighlightSpan>.GetInstance(kvp.Value.Count, out var spans); foreach (var span in kvp.Value) { spans.Add(span); } list.Add(new DocumentHighlights(kvp.Key, spans.ToImmutable())); } return list.ToImmutable(); } private static bool ShouldIncludeDefinition(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Namespace: return false; case SymbolKind.NamedType: return !((INamedTypeSymbol)symbol).IsScriptClass; } return true; } private static async Task AddLocationSpanAsync(Location location, Solution solution, HashSet<DocumentSpan> spanSet, MultiDictionary<Document, HighlightSpan> tagList, HighlightSpanKind kind, CancellationToken cancellationToken) { var span = await GetLocationSpanAsync(solution, location, cancellationToken).ConfigureAwait(false); if (span != null && !spanSet.Contains(span.Value)) { spanSet.Add(span.Value); tagList.Add(span.Value.Document, new HighlightSpan(span.Value.SourceSpan, kind)); } } private static async Task<DocumentSpan?> GetLocationSpanAsync( Solution solution, Location location, CancellationToken cancellationToken) { try { if (location != null && location.IsInSource) { var tree = location.SourceTree; var document = solution.GetRequiredDocument(tree); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts != null) { // Specify findInsideTrivia: true to ensure that we search within XML doc comments. var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(location.SourceSpan.Start, findInsideTrivia: true); return syntaxFacts.IsGenericName(token.Parent) || syntaxFacts.IsIndexerMemberCRef(token.Parent) ? new DocumentSpan(document, token.Span) : new DocumentSpan(document, location.SourceSpan); } } } catch (NullReferenceException e) when (FatalError.ReportAndCatch(e)) { // We currently are seeing a strange null references crash in this code. We have // a strong belief that this is recoverable, but we'd like to know why it is // happening. This exception filter allows us to report the issue and continue // without damaging the user experience. Once we get more crash reports, we // can figure out the root cause and address appropriately. This is preferable // to just using conditionl access operators to be resilient (as we won't actually // know why this is happening). } return null; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/DocumentationCommentExtensions.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.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class DocumentationCommentExtensions { public static bool IsMultilineDocComment([NotNullWhen(true)] this DocumentationCommentTriviaSyntax? documentationComment) { if (documentationComment == null) { return false; } return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal); } } }
// 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.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class DocumentationCommentExtensions { public static bool IsMultilineDocComment([NotNullWhen(true)] this DocumentationCommentTriviaSyntax? documentationComment) { if (documentationComment == null) { return false; } return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Def/Implementation/Preview/PreviewUpdater.Tagger.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.Linq; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal partial class PreviewUpdater { internal class PreviewTagger : ITagger<HighlightTag> { private readonly ITextBuffer _textBuffer; private Span _span; public PreviewTagger(ITextBuffer textBuffer) { _textBuffer = textBuffer; } public Span Span { get { return _span; } set { _span = value; TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(_textBuffer.CurrentSnapshot.GetFullSpan())); } } public event EventHandler<SnapshotSpanEventArgs>? TagsChanged; public IEnumerable<ITagSpan<HighlightTag>> GetTags(NormalizedSnapshotSpanCollection spans) { var lines = _textBuffer.CurrentSnapshot.Lines.Where(line => line.Extent.OverlapsWith(_span)); foreach (var line in lines) { var firstNonWhitespace = line.GetFirstNonWhitespacePosition(); var lastNonWhitespace = line.GetLastNonWhitespacePosition(); if (firstNonWhitespace.HasValue && lastNonWhitespace.HasValue) { yield return new TagSpan<HighlightTag>(new SnapshotSpan(_textBuffer.CurrentSnapshot, Span.FromBounds(firstNonWhitespace.Value, lastNonWhitespace.Value + 1)), new HighlightTag()); } } } } } }
// 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.Linq; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Preview { internal partial class PreviewUpdater { internal class PreviewTagger : ITagger<HighlightTag> { private readonly ITextBuffer _textBuffer; private Span _span; public PreviewTagger(ITextBuffer textBuffer) { _textBuffer = textBuffer; } public Span Span { get { return _span; } set { _span = value; TagsChanged?.Invoke(this, new SnapshotSpanEventArgs(_textBuffer.CurrentSnapshot.GetFullSpan())); } } public event EventHandler<SnapshotSpanEventArgs>? TagsChanged; public IEnumerable<ITagSpan<HighlightTag>> GetTags(NormalizedSnapshotSpanCollection spans) { var lines = _textBuffer.CurrentSnapshot.Lines.Where(line => line.Extent.OverlapsWith(_span)); foreach (var line in lines) { var firstNonWhitespace = line.GetFirstNonWhitespacePosition(); var lastNonWhitespace = line.GetLastNonWhitespacePosition(); if (firstNonWhitespace.HasValue && lastNonWhitespace.HasValue) { yield return new TagSpan<HighlightTag>(new SnapshotSpan(_textBuffer.CurrentSnapshot, Span.FromBounds(firstNonWhitespace.Value, lastNonWhitespace.Value + 1)), new HighlightTag()); } } } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.MethodTypeParameterTypeSymbol.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.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests #Region "FAR on generic methods" <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_Parameter1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void Goo<{|Definition:$$T|}>([|T|] x1, t x2) { } }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_Parameter3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class C { void Goo<{|Definition:$$T|}>(X<[|T|]> t) { } void Bar<T>(T t) { } }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_ParameterCaseSensitivity(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> partial class C sub Goo(of {|Definition:$$T|})(x as [|T|], x1 as [|t|]) end sub end class</Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_MethodCall(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; interface GenericInterface<T> { void {|Definition:IntMethod|}<T>(T t); } class GenericClass<T> : GenericInterface<T> { public void {|Definition:IntMethod|}<T>(T t) { } } class M { public M() { GenericClass<string> GCObj = new GenericClass<string>(); GCObj.[|$$IntMethod|]<string>("goo"); } }]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function #End Region #Region "FAR on generic partial methods" <WorkItem(544436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544436")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_CSharp1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:$$T|}>([|T|] t) { } }]]></Document> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:T|}>([|T|] t); }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(544436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544436"), WorkItem(544475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544475")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_CSharp2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:T|}>([|T|] t) { } }]]></Document> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:$$T|}>([|T|] t); }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(544435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544435")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_VB1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ partial class C sub Goo(Of {|Definition:$$T|})(t as [|T|]) end sub end class]]> </Document> <Document><![CDATA[ partial class C partial sub Goo(Of {|Definition:T|})(t as [|T|]) end sub end class]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(544435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544435")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_VB2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ partial class C sub Goo(Of {|Definition:T|})(t as [|T|]) end sub end class]]> </Document> <Document><![CDATA[ partial class C partial sub Goo(Of {|Definition:$$T|})(t as [|T|]) end sub end class]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) 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.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests #Region "FAR on generic methods" <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_Parameter1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void Goo<{|Definition:$$T|}>([|T|] x1, t x2) { } }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_Parameter3(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class C { void Goo<{|Definition:$$T|}>(X<[|T|]> t) { } void Bar<T>(T t) { } }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_ParameterCaseSensitivity(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> partial class C sub Goo(of {|Definition:$$T|})(x as [|T|], x1 as [|t|]) end sub end class</Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_MethodCall(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; interface GenericInterface<T> { void {|Definition:IntMethod|}<T>(T t); } class GenericClass<T> : GenericInterface<T> { public void {|Definition:IntMethod|}<T>(T t) { } } class M { public M() { GenericClass<string> GCObj = new GenericClass<string>(); GCObj.[|$$IntMethod|]<string>("goo"); } }]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function #End Region #Region "FAR on generic partial methods" <WorkItem(544436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544436")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_CSharp1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:$$T|}>([|T|] t) { } }]]></Document> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:T|}>([|T|] t); }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(544436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544436"), WorkItem(544475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544475")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_CSharp2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:T|}>([|T|] t) { } }]]></Document> <Document><![CDATA[ partial class C { partial void Goo<{|Definition:$$T|}>([|T|] t); }]]></Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(544435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544435")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_VB1(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ partial class C sub Goo(Of {|Definition:$$T|})(t as [|T|]) end sub end class]]> </Document> <Document><![CDATA[ partial class C partial sub Goo(Of {|Definition:T|})(t as [|T|]) end sub end class]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function <WorkItem(544435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544435")> <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestMethodType_GenericPartialParameter_VB2(kind As TestKind, host As TestHost) As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ partial class C sub Goo(Of {|Definition:T|})(t as [|T|]) end sub end class]]> </Document> <Document><![CDATA[ partial class C partial sub Goo(Of {|Definition:$$T|})(t as [|T|]) end sub end class]]> </Document> </Project> </Workspace> Await TestAPIAndFeature(input, kind, host) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedFieldSymbolBase.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.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a compiler generated field or captured variable. /// </summary> internal abstract class SynthesizedFieldSymbolBase : FieldSymbol { private readonly NamedTypeSymbol _containingType; private readonly string _name; private readonly DeclarationModifiers _modifiers; public SynthesizedFieldSymbolBase( NamedTypeSymbol containingType, string name, bool isPublic, bool isReadOnly, bool isStatic) { Debug.Assert((object)containingType != null); Debug.Assert(!string.IsNullOrEmpty(name)); _containingType = containingType; _name = name; _modifiers = (isPublic ? DeclarationModifiers.Public : DeclarationModifiers.Private) | (isReadOnly ? DeclarationModifiers.ReadOnly : DeclarationModifiers.None) | (isStatic ? DeclarationModifiers.Static : DeclarationModifiers.None); } internal abstract bool SuppressDynamicAttribute { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); CSharpCompilation compilation = this.DeclaringCompilation; var typeWithAnnotations = this.TypeWithAnnotations; var type = typeWithAnnotations.Type; // do not emit CompilerGenerated attributes for fields inside compiler generated types: if (!_containingType.IsImplicitlyDeclared) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } if (!this.SuppressDynamicAttribute && type.ContainsDynamic() && compilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitBoolean()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type, typeWithAnnotations.CustomModifiers.Length)); } if (type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type)); } if (type.ContainsTupleNames() && compilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitSpecialType(SpecialType.System_String)) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(Type)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations)); } } internal abstract override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound); public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override string Name { get { return _name; } } public override Symbol AssociatedSymbol { get { return null; } } public override bool IsReadOnly { get { return (_modifiers & DeclarationModifiers.ReadOnly) != 0; } } public override bool IsVolatile { get { return false; } } public override bool IsConst { get { return false; } } internal override bool IsNotSerialized { get { return false; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return null; } } internal override int? TypeLayoutOffset { get { return null; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { return null; } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_modifiers); } } public override bool IsStatic { get { return (_modifiers & DeclarationModifiers.Static) != 0; } } internal override bool HasSpecialName { get { return this.HasRuntimeSpecialName; } } internal override bool HasRuntimeSpecialName { get { return this.Name == WellKnownMemberNames.EnumBackingFieldName; } } public override bool IsImplicitlyDeclared { get { 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.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a compiler generated field or captured variable. /// </summary> internal abstract class SynthesizedFieldSymbolBase : FieldSymbol { private readonly NamedTypeSymbol _containingType; private readonly string _name; private readonly DeclarationModifiers _modifiers; public SynthesizedFieldSymbolBase( NamedTypeSymbol containingType, string name, bool isPublic, bool isReadOnly, bool isStatic) { Debug.Assert((object)containingType != null); Debug.Assert(!string.IsNullOrEmpty(name)); _containingType = containingType; _name = name; _modifiers = (isPublic ? DeclarationModifiers.Public : DeclarationModifiers.Private) | (isReadOnly ? DeclarationModifiers.ReadOnly : DeclarationModifiers.None) | (isStatic ? DeclarationModifiers.Static : DeclarationModifiers.None); } internal abstract bool SuppressDynamicAttribute { get; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); CSharpCompilation compilation = this.DeclaringCompilation; var typeWithAnnotations = this.TypeWithAnnotations; var type = typeWithAnnotations.Type; // do not emit CompilerGenerated attributes for fields inside compiler generated types: if (!_containingType.IsImplicitlyDeclared) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } if (!this.SuppressDynamicAttribute && type.ContainsDynamic() && compilation.HasDynamicEmitAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitBoolean()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(type, typeWithAnnotations.CustomModifiers.Length)); } if (type.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, type)); } if (type.ContainsTupleNames() && compilation.HasTupleNamesAttributes(BindingDiagnosticBag.Discarded, Location.None) && compilation.CanEmitSpecialType(SpecialType.System_String)) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(Type)); } if (compilation.ShouldEmitNullableAttributes(this)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, ContainingType.GetNullableContextValue(), typeWithAnnotations)); } } internal abstract override TypeWithAnnotations GetFieldType(ConsList<FieldSymbol> fieldsBeingBound); public override FlowAnalysisAnnotations FlowAnalysisAnnotations => FlowAnalysisAnnotations.None; public override string Name { get { return _name; } } public override Symbol AssociatedSymbol { get { return null; } } public override bool IsReadOnly { get { return (_modifiers & DeclarationModifiers.ReadOnly) != 0; } } public override bool IsVolatile { get { return false; } } public override bool IsConst { get { return false; } } internal override bool IsNotSerialized { get { return false; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return null; } } internal override int? TypeLayoutOffset { get { return null; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { return null; } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } public override Symbol ContainingSymbol { get { return _containingType; } } public override NamedTypeSymbol ContainingType { get { return _containingType; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray<Location>.Empty; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray<SyntaxReference>.Empty; } } public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_modifiers); } } public override bool IsStatic { get { return (_modifiers & DeclarationModifiers.Static) != 0; } } internal override bool HasSpecialName { get { return this.HasRuntimeSpecialName; } } internal override bool HasRuntimeSpecialName { get { return this.Name == WellKnownMemberNames.EnumBackingFieldName; } } public override bool IsImplicitlyDeclared { get { return true; } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.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.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public abstract partial class AbstractMetadataAsSourceTests { public const string DefaultMetadataSource = "public class C {}"; public const string DefaultSymbolMetadataName = "C"; internal class TestContext : IDisposable { public readonly TestWorkspace Workspace; private readonly IMetadataAsSourceFileService _metadataAsSourceService; public static TestContext Create( string? projectLanguage = null, IEnumerable<string>? metadataSources = null, bool includeXmlDocComments = false, string? sourceWithSymbolReference = null, string? languageVersion = null, string? metadataLanguageVersion = null) { projectLanguage ??= LanguageNames.CSharp; metadataSources ??= SpecializedCollections.EmptyEnumerable<string>(); metadataSources = !metadataSources.Any() ? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource } : metadataSources; var workspace = CreateWorkspace( projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference, languageVersion, metadataLanguageVersion); return new TestContext(workspace); } public TestContext(TestWorkspace workspace) { Workspace = workspace; _metadataAsSourceService = Workspace.GetService<IMetadataAsSourceFileService>(); } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public Project DefaultProject { get { return this.CurrentSolution.Projects.First(); } } public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project? project = null, bool allowDecompilation = false) { project ??= this.DefaultProject; Contract.ThrowIfNull(symbol); // Generate and hold onto the result so it can be disposed of with this context return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); } public async Task<MetadataAsSourceFile> GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool allowDecompilation = false) { symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName; project ??= this.DefaultProject; // Get an ISymbol corresponding to the metadata name var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation); Contract.ThrowIfNull(symbol); if (allowDecompilation) { foreach (var reference in compilation.References) { if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference)) { continue; } if (reference is PortableExecutableReference portableExecutable) { Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'"); Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name"); } else { Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist"); Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name"); } } } // Generate and hold onto the result so it can be disposed of with this context var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); return result; } public static void VerifyResult(MetadataAsSourceFile file, string expected) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; // Compare exact texts and verify that the location returned is exactly that // indicated by expected MarkupTestFile.GetSpan(expected, out expected, out var expectedSpan); AssertEx.EqualOrDiff(expected, actual); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool allowDecompilation = false) { var result = await GenerateSourceAsync(symbolMetadataName, project, allowDecompilation); VerifyResult(result, expected); } public static void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.Same(a.FilePath, b.FilePath); public static void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.NotSame(a.FilePath, b.FilePath); public void Dispose() { try { _metadataAsSourceService.CleanupGeneratedFiles(); } finally { Workspace.Dispose(); } } public async Task<ISymbol?> ResolveSymbolAsync(string symbolMetadataName, Compilation? compilation = null) { if (compilation == null) { compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); } foreach (var reference in compilation.References) { var assemblySymbol = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(reference); Contract.ThrowIfNull(assemblySymbol); var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName); if (namedTypeSymbol != null) { return namedTypeSymbol; } else { // The symbol name could possibly be referring to the member of a named // type. Parse the member symbol name. var lastDotIndex = symbolMetadataName.LastIndexOf('.'); if (lastDotIndex < 0) { // The symbol name is not a member name and the named type was not found // in this assembly continue; } // The member symbol name itself could contain a dot (e.g. '.ctor'), so make // sure we don't cut that off while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.') { --lastDotIndex; } var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1); var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex); namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName); if (namedTypeSymbol != null) { var memberSymbol = namedTypeSymbol.GetMembers() .Where(member => member.MetadataName == memberSymbolName) .FirstOrDefault(); if (memberSymbol != null) { return memberSymbol; } } } } return null; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim"); } private static string DeduceLanguageString(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static TestWorkspace CreateWorkspace( string projectLanguage, IEnumerable<string>? metadataSources, bool includeXmlDocComments, string? sourceWithSymbolReference, string? languageVersion, string? metadataLanguageVersion) { var languageVersionAttribute = languageVersion is null ? "" : $@" LanguageVersion=""{languageVersion}"""; var xmlString = string.Concat(@" <Workspace> <Project Language=""", projectLanguage, @""" CommonReferences=""true"" ReferencesOnDisk=""true""", languageVersionAttribute); xmlString += ">"; metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }; foreach (var source in metadataSources) { var metadataLanguage = DeduceLanguageString(source); var metadataLanguageVersionAttribute = metadataLanguageVersion is null ? "" : $@" LanguageVersion=""{metadataLanguageVersion}"""; xmlString = string.Concat(xmlString, $@" <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}""> <Document FilePath=""MetadataDocument""> {SecurityElement.Escape(source)} </Document> </MetadataReferenceFromSource>"); } if (sourceWithSymbolReference != null) { xmlString = string.Concat(xmlString, string.Format(@" <Document FilePath=""SourceDocument""> {0} </Document>", sourceWithSymbolReference)); } xmlString = string.Concat(xmlString, @" </Project> </Workspace>"); return TestWorkspace.Create(xmlString); } internal Document GetDocument(MetadataAsSourceFile file) { using var reader = File.OpenRead(file.FilePath); var stringText = EncodedStringText.Create(reader); Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, stringText.Container)); return stringText.Container.GetRelatedDocuments().Single(); } internal async Task<ISymbol> GetNavigationSymbolAsync() { var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None); var symbol = semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol; Contract.ThrowIfNull(symbol); return symbol; } } } }
// 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.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public abstract partial class AbstractMetadataAsSourceTests { public const string DefaultMetadataSource = "public class C {}"; public const string DefaultSymbolMetadataName = "C"; internal class TestContext : IDisposable { public readonly TestWorkspace Workspace; private readonly IMetadataAsSourceFileService _metadataAsSourceService; public static TestContext Create( string? projectLanguage = null, IEnumerable<string>? metadataSources = null, bool includeXmlDocComments = false, string? sourceWithSymbolReference = null, string? languageVersion = null, string? metadataLanguageVersion = null) { projectLanguage ??= LanguageNames.CSharp; metadataSources ??= SpecializedCollections.EmptyEnumerable<string>(); metadataSources = !metadataSources.Any() ? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource } : metadataSources; var workspace = CreateWorkspace( projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference, languageVersion, metadataLanguageVersion); return new TestContext(workspace); } public TestContext(TestWorkspace workspace) { Workspace = workspace; _metadataAsSourceService = Workspace.GetService<IMetadataAsSourceFileService>(); } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public Project DefaultProject { get { return this.CurrentSolution.Projects.First(); } } public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project? project = null, bool allowDecompilation = false) { project ??= this.DefaultProject; Contract.ThrowIfNull(symbol); // Generate and hold onto the result so it can be disposed of with this context return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); } public async Task<MetadataAsSourceFile> GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool allowDecompilation = false) { symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName; project ??= this.DefaultProject; // Get an ISymbol corresponding to the metadata name var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation); Contract.ThrowIfNull(symbol); if (allowDecompilation) { foreach (var reference in compilation.References) { if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference)) { continue; } if (reference is PortableExecutableReference portableExecutable) { Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'"); Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name"); } else { Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist"); Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name"); } } } // Generate and hold onto the result so it can be disposed of with this context var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); return result; } public static void VerifyResult(MetadataAsSourceFile file, string expected) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; // Compare exact texts and verify that the location returned is exactly that // indicated by expected MarkupTestFile.GetSpan(expected, out expected, out var expectedSpan); AssertEx.EqualOrDiff(expected, actual); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool allowDecompilation = false) { var result = await GenerateSourceAsync(symbolMetadataName, project, allowDecompilation); VerifyResult(result, expected); } public static void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.Same(a.FilePath, b.FilePath); public static void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.NotSame(a.FilePath, b.FilePath); public void Dispose() { try { _metadataAsSourceService.CleanupGeneratedFiles(); } finally { Workspace.Dispose(); } } public async Task<ISymbol?> ResolveSymbolAsync(string symbolMetadataName, Compilation? compilation = null) { if (compilation == null) { compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); } foreach (var reference in compilation.References) { var assemblySymbol = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(reference); Contract.ThrowIfNull(assemblySymbol); var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName); if (namedTypeSymbol != null) { return namedTypeSymbol; } else { // The symbol name could possibly be referring to the member of a named // type. Parse the member symbol name. var lastDotIndex = symbolMetadataName.LastIndexOf('.'); if (lastDotIndex < 0) { // The symbol name is not a member name and the named type was not found // in this assembly continue; } // The member symbol name itself could contain a dot (e.g. '.ctor'), so make // sure we don't cut that off while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.') { --lastDotIndex; } var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1); var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex); namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName); if (namedTypeSymbol != null) { var memberSymbol = namedTypeSymbol.GetMembers() .Where(member => member.MetadataName == memberSymbolName) .FirstOrDefault(); if (memberSymbol != null) { return memberSymbol; } } } } return null; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim"); } private static string DeduceLanguageString(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static TestWorkspace CreateWorkspace( string projectLanguage, IEnumerable<string>? metadataSources, bool includeXmlDocComments, string? sourceWithSymbolReference, string? languageVersion, string? metadataLanguageVersion) { var languageVersionAttribute = languageVersion is null ? "" : $@" LanguageVersion=""{languageVersion}"""; var xmlString = string.Concat(@" <Workspace> <Project Language=""", projectLanguage, @""" CommonReferences=""true"" ReferencesOnDisk=""true""", languageVersionAttribute); xmlString += ">"; metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }; foreach (var source in metadataSources) { var metadataLanguage = DeduceLanguageString(source); var metadataLanguageVersionAttribute = metadataLanguageVersion is null ? "" : $@" LanguageVersion=""{metadataLanguageVersion}"""; xmlString = string.Concat(xmlString, $@" <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}""> <Document FilePath=""MetadataDocument""> {SecurityElement.Escape(source)} </Document> </MetadataReferenceFromSource>"); } if (sourceWithSymbolReference != null) { xmlString = string.Concat(xmlString, string.Format(@" <Document FilePath=""SourceDocument""> {0} </Document>", sourceWithSymbolReference)); } xmlString = string.Concat(xmlString, @" </Project> </Workspace>"); return TestWorkspace.Create(xmlString); } internal Document GetDocument(MetadataAsSourceFile file) { using var reader = File.OpenRead(file.FilePath); var stringText = EncodedStringText.Create(reader); Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, stringText.Container)); return stringText.Container.GetRelatedDocuments().Single(); } internal async Task<ISymbol> GetNavigationSymbolAsync() { var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None); var symbol = semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol; Contract.ThrowIfNull(symbol); return symbol; } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Remote/ServiceHub/Host/TestUtils.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.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; #if DEBUG using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Internal.Log; #endif namespace Microsoft.CodeAnalysis.Remote { internal static class TestUtils { public static void RemoveChecksums(this Dictionary<Checksum, object> map, ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); RemoveChecksums(map, set); } public static void RemoveChecksums(this Dictionary<Checksum, object> map, IEnumerable<Checksum> checksums) { foreach (var checksum in checksums) { map.Remove(checksum); } } internal static async Task AssertChecksumsAsync( AssetProvider assetService, Checksum checksumFromRequest, Solution solutionFromScratch, Solution incrementalSolutionBuilt) { #if DEBUG var sb = new StringBuilder(); var allChecksumsFromRequest = await GetAllChildrenChecksumsAsync(checksumFromRequest).ConfigureAwait(false); var assetMapFromNewSolution = await solutionFromScratch.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); var assetMapFromIncrementalSolution = await incrementalSolutionBuilt.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); // check 4 things // 1. first see if we create new solution from scratch, it works as expected (indicating a bug in incremental update) var mismatch1 = assetMapFromNewSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch1, "assets only in new solutoin but not in the request", sb); // 2. second check what items is mismatching for incremental solution var mismatch2 = assetMapFromIncrementalSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch2, "assets only in the incremental solution but not in the request", sb); // 3. check whether solution created from scratch and incremental one have any mismatch var mismatch3 = assetMapFromNewSolution.Where(p => !assetMapFromIncrementalSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch3, "assets only in new solution but not in incremental solution", sb); var mismatch4 = assetMapFromIncrementalSolution.Where(p => !assetMapFromNewSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch4, "assets only in incremental solution but not in new solution", sb); // 4. see what item is missing from request var mismatch5 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromNewSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch5, "assets only in the request but not in new solution", sb); var mismatch6 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromIncrementalSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch6, "assets only in the request but not in incremental solution", sb); var result = sb.ToString(); if (result.Length > 0) { Logger.Log(FunctionId.SolutionCreator_AssetDifferences, result); Debug.Fail("Differences detected in solution checksum: " + result); } static void AppendMismatch(List<KeyValuePair<Checksum, object>> items, string title, StringBuilder stringBuilder) { if (items.Count == 0) { return; } stringBuilder.AppendLine(title); foreach (var kv in items) { stringBuilder.AppendLine($"{kv.Key.ToString()}, {kv.Value.ToString()}"); } stringBuilder.AppendLine(); } async Task<List<KeyValuePair<Checksum, object>>> GetAssetFromAssetServiceAsync(IEnumerable<Checksum> checksums) { var items = new List<KeyValuePair<Checksum, object>>(); foreach (var checksum in checksums) { items.Add(new KeyValuePair<Checksum, object>(checksum, await assetService.GetAssetAsync<object>(checksum, CancellationToken.None).ConfigureAwait(false))); } return items; } async Task<HashSet<Checksum>> GetAllChildrenChecksumsAsync(Checksum solutionChecksum) { var set = new HashSet<Checksum>(); var solutionChecksums = await assetService.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(solutionChecksums); foreach (var projectChecksum in solutionChecksums.Projects) { var projectChecksums = await assetService.GetAssetAsync<ProjectStateChecksums>(projectChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(projectChecksums); foreach (var documentChecksum in projectChecksums.Documents.Concat(projectChecksums.AdditionalDocuments).Concat(projectChecksums.AnalyzerConfigDocuments)) { var documentChecksums = await assetService.GetAssetAsync<DocumentStateChecksums>(documentChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(documentChecksums); } } return set; } #else // have this to avoid error on async await Task.CompletedTask.ConfigureAwait(false); #endif } /// <summary> /// create checksum to correspoing object map from solution /// this map should contain every parts of solution that can be used to re-create the solution back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Solution solution, bool includeProjectCones, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await solution.AppendAssetMapAsync(includeProjectCones, map, cancellationToken).ConfigureAwait(false); return map; } /// <summary> /// create checksum to correspoing object map from project /// this map should contain every parts of project that can be used to re-create the project back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Project project, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); return map; } public static async Task AppendAssetMapAsync(this Solution solution, bool includeProjectCones, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { var solutionChecksums = await solution.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await solutionChecksums.FindAsync(solution.State, Flatten(solutionChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var project in solution.Projects) { if (includeProjectCones) { var projectSubsetChecksums = await solution.State.GetStateChecksumsAsync(project.Id, cancellationToken).ConfigureAwait(false); await projectSubsetChecksums.FindAsync(solution.State, Flatten(projectSubsetChecksums), map, cancellationToken).ConfigureAwait(false); } await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); } } private static async Task AppendAssetMapAsync(this Project project, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { if (!RemoteSupportedLanguages.IsSupported(project.Language)) { return; } var projectChecksums = await project.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await projectChecksums.FindAsync(project.State, Flatten(projectChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var document in project.Documents.Concat(project.AdditionalDocuments).Concat(project.AnalyzerConfigDocuments)) { var documentChecksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await documentChecksums.FindAsync(document.State, Flatten(documentChecksums), map, cancellationToken).ConfigureAwait(false); } } private static HashSet<Checksum> Flatten(ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); return set; } public static void AppendChecksums(this HashSet<Checksum> set, ChecksumWithChildren checksums) { set.Add(checksums.Checksum); foreach (var child in checksums.Children) { if (child is Checksum checksum) { if (checksum != Checksum.Null) set.Add(checksum); } if (child is ChecksumCollection collection) { set.AppendChecksums(collection); } } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; #if DEBUG using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Internal.Log; #endif namespace Microsoft.CodeAnalysis.Remote { internal static class TestUtils { public static void RemoveChecksums(this Dictionary<Checksum, object> map, ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); RemoveChecksums(map, set); } public static void RemoveChecksums(this Dictionary<Checksum, object> map, IEnumerable<Checksum> checksums) { foreach (var checksum in checksums) { map.Remove(checksum); } } internal static async Task AssertChecksumsAsync( AssetProvider assetService, Checksum checksumFromRequest, Solution solutionFromScratch, Solution incrementalSolutionBuilt) { #if DEBUG var sb = new StringBuilder(); var allChecksumsFromRequest = await GetAllChildrenChecksumsAsync(checksumFromRequest).ConfigureAwait(false); var assetMapFromNewSolution = await solutionFromScratch.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); var assetMapFromIncrementalSolution = await incrementalSolutionBuilt.GetAssetMapAsync(includeProjectCones: true, CancellationToken.None).ConfigureAwait(false); // check 4 things // 1. first see if we create new solution from scratch, it works as expected (indicating a bug in incremental update) var mismatch1 = assetMapFromNewSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch1, "assets only in new solutoin but not in the request", sb); // 2. second check what items is mismatching for incremental solution var mismatch2 = assetMapFromIncrementalSolution.Where(p => !allChecksumsFromRequest.Contains(p.Key)).ToList(); AppendMismatch(mismatch2, "assets only in the incremental solution but not in the request", sb); // 3. check whether solution created from scratch and incremental one have any mismatch var mismatch3 = assetMapFromNewSolution.Where(p => !assetMapFromIncrementalSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch3, "assets only in new solution but not in incremental solution", sb); var mismatch4 = assetMapFromIncrementalSolution.Where(p => !assetMapFromNewSolution.ContainsKey(p.Key)).ToList(); AppendMismatch(mismatch4, "assets only in incremental solution but not in new solution", sb); // 4. see what item is missing from request var mismatch5 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromNewSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch5, "assets only in the request but not in new solution", sb); var mismatch6 = await GetAssetFromAssetServiceAsync(allChecksumsFromRequest.Except(assetMapFromIncrementalSolution.Keys)).ConfigureAwait(false); AppendMismatch(mismatch6, "assets only in the request but not in incremental solution", sb); var result = sb.ToString(); if (result.Length > 0) { Logger.Log(FunctionId.SolutionCreator_AssetDifferences, result); Debug.Fail("Differences detected in solution checksum: " + result); } static void AppendMismatch(List<KeyValuePair<Checksum, object>> items, string title, StringBuilder stringBuilder) { if (items.Count == 0) { return; } stringBuilder.AppendLine(title); foreach (var kv in items) { stringBuilder.AppendLine($"{kv.Key.ToString()}, {kv.Value.ToString()}"); } stringBuilder.AppendLine(); } async Task<List<KeyValuePair<Checksum, object>>> GetAssetFromAssetServiceAsync(IEnumerable<Checksum> checksums) { var items = new List<KeyValuePair<Checksum, object>>(); foreach (var checksum in checksums) { items.Add(new KeyValuePair<Checksum, object>(checksum, await assetService.GetAssetAsync<object>(checksum, CancellationToken.None).ConfigureAwait(false))); } return items; } async Task<HashSet<Checksum>> GetAllChildrenChecksumsAsync(Checksum solutionChecksum) { var set = new HashSet<Checksum>(); var solutionChecksums = await assetService.GetAssetAsync<SolutionStateChecksums>(solutionChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(solutionChecksums); foreach (var projectChecksum in solutionChecksums.Projects) { var projectChecksums = await assetService.GetAssetAsync<ProjectStateChecksums>(projectChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(projectChecksums); foreach (var documentChecksum in projectChecksums.Documents.Concat(projectChecksums.AdditionalDocuments).Concat(projectChecksums.AnalyzerConfigDocuments)) { var documentChecksums = await assetService.GetAssetAsync<DocumentStateChecksums>(documentChecksum, CancellationToken.None).ConfigureAwait(false); set.AppendChecksums(documentChecksums); } } return set; } #else // have this to avoid error on async await Task.CompletedTask.ConfigureAwait(false); #endif } /// <summary> /// create checksum to correspoing object map from solution /// this map should contain every parts of solution that can be used to re-create the solution back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Solution solution, bool includeProjectCones, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await solution.AppendAssetMapAsync(includeProjectCones, map, cancellationToken).ConfigureAwait(false); return map; } /// <summary> /// create checksum to correspoing object map from project /// this map should contain every parts of project that can be used to re-create the project back /// </summary> public static async Task<Dictionary<Checksum, object>> GetAssetMapAsync(this Project project, CancellationToken cancellationToken) { var map = new Dictionary<Checksum, object>(); await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); return map; } public static async Task AppendAssetMapAsync(this Solution solution, bool includeProjectCones, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { var solutionChecksums = await solution.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await solutionChecksums.FindAsync(solution.State, Flatten(solutionChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var project in solution.Projects) { if (includeProjectCones) { var projectSubsetChecksums = await solution.State.GetStateChecksumsAsync(project.Id, cancellationToken).ConfigureAwait(false); await projectSubsetChecksums.FindAsync(solution.State, Flatten(projectSubsetChecksums), map, cancellationToken).ConfigureAwait(false); } await project.AppendAssetMapAsync(map, cancellationToken).ConfigureAwait(false); } } private static async Task AppendAssetMapAsync(this Project project, Dictionary<Checksum, object> map, CancellationToken cancellationToken) { if (!RemoteSupportedLanguages.IsSupported(project.Language)) { return; } var projectChecksums = await project.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await projectChecksums.FindAsync(project.State, Flatten(projectChecksums), map, cancellationToken).ConfigureAwait(false); foreach (var document in project.Documents.Concat(project.AdditionalDocuments).Concat(project.AnalyzerConfigDocuments)) { var documentChecksums = await document.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false); await documentChecksums.FindAsync(document.State, Flatten(documentChecksums), map, cancellationToken).ConfigureAwait(false); } } private static HashSet<Checksum> Flatten(ChecksumWithChildren checksums) { var set = new HashSet<Checksum>(); set.AppendChecksums(checksums); return set; } public static void AppendChecksums(this HashSet<Checksum> set, ChecksumWithChildren checksums) { set.Add(checksums.Checksum); foreach (var child in checksums.Children) { if (child is Checksum checksum) { if (checksum != Checksum.Null) set.Add(checksum); } if (child is ChecksumCollection collection) { set.AppendChecksums(collection); } } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Analyzers/VisualBasic/CodeFixes/xlf/VisualBasicCodeFixesResources.es.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../VisualBasicCodeFixesResources.resx"> <body> <trans-unit id="Add_Me"> <source>Add 'Me.'</source> <target state="translated">Agregar "Me."</target> <note /> </trans-unit> <trans-unit id="Convert_GetType_to_NameOf"> <source>Convert 'GetType' to 'NameOf'</source> <target state="translated">Convertir "GetType" en "NameOf"</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Imports"> <source>Remove Unnecessary Imports</source> <target state="translated">Quitar instrucciones Import innecesarias</target> <note /> </trans-unit> <trans-unit id="Simplify_object_creation"> <source>Simplify object creation</source> <target state="translated">Simplificar la creación de objetos</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="es" original="../VisualBasicCodeFixesResources.resx"> <body> <trans-unit id="Add_Me"> <source>Add 'Me.'</source> <target state="translated">Agregar "Me."</target> <note /> </trans-unit> <trans-unit id="Convert_GetType_to_NameOf"> <source>Convert 'GetType' to 'NameOf'</source> <target state="translated">Convertir "GetType" en "NameOf"</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Imports"> <source>Remove Unnecessary Imports</source> <target state="translated">Quitar instrucciones Import innecesarias</target> <note /> </trans-unit> <trans-unit id="Simplify_object_creation"> <source>Simplify object creation</source> <target state="translated">Simplificar la creación de objetos</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Tools/IdeBenchmarks/IdeBenchmarks.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"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> <!-- Automatically generate the necessary assembly binding redirects --> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <NoWarn>$(NoWarn),CA2007</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetVersion)" /> <PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="$(BenchmarkDotNetDiagnosticsWindowsVersion)" /> <PackageReference Include="Microsoft.Build.Locator" Version="$(MicrosoftBuildLocatorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </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"> <Import Project="$(RepositoryEngineeringDir)targets\GenerateCompilerExecutableBindingRedirects.targets" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> <!-- Automatically generate the necessary assembly binding redirects --> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <NoWarn>$(NoWarn),CA2007</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="BenchmarkDotNet" Version="$(BenchmarkDotNetVersion)" /> <PackageReference Include="BenchmarkDotNet.Diagnostics.Windows" Version="$(BenchmarkDotNetDiagnosticsWindowsVersion)" /> <PackageReference Include="Microsoft.Build.Locator" Version="$(MicrosoftBuildLocatorVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Composition" Version="$(MicrosoftVisualStudioCompositionVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> </ItemGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\EditorFeatures\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\..\EditorFeatures\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Interactive\Host\Microsoft.CodeAnalysis.InteractiveHost.csproj" /> <ProjectReference Include="..\..\Scripting\Core\Microsoft.CodeAnalysis.Scripting.csproj" /> <ProjectReference Include="..\..\Scripting\CSharp\Microsoft.CodeAnalysis.CSharp.Scripting.csproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\MSBuild\Microsoft.CodeAnalysis.Workspaces.MSBuild.csproj" /> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\EditorFeatures\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <!-- These aren't used by the build, but it allows the tool to locate dependencies of the built-in analyzers. --> <ProjectReference Include="..\..\EditorFeatures\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\..\EditorFeatures\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> </ItemGroup> <ItemGroup> <None Include="app.config" /> </ItemGroup> </Project>
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Log/EtwLogger.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.Tracing; using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// A logger that publishes events to ETW using an EventSource. /// </summary> internal sealed class EtwLogger : ILogger { private readonly Lazy<Func<FunctionId, bool>> _isEnabledPredicate; // Due to ETW specifics, RoslynEventSource.Instance needs to be initialized during EtwLogger construction // so that we can enable the listeners synchronously before any events are logged. private readonly RoslynEventSource _source = RoslynEventSource.Instance; public EtwLogger(IGlobalOptionService globalOptions) => _isEnabledPredicate = new Lazy<Func<FunctionId, bool>>(() => Logger.GetLoggingChecker(globalOptions)); public EtwLogger(Func<FunctionId, bool> isEnabledPredicate) => _isEnabledPredicate = new Lazy<Func<FunctionId, bool>>(() => isEnabledPredicate); public bool IsEnabled(FunctionId functionId) => _source.IsEnabled() && _isEnabledPredicate.Value(functionId); public void Log(FunctionId functionId, LogMessage logMessage) => _source.Log(GetMessage(logMessage), functionId); public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) => _source.BlockStart(GetMessage(logMessage), functionId, uniquePairId); public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { _source.BlockCanceled(functionId, delta, uniquePairId); } else { _source.BlockStop(functionId, delta, uniquePairId); } } private bool IsVerbose() { // "-1" makes this to work with any keyword return _source.IsEnabled(EventLevel.Verbose, (EventKeywords)(-1)); } private string GetMessage(LogMessage logMessage) => IsVerbose() ? logMessage.GetMessage() : string.Empty; } }
// 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.Tracing; using System.Threading; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// A logger that publishes events to ETW using an EventSource. /// </summary> internal sealed class EtwLogger : ILogger { private readonly Lazy<Func<FunctionId, bool>> _isEnabledPredicate; // Due to ETW specifics, RoslynEventSource.Instance needs to be initialized during EtwLogger construction // so that we can enable the listeners synchronously before any events are logged. private readonly RoslynEventSource _source = RoslynEventSource.Instance; public EtwLogger(IGlobalOptionService globalOptions) => _isEnabledPredicate = new Lazy<Func<FunctionId, bool>>(() => Logger.GetLoggingChecker(globalOptions)); public EtwLogger(Func<FunctionId, bool> isEnabledPredicate) => _isEnabledPredicate = new Lazy<Func<FunctionId, bool>>(() => isEnabledPredicate); public bool IsEnabled(FunctionId functionId) => _source.IsEnabled() && _isEnabledPredicate.Value(functionId); public void Log(FunctionId functionId, LogMessage logMessage) => _source.Log(GetMessage(logMessage), functionId); public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) => _source.BlockStart(GetMessage(logMessage), functionId, uniquePairId); public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { _source.BlockCanceled(functionId, delta, uniquePairId); } else { _source.BlockStop(functionId, delta, uniquePairId); } } private bool IsVerbose() { // "-1" makes this to work with any keyword return _source.IsEnabled(EventLevel.Verbose, (EventKeywords)(-1)); } private string GetMessage(LogMessage logMessage) => IsVerbose() ? logMessage.GetMessage() : string.Empty; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Test/Emit/Emit/DynamicAnalysis/DynamicInstrumentationTests.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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Test.Utilities.CSharpInstrumentationChecker; namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests { public class DynamicInstrumentationTests : CSharpTestBase { [Fact] public void HelpersInstrumentation() { string source = @" using System; public class Program { public static void Main(string[] args) { Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } } "; string expectedOutput = @"Flushing Method 1 File 1 True True Method 4 File 1 True True False True True True True True True True True True True True True True "; string expectedCreatePayloadForMethodsSpanningSingleFileIL = @"{ // Code size 21 (0x15) .maxstack 6 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldarg.2 IL_000b: stelem.i4 IL_000c: ldarg.3 IL_000d: ldarg.s V_4 IL_000f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)"" IL_0014: ret }"; string expectedCreatePayloadForMethodsSpanningMultipleFilesIL = @"{ // Code size 87 (0x57) .maxstack 3 IL_0000: ldsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid"" IL_0005: ldarg.0 IL_0006: call ""bool System.Guid.op_Inequality(System.Guid, System.Guid)"" IL_000b: brfalse.s IL_002b IL_000d: ldc.i4.s 100 IL_000f: newarr ""bool[]"" IL_0014: stsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0019: ldc.i4.s 100 IL_001b: newarr ""int[]"" IL_0020: stsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_0025: ldarg.0 IL_0026: stsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid"" IL_002b: ldarg.3 IL_002c: ldarg.s V_4 IL_002e: newarr ""bool"" IL_0033: ldnull IL_0034: call ""bool[] System.Threading.Interlocked.CompareExchange<bool[]>(ref bool[], bool[], bool[])"" IL_0039: brtrue.s IL_004f IL_003b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0040: ldarg.1 IL_0041: ldarg.3 IL_0042: ldind.ref IL_0043: stelem.ref IL_0044: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_0049: ldarg.1 IL_004a: ldarg.2 IL_004b: stelem.ref IL_004c: ldarg.3 IL_004d: ldind.ref IL_004e: ret IL_004f: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0054: ldarg.1 IL_0055: ldelem.ref IL_0056: ret }"; string expectedFlushPayloadIL = @"{ // Code size 288 (0x120) .maxstack 5 .locals init (bool[] V_0, int V_1, //i bool[] V_2, //payload int V_3, //j int V_4) //j IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0035 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.s 16 IL_002f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0034: stloc.0 IL_0035: ldloc.0 IL_0036: ldc.i4.0 IL_0037: ldc.i4.1 IL_0038: stelem.i1 IL_0039: ldloc.0 IL_003a: ldc.i4.1 IL_003b: ldc.i4.1 IL_003c: stelem.i1 IL_003d: ldstr ""Flushing"" IL_0042: call ""void System.Console.WriteLine(string)"" IL_0047: ldloc.0 IL_0048: ldc.i4.3 IL_0049: ldc.i4.1 IL_004a: stelem.i1 IL_004b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0050: brtrue.s IL_0057 IL_0052: ldloc.0 IL_0053: ldc.i4.2 IL_0054: ldc.i4.1 IL_0055: stelem.i1 IL_0056: ret IL_0057: ldloc.0 IL_0058: ldc.i4.4 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldc.i4.0 IL_005c: stloc.1 IL_005d: br IL_0112 IL_0062: ldloc.0 IL_0063: ldc.i4.6 IL_0064: ldc.i4.1 IL_0065: stelem.i1 IL_0066: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_006b: ldloc.1 IL_006c: ldelem.ref IL_006d: stloc.2 IL_006e: ldloc.0 IL_006f: ldc.i4.s 15 IL_0071: ldc.i4.1 IL_0072: stelem.i1 IL_0073: ldloc.2 IL_0074: brfalse IL_010a IL_0079: ldloc.0 IL_007a: ldc.i4.7 IL_007b: ldc.i4.1 IL_007c: stelem.i1 IL_007d: ldstr ""Method "" IL_0082: ldloca.s V_1 IL_0084: call ""string int.ToString()"" IL_0089: call ""string string.Concat(string, string)"" IL_008e: call ""void System.Console.WriteLine(string)"" IL_0093: ldloc.0 IL_0094: ldc.i4.8 IL_0095: ldc.i4.1 IL_0096: stelem.i1 IL_0097: ldc.i4.0 IL_0098: stloc.3 IL_0099: br.s IL_00ca IL_009b: ldloc.0 IL_009c: ldc.i4.s 10 IL_009e: ldc.i4.1 IL_009f: stelem.i1 IL_00a0: ldstr ""File "" IL_00a5: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_00aa: ldloc.1 IL_00ab: ldelem.ref IL_00ac: ldloc.3 IL_00ad: ldelema ""int"" IL_00b2: call ""string int.ToString()"" IL_00b7: call ""string string.Concat(string, string)"" IL_00bc: call ""void System.Console.WriteLine(string)"" IL_00c1: ldloc.0 IL_00c2: ldc.i4.s 9 IL_00c4: ldc.i4.1 IL_00c5: stelem.i1 IL_00c6: ldloc.3 IL_00c7: ldc.i4.1 IL_00c8: add IL_00c9: stloc.3 IL_00ca: ldloc.3 IL_00cb: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_00d0: ldloc.1 IL_00d1: ldelem.ref IL_00d2: ldlen IL_00d3: conv.i4 IL_00d4: blt.s IL_009b IL_00d6: ldloc.0 IL_00d7: ldc.i4.s 11 IL_00d9: ldc.i4.1 IL_00da: stelem.i1 IL_00db: ldc.i4.0 IL_00dc: stloc.s V_4 IL_00de: br.s IL_0103 IL_00e0: ldloc.0 IL_00e1: ldc.i4.s 13 IL_00e3: ldc.i4.1 IL_00e4: stelem.i1 IL_00e5: ldloc.2 IL_00e6: ldloc.s V_4 IL_00e8: ldelem.u1 IL_00e9: call ""void System.Console.WriteLine(bool)"" IL_00ee: ldloc.0 IL_00ef: ldc.i4.s 14 IL_00f1: ldc.i4.1 IL_00f2: stelem.i1 IL_00f3: ldloc.2 IL_00f4: ldloc.s V_4 IL_00f6: ldc.i4.0 IL_00f7: stelem.i1 IL_00f8: ldloc.0 IL_00f9: ldc.i4.s 12 IL_00fb: ldc.i4.1 IL_00fc: stelem.i1 IL_00fd: ldloc.s V_4 IL_00ff: ldc.i4.1 IL_0100: add IL_0101: stloc.s V_4 IL_0103: ldloc.s V_4 IL_0105: ldloc.2 IL_0106: ldlen IL_0107: conv.i4 IL_0108: blt.s IL_00e0 IL_010a: ldloc.0 IL_010b: ldc.i4.5 IL_010c: ldc.i4.1 IL_010d: stelem.i1 IL_010e: ldloc.1 IL_010f: ldc.i4.1 IL_0110: add IL_0111: stloc.1 IL_0112: ldloc.1 IL_0113: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0118: ldlen IL_0119: conv.i4 IL_011a: blt IL_0062 IL_011f: ret }"; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)", expectedCreatePayloadForMethodsSpanningSingleFileIL); verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)", expectedCreatePayloadForMethodsSpanningMultipleFilesIL); verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload", expectedFlushPayloadIL); verifier.VerifyDiagnostics(); } [Fact] public void GotoCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() { Console.WriteLine(""goo""); goto bar; Console.Write(""you won't see me""); bar: Console.WriteLine(""bar""); Fred(); return; } static void Wilma() { Betty(true); Barney(true); Barney(false); Betty(true); } static int Barney(bool b) { if (b) return 10; if (b) return 100; return 20; } static int Betty(bool b) { if (b) return 30; if (b) return 100; return 40; } static void Fred() { Wilma(); } } "; string expectedOutput = @"goo bar Flushing Method 1 File 1 True True True Method 2 File 1 True True True False True True True Method 3 File 1 True True True True True Method 4 File 1 True True True False True True Method 5 File 1 True True True False False False Method 6 File 1 True True Method 9 File 1 True True False True True True True True True True True True True True True True "; string expectedBarneyIL = @"{ // Code size 91 (0x5b) .maxstack 5 .locals init (bool[] V_0) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""int Program.Barney(bool)"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""int Program.Barney(bool)"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""int Program.Barney(bool)"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.6 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: brfalse.s IL_0046 IL_003f: ldloc.0 IL_0040: ldc.i4.1 IL_0041: ldc.i4.1 IL_0042: stelem.i1 IL_0043: ldc.i4.s 10 IL_0045: ret IL_0046: ldloc.0 IL_0047: ldc.i4.4 IL_0048: ldc.i4.1 IL_0049: stelem.i1 IL_004a: ldarg.0 IL_004b: brfalse.s IL_0054 IL_004d: ldloc.0 IL_004e: ldc.i4.3 IL_004f: ldc.i4.1 IL_0050: stelem.i1 IL_0051: ldc.i4.s 100 IL_0053: ret IL_0054: ldloc.0 IL_0055: ldc.i4.5 IL_0056: ldc.i4.1 IL_0057: stelem.i1 IL_0058: ldc.i4.s 20 IL_005a: ret }"; string expectedPIDStaticConstructorIL = @"{ // Code size 33 (0x21) .maxstack 2 IL_0000: ldtoken Max Method Token Index IL_0005: ldc.i4.1 IL_0006: add IL_0007: newarr ""bool[]"" IL_000c: stsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0011: ldstr ##MVID## IL_0016: newobj ""System.Guid..ctor(string)"" IL_001b: stsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0020: ret }"; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Barney", expectedBarneyIL); verifier.VerifyIL(".cctor", expectedPIDStaticConstructorIL); verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(16, 9)); } [Fact] public void MethodsOfGenericTypesCoverage() { string source = @" using System; class MyBox<T> where T : class { readonly T _value; public MyBox(T value) { _value = value; } public T GetValue() { if (_value == null) { return null; } return _value; } } public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() { MyBox<object> x = new MyBox<object>(null); Console.WriteLine(x.GetValue() == null ? ""null"" : x.GetValue().ToString()); MyBox<string> s = new MyBox<string>(""Hello""); Console.WriteLine(s.GetValue() == null ? ""null"" : s.GetValue()); } } "; // All instrumentation points in method 2 are True because they are covered by at least one specialization. // // This test verifies that the payloads of methods of generic types are in terms of method definitions and // not method references -- the indices for the methods would be different for references. string expectedOutput = @"null Hello Flushing Method 1 File 1 True True Method 2 File 1 True True True True Method 3 File 1 True True True Method 4 File 1 True True True True True Method 7 File 1 True True False True True True True True True True True True True True True True "; string expectedReleaseGetValueIL = @"{ // Code size 98 (0x62) .maxstack 5 .locals init (bool[] V_0, T V_1) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""T MyBox<T>.GetValue()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""T MyBox<T>.GetValue()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""T MyBox<T>.GetValue()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.4 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld ""T MyBox<T>._value"" IL_0042: box ""T"" IL_0047: brtrue.s IL_0057 IL_0049: ldloc.0 IL_004a: ldc.i4.1 IL_004b: ldc.i4.1 IL_004c: stelem.i1 IL_004d: ldloca.s V_1 IL_004f: initobj ""T"" IL_0055: ldloc.1 IL_0056: ret IL_0057: ldloc.0 IL_0058: ldc.i4.3 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldarg.0 IL_005c: ldfld ""T MyBox<T>._value"" IL_0061: ret }"; string expectedDebugGetValueIL = @"{ // Code size 110 (0x6e) .maxstack 5 .locals init (bool[] V_0, bool V_1, T V_2, T V_3) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""T MyBox<T>.GetValue()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""T MyBox<T>.GetValue()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""T MyBox<T>.GetValue()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.4 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld ""T MyBox<T>._value"" IL_0042: box ""T"" IL_0047: ldnull IL_0048: ceq IL_004a: stloc.1 IL_004b: ldloc.1 IL_004c: brfalse.s IL_005f IL_004e: nop IL_004f: ldloc.0 IL_0050: ldc.i4.1 IL_0051: ldc.i4.1 IL_0052: stelem.i1 IL_0053: ldloca.s V_2 IL_0055: initobj ""T"" IL_005b: ldloc.2 IL_005c: stloc.3 IL_005d: br.s IL_006c IL_005f: ldloc.0 IL_0060: ldc.i4.3 IL_0061: ldc.i4.1 IL_0062: stelem.i1 IL_0063: ldarg.0 IL_0064: ldfld ""T MyBox<T>._value"" IL_0069: stloc.3 IL_006a: br.s IL_006c IL_006c: ldloc.3 IL_006d: ret }"; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyIL("MyBox<T>.GetValue", expectedReleaseGetValueIL); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe); verifier.VerifyIL("MyBox<T>.GetValue", expectedDebugGetValueIL); verifier.VerifyDiagnostics(); } [Fact] public void NonStaticImplicitBlockMethodsCoverage() { string source = @" using System; public class Program { public int Prop { get; } public int Prop2 { get; } = 25; public int Prop3 { get; set; } // Methods 3 and 4 public Program() // Method 5 { Prop = 12; Prop3 = 12; Prop2 = Prop3; } public static void Main(string[] args) // Method 6 { new Program(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(3, 1, "public int Prop3") .True("get"); checker.Method(4, 1, "public int Prop3") .True("set"); checker.Method(5, 1, "public Program()") .True("25") .True("Prop = 12;") .True("Prop3 = 12;") .True("Prop2 = Prop3;"); checker.Method(6, 1, "public static void Main") .True("new Program();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(8, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); } [Fact] public void ImplicitBlockMethodsCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { int x = Count; x += Prop; Prop = x; x += Prop2; Lambda(x, (y) => y + 1); } static int Function(int x) => x; static int Count => Function(44); static int Prop { get; set; } static int Prop2 { get; set; } = 12; static int Lambda(int x, Func<int, int> l) { return l(x); } // Method 11 is a synthesized static constructor. } "; // There is no entry for method '8' since it's a Prop2_set which is never called. string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True Method 6 File 1 True True Method 7 File 1 True True Method 9 File 1 True True Method 11 File 1 True Method 13 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void LocalFunctionWithLambdaCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { new D().M1(); } } public class D { public void M1() // Method 4 { L1(); void L1() { var f = new Func<int>( () => 1 ); var f1 = new Func<int>( () => 2 ); var f2 = new Func<int, int>( (x) => x + 3 ); var f3 = new Func<int, int>( x => x + 4 ); f(); f3(2); } } // Method 5 is the synthesized instance constructor for D. } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, "public static void Main") .True("TestMain();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(2, 1, "static void TestMain") .True("new D().M1();"); checker.Method(4, 1, "public void M1()") .True("L1();") .True("1") .True("var f = new Func<int>") .False("2") .True("var f1 = new Func<int>") .False("x + 3") .True("var f2 = new Func<int, int>") .True("x + 4") .True("var f3 = new Func<int, int>") .True("f();") .True("f3(2);"); checker.Method(5, 1, snippet: null, expectBodySpan: false); checker.Method(7, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); } [Fact] public void MultipleFilesCoverage() { string source = @" using System; public class Program { #line 10 ""File1.cs"" public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } #line 20 ""File2.cs"" static void TestMain() // Method 2 { Fred(); Program p = new Program(); return; } #line 30 ""File3.cs"" static void Fred() // Method 3 { return; } #line 40 ""File5.cs"" // The synthesized instance constructor is method 4 and // appears in the original source file, which gets file index 4. } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 2 True True True True Method 3 File 3 True True Method 4 File 4 Method 6 File 5 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void MultipleDeclarationsCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { int x; int a, b; DoubleDeclaration(5); DoubleForDeclaration(5); } static int DoubleDeclaration(int x) // Method 3 { int c = x; int a, b; int f; a = b = f = c; int d = a, e = b; return d + e + f; } static int DoubleForDeclaration(int x) // Method 4 { for(int a = x, b = x; a + b < 10; a++) { Console.WriteLine(""Cannot get here.""); x++; } return x; } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True True True True True Method 4 File 1 True True True False False False True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(14, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(15, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(15, 16)); } [Fact] public void UsingAndFixedCoverage() { string source = @" using System; using System.IO; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { using (var memoryStream = new MemoryStream()) { ; } using (MemoryStream s1 = new MemoryStream(), s2 = new MemoryStream()) { ; } var otherStream = new MemoryStream(); using (otherStream) { ; } unsafe { double[] a = { 1, 2, 3 }; fixed(double* p = a) { ; } fixed(double* q = a, r = a) { ; } } } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True True True True True True True True True Method 5 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails); verifier.VerifyDiagnostics(); } [Fact] public void ManyStatementsCoverage() // Method 3 { string source = @" using System; public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() { VariousStatements(2); Empty(); } static void VariousStatements(int z) { int x = z + 10; switch (z) { case 1: break; case 2: break; case 3: break; default: break; } if (x > 10) { x++; } else { x--; } for (int y = 0; y < 50; y++) { if (y < 30) { x++; continue; } else break; } int[] a = new int[] { 1, 2, 3, 4 }; foreach (int i in a) { x++; } while (x < 100) { x++; } try { x++; if (x > 10) { throw new System.Exception(); } x++; } catch (System.Exception) { x++; } finally { x++; } lock (new object()) { ; } Console.WriteLine(x); try { using ((System.IDisposable)new object()) { ; } } catch (System.Exception) { } // Include an infinite loop to make sure that a compiler optimization doesn't eliminate the instrumentation. while (true) { return; } } static void Empty() // Method 4 { } } "; string expectedOutput = @"103 Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True False True False False True True False True True True True True True True True True True True True True True True False True True True True True False True True True Method 4 File 1 True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void PatternsCoverage() { string source = @" using System; public class C { public static void Main() { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { Student s = new Student(); s.Name = ""Bozo""; s.GPA = s.Name switch { _ => 2.3 }; // switch expression is not instrumented Operate(s); } static string Operate(Person p) // Method 3 { switch (p) { case Student s when s.GPA > 3.5: return $""Student {s.Name} ({s.GPA:N1})""; case Student s: return $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return $""Teacher {t.Name} of {t.Subject}""; default: return $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } // Methods 5 and 7 are implicit constructors. "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True False True False False True Method 5 File 1 Method 7 File 1 Method 9 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Subject").WithArguments("Teacher.Subject", "null").WithLocation(37, 40)); } /// <see cref="DynamicAnalysisResourceTests.TestPatternSpans_WithSharedWhenExpression"/> /// for meaning of the spans [Fact] public void PatternsCoverage_WithSharedWhenExpression() { string source = @" using System; public class C { public static void Main() { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } public static void TestMain() { Method3(1, b1: false, b2: false); } static string Method3(int i, bool b1, bool b2) // Method 3 { switch (i) { case not 1 when b1: return ""b1""; case var _ when b2: return ""b2""; case 1: return ""1""; default: return ""default""; } } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True False True False False True False True Method 6 File 1 True True False True True True True True True True True True True True True True "; CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); } [Fact] public void DeconstructionStatementCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain2(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain2() // Method 2 { var (x, y) = new C(); } static void TestMain3() // Method 3 { var (x, y) = new C(); } public C() // Method 4 { } public void Deconstruct(out int x, out int y) // Method 5 { x = 1; y = 1 switch { 1 => 2, 3 => 4, _ => 5 }; // switch expression is not instrumented } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 4 File 1 True Method 5 File 1 True True True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); } [Fact] public void DeconstructionForeachStatementCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain2(new C[] { new C() }); TestMain3(new C[] { }); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain2(C[] a) // Method 2 { foreach ( var (x, y) in a) ; } static void TestMain3(C[] a) // Method 3 { foreach ( var (x, y) in a) ; } public C() // Method 4 { } public void Deconstruct(out int x, out int y) // Method 5 { x = 1; y = 2; } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True True Method 2 File 1 True True True Method 3 File 1 True False False Method 4 File 1 True Method 5 File 1 True True True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); } [Fact] public void LambdaCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); // Method 2 } static void TestMain() { int y = 5; Func<int, int> tester = (x) => { while (x > 10) { return y; } return x; }; y = 75; if (tester(20) > 50) Console.WriteLine(""OK""); else Console.WriteLine(""Bad""); } } "; string expectedOutput = @"OK Flushing Method 1 File 1 True True True Method 2 File 1 True True True True False True True True False True Method 5 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void AsyncCoverage() { string source = @" using System; using System.Threading.Tasks; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { Console.WriteLine(Outer(""Goo"").Result); } async static Task<string> Outer(string s) // Method 3 { string s1 = await First(s); string s2 = await Second(s); return s1 + s2; } async static Task<string> First(string s) // Method 4 { string result = await Second(s) + ""Glue""; if (result.Length > 2) return result; else return ""Too short""; } async static Task<string> Second(string s) // Method 5 { string doubled = """"; if (s.Length > 2) doubled = s + s; else doubled = ""HuhHuh""; return await Task.Factory.StartNew(() => doubled); } } "; string expectedOutput = @"GooGooGlueGooGoo Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True True True True Method 4 File 1 True True True False True Method 5 File 1 True True True False True True True Method 8 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void IteratorCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { foreach (var i in Goo()) { Console.WriteLine(i); } foreach (var i in Goo()) { Console.WriteLine(i); } } public static System.Collections.Generic.IEnumerable<int> Goo() { for (int i = 0; i < 5; ++i) { yield return i; } } } "; string expectedOutput = @"0 1 2 3 4 0 1 2 3 4 Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True True True Method 6 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void TestFieldInitializerCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { C local = new C(); local = new C(1, s_z); } static int Init() => 33; // Method 3 C() // Method 4 { _z = 12; } static C() // Method 5 { s_z = 123; } int _x = Init(); int _y = Init() + 12; int _z; static int s_x = Init(); static int s_y = Init() + 153; static int s_z; C(int x) // Method 6 { _z = x; } C(int a, int b) // Method 7 { _z = a + b; } int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; string expectedOutput = @" Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 4 File 1 True True True True True Method 5 File 1 True True True True True Method 7 File 1 True True True True True Method 11 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void TestImplicitConstructorCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { C local = new C(); int x = local._x + local._y + C.s_x + C.s_y + C.s_z; } static int Init() => 33; // Method 3 // Method 6 is the implicit instance constructor. // Method 7 is the implicit shared constructor. int _x = Init(); int _y = Init() + 12; static int s_x = Init(); static int s_y = Init() + 153; static int s_z = 144; int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; string expectedOutput = @" Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 6 File 1 True True True Method 7 File 1 True True True True Method 9 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void TestImplicitConstructorsWithLambdasCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { int y = s_c._function(); D d = new D(); int z = d._c._function(); int zz = D.s_c._function(); int zzz = d._c1._function(); } public C(Func<int> f) // Method 3 { _function = f; } static C s_c = new C(() => 115); Func<int> _function; } partial class D { } partial class D { } partial class D { public C _c = new C(() => 120); public static C s_c = new C(() => 144); public C _c1 = new C(() => 130); public static C s_c1 = new C(() => 156); } partial class D { } partial struct E { } partial struct E { public static C s_c = new C(() => 1444); public static C s_c1 = new C(() => { return 1567; }); } // Method 4 is the synthesized static constructor for C. // Method 5 is the synthesized instance constructor for D. // Method 6 is the synthesized static constructor for D. "; string expectedOutput = @" Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True True True Method 6 File 1 True False True True Method 9 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void MissingMethodNeededForAnalysis() { string source = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class Exception { } public class ValueType { } public class Enum { } public struct Void { } public class Guid { } } public class Console { public static void WriteLine(string s) { } public static void WriteLine(int i) { } public static void WriteLine(bool b) { } } public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static int TestMain() { return 3; } } "; ImmutableArray<Diagnostic> diagnostics = CreateEmptyCompilation(source + InstrumentationHelperSource).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); foreach (Diagnostic diagnostic in diagnostics) { if (diagnostic.Code == (int)ErrorCode.ERR_MissingPredefinedMember && diagnostic.Arguments[0].Equals("System.Guid") && diagnostic.Arguments[1].Equals(".ctor")) { return; } } Assert.True(false); } [Fact] public void ExcludeFromCodeCoverageAttribute_Method() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] void M1() { Console.WriteLine(1); } void M2() { Console.WriteLine(1); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.M1"); AssertInstrumented(verifier, "C.M2"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Ctor() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { int a = 1; [ExcludeFromCodeCoverage] public C() { Console.WriteLine(3); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..ctor"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Cctor() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static int a = 1; [ExcludeFromCodeCoverage] static C() { Console.WriteLine(3); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..cctor"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InMethod() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] static void M1() { L1(); void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); } } static void M2() { L2(); void L2() { new Action(() => { Console.WriteLine(2); }).Invoke(); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.M1"); AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0"); AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1"); AssertInstrumented(verifier, "C.M2"); AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>g__L2|0"); // M2:L2 AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>b__1"); // M2:L2 lambda } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static void M1() { L1(); [ExcludeFromCodeCoverage] void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertInstrumented(verifier, "C.M1"); AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0()"); AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1()"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Multiple() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static void M1() { #pragma warning disable 8321 // Unreferenced local function void L1() { Console.WriteLine(1); } [ExcludeFromCodeCoverage] void L2() { Console.WriteLine(2); } void L3() { Console.WriteLine(3); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertInstrumented(verifier, "C.M1"); AssertInstrumented(verifier, "C.<M1>g__L1|0_0(ref C.<>c__DisplayClass0_0)"); AssertNotInstrumented(verifier, "C.<M1>g__L2|0_1()"); AssertInstrumented(verifier, "C.<M1>g__L3|0_2(ref C.<>c__DisplayClass0_0)"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Nested() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static void M1() { L1(); void L1() { new Action(() => { L2(); [ExcludeFromCodeCoverage] void L2() { new Action(() => { L3(); void L3() { Console.WriteLine(1); } }).Invoke(); } }).Invoke(); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertInstrumented(verifier, "C.M1"); AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>g__L1|0()"); AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>b__1()"); AssertNotInstrumented(verifier, "C.<M1>g__L2|0_2()"); AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_3"); AssertNotInstrumented(verifier, "C.<M1>g__L3|0_4()"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InInitializers() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { Action IF = new Action(() => { Console.WriteLine(1); }); Action IP { get; } = new Action(() => { Console.WriteLine(2); }); static Action SF = new Action(() => { Console.WriteLine(3); }); static Action SP { get; } = new Action(() => { Console.WriteLine(4); }); [ExcludeFromCodeCoverage] C() {} static C() {} } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..ctor"); AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_0"); AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_1"); AssertInstrumented(verifier, "C..cctor"); AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__0"); AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__1"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InAccessors() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] int P1 { get { L1(); void L1() { Console.WriteLine(1); } return 1; } set { L2(); void L2() { Console.WriteLine(2); } } } int P2 { get { L3(); void L3() { Console.WriteLine(3); } return 3; } set { L4(); void L4() { Console.WriteLine(4); } } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.P1.get"); AssertNotInstrumented(verifier, "C.P1.set"); AssertNotInstrumented(verifier, "C.<get_P1>g__L1|1_0"); AssertNotInstrumented(verifier, "C.<set_P1>g__L2|2_0"); AssertInstrumented(verifier, "C.P2.get"); AssertInstrumented(verifier, "C.P2.set"); AssertInstrumented(verifier, "C.<get_P2>g__L3|4_0"); AssertInstrumented(verifier, "C.<set_P2>g__L4|5_0"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LambdaAttributes() { string source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void M1() { Action a1 = static () => { Func<bool, int> f1 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; }; Func<bool, int> f2 = static (bool b) => { if (b) return 0; return 1; }; }; } static void M2() { Action a2 = [ExcludeFromCodeCoverage] static () => { Func<bool, int> f3 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; }; Func<bool, int> f4 = static (bool b) => { if (b) return 0; return 1; }; }; } }"; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview); AssertInstrumented(verifier, "Program.M1"); AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__0()"); AssertNotInstrumented(verifier, "Program.<>c.<M1>b__0_1(bool)"); AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__2(bool)"); AssertInstrumented(verifier, "Program.M2"); AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_0()"); AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_1(bool)"); AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_2(bool)"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Type() { string source = @" using System; using System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] class C { int x = 1; static C() { } void M1() { Console.WriteLine(1); } int P { get => 1; set { } } event Action E { add { } remove { } } } class D { int x = 1; static D() { } void M1() { Console.WriteLine(1); } int P { get => 1; set { } } event Action E { add { } remove { } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..ctor"); AssertNotInstrumented(verifier, "C..cctor"); AssertNotInstrumented(verifier, "C.M1"); AssertNotInstrumented(verifier, "C.P.get"); AssertNotInstrumented(verifier, "C.P.set"); AssertNotInstrumented(verifier, "C.E.add"); AssertNotInstrumented(verifier, "C.E.remove"); AssertInstrumented(verifier, "D..ctor"); AssertInstrumented(verifier, "D..cctor"); AssertInstrumented(verifier, "D.M1"); AssertInstrumented(verifier, "D.P.get"); AssertInstrumented(verifier, "D.P.set"); AssertInstrumented(verifier, "D.E.add"); AssertInstrumented(verifier, "D.E.remove"); } [Fact] public void ExcludeFromCodeCoverageAttribute_NestedType() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class A { class B1 { [ExcludeFromCodeCoverage] class C { void M1() { Console.WriteLine(1); } } void M2() { Console.WriteLine(2); } } [ExcludeFromCodeCoverage] partial class B2 { partial class C1 { void M3() { Console.WriteLine(3); } } class C2 { void M4() { Console.WriteLine(4); } } void M5() { Console.WriteLine(5); } } partial class B2 { [ExcludeFromCodeCoverage] partial class C1 { void M6() { Console.WriteLine(6); } } void M7() { Console.WriteLine(7); } } void M8() { Console.WriteLine(8); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "A.B1.C.M1"); AssertInstrumented(verifier, "A.B1.M2"); AssertNotInstrumented(verifier, "A.B2.C1.M3"); AssertNotInstrumented(verifier, "A.B2.C2.M4"); AssertNotInstrumented(verifier, "A.B2.C1.M6"); AssertNotInstrumented(verifier, "A.B2.M7"); AssertInstrumented(verifier, "A.M8"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Accessors() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] int P1 { get => 1; set {} } [ExcludeFromCodeCoverage] event Action E1 { add { } remove { } } int P2 { get => 1; set {} } event Action E2 { add { } remove { } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.P1.get"); AssertNotInstrumented(verifier, "C.P1.set"); AssertNotInstrumented(verifier, "C.E1.add"); AssertNotInstrumented(verifier, "C.E1.remove"); AssertInstrumented(verifier, "C.P2.get"); AssertInstrumented(verifier, "C.P2.set"); AssertInstrumented(verifier, "C.E2.add"); AssertInstrumented(verifier, "C.E2.remove"); } [CompilerTrait(CompilerFeature.InitOnlySetters)] [Fact] public void ExcludeFromCodeCoverageAttribute_Accessors_Init() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] int P1 { get => 1; init {} } int P2 { get => 1; init {} } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource + IsExternalInitTypeDefinition, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertNotInstrumented(verifier, "C.P1.get"); AssertNotInstrumented(verifier, "C.P1.init"); AssertInstrumented(verifier, "C.P2.get"); AssertInstrumented(verifier, "C.P2.init"); } [Fact] public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Good() { string source = @" using System; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class)] public sealed class ExcludeFromCodeCoverageAttribute : Attribute { public ExcludeFromCodeCoverageAttribute() {} } } [ExcludeFromCodeCoverage] class C { void M() {} } class D { void M() {} } "; var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); c.VerifyEmitDiagnostics(); AssertNotInstrumented(verifier, "C.M"); AssertInstrumented(verifier, "D.M"); } [Fact] public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad() { string source = @" using System; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class)] public sealed class ExcludeFromCodeCoverageAttribute : Attribute { public ExcludeFromCodeCoverageAttribute(int x) {} } } [ExcludeFromCodeCoverage(1)] class C { void M() {} } class D { void M() {} } "; var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); c.VerifyEmitDiagnostics(); AssertInstrumented(verifier, "C.M"); AssertInstrumented(verifier, "D.M"); } [Fact] public void TestPartialMethodsWithImplementation() { var source = @" using System; public partial class Class1<T> { partial void Method1<U>(int x); public void Method2(int x) { Console.WriteLine($""Method2: x = {x}""); Method1<T>(x); } } public partial class Class1<T> { partial void Method1<U>(int x) { Console.WriteLine($""Method1: x = {x}""); if (x > 0) { Console.WriteLine(""Method1: x > 0""); Method1<U>(0); } else if (x < 0) { Console.WriteLine(""Method1: x < 0""); } } } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); c.Method2(1); } } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, "partial void Method1<U>(int x)") .True(@"Console.WriteLine($""Method1: x = {x}"");") .True(@"Console.WriteLine(""Method1: x > 0"");") .True("Method1<U>(0);") .False(@"Console.WriteLine(""Method1: x < 0"");") .True("x < 0)") .True("x > 0)"); checker.Method(2, 1, "public void Method2(int x)") .True(@"Console.WriteLine($""Method2: x = {x}"");") .True("Method1<T>(x);"); checker.Method(3, 1, ".ctor()", expectBodySpan: false); checker.Method(4, 1, "public static void Main(string[] args)") .True("Test();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(5, 1, "static void Test()") .True(@"Console.WriteLine(""Test"");") .True("var c = new Class1<int>();") .True("c.Method2(1);"); checker.Method(8, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); var expectedOutput = @"Test Method2: x = 1 Method1: x = 1 Method1: x > 0 Method1: x = 0 " + checker.ExpectedOutput; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); } [Fact] public void TestPartialMethodsWithoutImplementation() { var source = @" using System; public partial class Class1<T> { partial void Method1<U>(int x); public void Method2(int x) { Console.WriteLine($""Method2: x = {x}""); Method1<T>(x); } } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); c.Method2(1); } } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, "public void Method2(int x)") .True(@"Console.WriteLine($""Method2: x = {x}"");"); checker.Method(2, 1, ".ctor()", expectBodySpan: false); checker.Method(3, 1, "public static void Main(string[] args)") .True("Test();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(4, 1, "static void Test()") .True(@"Console.WriteLine(""Test"");") .True("var c = new Class1<int>();") .True("c.Method2(1);"); checker.Method(7, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); var expectedOutput = @"Test Method2: x = 1 " + checker.ExpectedOutput; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); } [Fact] public void TestSynthesizedConstructorWithSpansInMultipleFilesCoverage() { var source1 = @" using System; public partial class Class1<T> { private int x = 1; } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); c.Method1(1); } } " + InstrumentationHelperSource; var source2 = @" public partial class Class1<T> { private int y = 2; } public partial class Class1<T> { private int z = 3; }"; var source3 = @" using System; public partial class Class1<T> { private Action<int> a = i => { Console.WriteLine(i); }; public void Method1(int i) { a(i); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } }"; var sources = new[] { (Name: "b.cs", Content: source1), (Name: "c.cs", Content: source2), (Name: "a.cs", Content: source3) }; var expectedOutput = @"Test 1 1 2 3 Flushing Method 1 File 1 True True True True True Method 2 File 1 File 2 File 3 True True True True True Method 3 File 2 True True True Method 4 File 2 True True True True Method 7 File 2 True True False True True True True True True True True True True True True True "; var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage() { var source1 = @" using System; public partial class Class1<T> { private static int x = 1; } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); Class1<int>.Method1(1); } } " + InstrumentationHelperSource; var source2 = @" public partial class Class1<T> { private static int y = 2; } public partial class Class1<T> { private static int z = 3; }"; var source3 = @" using System; public partial class Class1<T> { private static Action<int> a = i => { Console.WriteLine(i); }; public static void Method1(int i) { a(i); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } }"; var sources = new[] { (Name: "b.cs", Content: source1), (Name: "c.cs", Content: source2), (Name: "a.cs", Content: source3) }; var expectedOutput = @"Test 1 1 2 3 Flushing Method 1 File 1 True True True True True Method 2 File 2 Method 3 File 1 File 2 File 3 True True True True True Method 4 File 2 True True True Method 5 File 2 True True True True Method 8 File 2 True True False True True True True True True True True True True True True True "; var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void TestLineDirectiveCoverage() { var source = @" using System; public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { #line 300 ""File2.cs"" Console.WriteLine(""Start""); #line hidden Console.WriteLine(""Hidden""); #line default Console.WriteLine(""Visible""); #line 400 ""File3.cs"" Console.WriteLine(""End""); } } " + InstrumentationHelperSource; var expectedOutput = @"Start Hidden Visible End Flushing Method 1 File 1 True True True Method 2 File 1 File 2 File 3 True True True True True Method 5 File 3 True True False True True True True True True True True True True True True True "; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.TopLevelStatements)] public void TopLevelStatements_01() { var source = @" using System; Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); static void Test() { Console.WriteLine(""Test""); } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, snippet: "", expectBodySpan: false) .True("Test();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();") .True(@"Console.WriteLine(""Test"");"); checker.Method(5, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); var expectedOutput = @"Test " + checker.ExpectedOutput; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); } private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName) => AssertInstrumented(verifier, qualifiedMethodName, expected: false); private static void AssertInstrumented(CompilationVerifier verifier, string qualifiedMethodName, bool expected = true) { string il = verifier.VisualizeIL(qualifiedMethodName); // Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload, // lambdas a reference to payload bool array. bool instrumented = il.Contains("CreatePayload") || il.Contains("bool[]"); Assert.True(expected == instrumented, $"Method '{qualifiedMethodName}' should {(expected ? "be" : "not be")} instrumented. Actual IL:{Environment.NewLine}{il}"); } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, CSharpCompilationOptions options = null, CSharpParseOptions parseOptions = null, Verification verify = Verification.Passes) { return base.CompileAndVerify( source, expectedOutput: expectedOutput, options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true), parseOptions: parseOptions, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)), verify: verify); } private CompilationVerifier CompileAndVerify((string Path, string Content)[] sources, string expectedOutput = null, CSharpCompilationOptions options = null) { var trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var source in sources) { // The trees must be assigned unique file names in order for instrumentation to work correctly. trees.Add(Parse(source.Content, filename: source.Path)); } var compilation = CreateCompilation(trees.ToArray(), options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true)); trees.Free(); return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } } }
// 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Test.Utilities.CSharpInstrumentationChecker; namespace Microsoft.CodeAnalysis.CSharp.DynamicAnalysis.UnitTests { public class DynamicInstrumentationTests : CSharpTestBase { [Fact] public void HelpersInstrumentation() { string source = @" using System; public class Program { public static void Main(string[] args) { Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } } "; string expectedOutput = @"Flushing Method 1 File 1 True True Method 4 File 1 True True False True True True True True True True True True True True True True "; string expectedCreatePayloadForMethodsSpanningSingleFileIL = @"{ // Code size 21 (0x15) .maxstack 6 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldc.i4.1 IL_0003: newarr ""int"" IL_0008: dup IL_0009: ldc.i4.0 IL_000a: ldarg.2 IL_000b: stelem.i4 IL_000c: ldarg.3 IL_000d: ldarg.s V_4 IL_000f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)"" IL_0014: ret }"; string expectedCreatePayloadForMethodsSpanningMultipleFilesIL = @"{ // Code size 87 (0x57) .maxstack 3 IL_0000: ldsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid"" IL_0005: ldarg.0 IL_0006: call ""bool System.Guid.op_Inequality(System.Guid, System.Guid)"" IL_000b: brfalse.s IL_002b IL_000d: ldc.i4.s 100 IL_000f: newarr ""bool[]"" IL_0014: stsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0019: ldc.i4.s 100 IL_001b: newarr ""int[]"" IL_0020: stsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_0025: ldarg.0 IL_0026: stsfld ""System.Guid Microsoft.CodeAnalysis.Runtime.Instrumentation._mvid"" IL_002b: ldarg.3 IL_002c: ldarg.s V_4 IL_002e: newarr ""bool"" IL_0033: ldnull IL_0034: call ""bool[] System.Threading.Interlocked.CompareExchange<bool[]>(ref bool[], bool[], bool[])"" IL_0039: brtrue.s IL_004f IL_003b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0040: ldarg.1 IL_0041: ldarg.3 IL_0042: ldind.ref IL_0043: stelem.ref IL_0044: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_0049: ldarg.1 IL_004a: ldarg.2 IL_004b: stelem.ref IL_004c: ldarg.3 IL_004d: ldind.ref IL_004e: ret IL_004f: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0054: ldarg.1 IL_0055: ldelem.ref IL_0056: ret }"; string expectedFlushPayloadIL = @"{ // Code size 288 (0x120) .maxstack 5 .locals init (bool[] V_0, int V_1, //i bool[] V_2, //payload int V_3, //j int V_4) //j IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0035 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""void Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.s 16 IL_002f: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0034: stloc.0 IL_0035: ldloc.0 IL_0036: ldc.i4.0 IL_0037: ldc.i4.1 IL_0038: stelem.i1 IL_0039: ldloc.0 IL_003a: ldc.i4.1 IL_003b: ldc.i4.1 IL_003c: stelem.i1 IL_003d: ldstr ""Flushing"" IL_0042: call ""void System.Console.WriteLine(string)"" IL_0047: ldloc.0 IL_0048: ldc.i4.3 IL_0049: ldc.i4.1 IL_004a: stelem.i1 IL_004b: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0050: brtrue.s IL_0057 IL_0052: ldloc.0 IL_0053: ldc.i4.2 IL_0054: ldc.i4.1 IL_0055: stelem.i1 IL_0056: ret IL_0057: ldloc.0 IL_0058: ldc.i4.4 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldc.i4.0 IL_005c: stloc.1 IL_005d: br IL_0112 IL_0062: ldloc.0 IL_0063: ldc.i4.6 IL_0064: ldc.i4.1 IL_0065: stelem.i1 IL_0066: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_006b: ldloc.1 IL_006c: ldelem.ref IL_006d: stloc.2 IL_006e: ldloc.0 IL_006f: ldc.i4.s 15 IL_0071: ldc.i4.1 IL_0072: stelem.i1 IL_0073: ldloc.2 IL_0074: brfalse IL_010a IL_0079: ldloc.0 IL_007a: ldc.i4.7 IL_007b: ldc.i4.1 IL_007c: stelem.i1 IL_007d: ldstr ""Method "" IL_0082: ldloca.s V_1 IL_0084: call ""string int.ToString()"" IL_0089: call ""string string.Concat(string, string)"" IL_008e: call ""void System.Console.WriteLine(string)"" IL_0093: ldloc.0 IL_0094: ldc.i4.8 IL_0095: ldc.i4.1 IL_0096: stelem.i1 IL_0097: ldc.i4.0 IL_0098: stloc.3 IL_0099: br.s IL_00ca IL_009b: ldloc.0 IL_009c: ldc.i4.s 10 IL_009e: ldc.i4.1 IL_009f: stelem.i1 IL_00a0: ldstr ""File "" IL_00a5: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_00aa: ldloc.1 IL_00ab: ldelem.ref IL_00ac: ldloc.3 IL_00ad: ldelema ""int"" IL_00b2: call ""string int.ToString()"" IL_00b7: call ""string string.Concat(string, string)"" IL_00bc: call ""void System.Console.WriteLine(string)"" IL_00c1: ldloc.0 IL_00c2: ldc.i4.s 9 IL_00c4: ldc.i4.1 IL_00c5: stelem.i1 IL_00c6: ldloc.3 IL_00c7: ldc.i4.1 IL_00c8: add IL_00c9: stloc.3 IL_00ca: ldloc.3 IL_00cb: ldsfld ""int[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._fileIndices"" IL_00d0: ldloc.1 IL_00d1: ldelem.ref IL_00d2: ldlen IL_00d3: conv.i4 IL_00d4: blt.s IL_009b IL_00d6: ldloc.0 IL_00d7: ldc.i4.s 11 IL_00d9: ldc.i4.1 IL_00da: stelem.i1 IL_00db: ldc.i4.0 IL_00dc: stloc.s V_4 IL_00de: br.s IL_0103 IL_00e0: ldloc.0 IL_00e1: ldc.i4.s 13 IL_00e3: ldc.i4.1 IL_00e4: stelem.i1 IL_00e5: ldloc.2 IL_00e6: ldloc.s V_4 IL_00e8: ldelem.u1 IL_00e9: call ""void System.Console.WriteLine(bool)"" IL_00ee: ldloc.0 IL_00ef: ldc.i4.s 14 IL_00f1: ldc.i4.1 IL_00f2: stelem.i1 IL_00f3: ldloc.2 IL_00f4: ldloc.s V_4 IL_00f6: ldc.i4.0 IL_00f7: stelem.i1 IL_00f8: ldloc.0 IL_00f9: ldc.i4.s 12 IL_00fb: ldc.i4.1 IL_00fc: stelem.i1 IL_00fd: ldloc.s V_4 IL_00ff: ldc.i4.1 IL_0100: add IL_0101: stloc.s V_4 IL_0103: ldloc.s V_4 IL_0105: ldloc.2 IL_0106: ldlen IL_0107: conv.i4 IL_0108: blt.s IL_00e0 IL_010a: ldloc.0 IL_010b: ldc.i4.5 IL_010c: ldc.i4.1 IL_010d: stelem.i1 IL_010e: ldloc.1 IL_010f: ldc.i4.1 IL_0110: add IL_0111: stloc.1 IL_0112: ldloc.1 IL_0113: ldsfld ""bool[][] Microsoft.CodeAnalysis.Runtime.Instrumentation._payloads"" IL_0118: ldlen IL_0119: conv.i4 IL_011a: blt IL_0062 IL_011f: ret }"; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)", expectedCreatePayloadForMethodsSpanningSingleFileIL); verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int[], ref bool[], int)", expectedCreatePayloadForMethodsSpanningMultipleFilesIL); verifier.VerifyIL("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload", expectedFlushPayloadIL); verifier.VerifyDiagnostics(); } [Fact] public void GotoCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() { Console.WriteLine(""goo""); goto bar; Console.Write(""you won't see me""); bar: Console.WriteLine(""bar""); Fred(); return; } static void Wilma() { Betty(true); Barney(true); Barney(false); Betty(true); } static int Barney(bool b) { if (b) return 10; if (b) return 100; return 20; } static int Betty(bool b) { if (b) return 30; if (b) return 100; return 40; } static void Fred() { Wilma(); } } "; string expectedOutput = @"goo bar Flushing Method 1 File 1 True True True Method 2 File 1 True True True False True True True Method 3 File 1 True True True True True Method 4 File 1 True True True False True True Method 5 File 1 True True True False False False Method 6 File 1 True True Method 9 File 1 True True False True True True True True True True True True True True True True "; string expectedBarneyIL = @"{ // Code size 91 (0x5b) .maxstack 5 .locals init (bool[] V_0) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""int Program.Barney(bool)"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""int Program.Barney(bool)"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""int Program.Barney(bool)"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.6 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: brfalse.s IL_0046 IL_003f: ldloc.0 IL_0040: ldc.i4.1 IL_0041: ldc.i4.1 IL_0042: stelem.i1 IL_0043: ldc.i4.s 10 IL_0045: ret IL_0046: ldloc.0 IL_0047: ldc.i4.4 IL_0048: ldc.i4.1 IL_0049: stelem.i1 IL_004a: ldarg.0 IL_004b: brfalse.s IL_0054 IL_004d: ldloc.0 IL_004e: ldc.i4.3 IL_004f: ldc.i4.1 IL_0050: stelem.i1 IL_0051: ldc.i4.s 100 IL_0053: ret IL_0054: ldloc.0 IL_0055: ldc.i4.5 IL_0056: ldc.i4.1 IL_0057: stelem.i1 IL_0058: ldc.i4.s 20 IL_005a: ret }"; string expectedPIDStaticConstructorIL = @"{ // Code size 33 (0x21) .maxstack 2 IL_0000: ldtoken Max Method Token Index IL_0005: ldc.i4.1 IL_0006: add IL_0007: newarr ""bool[]"" IL_000c: stsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0011: ldstr ##MVID## IL_0016: newobj ""System.Guid..ctor(string)"" IL_001b: stsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0020: ret }"; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Barney", expectedBarneyIL); verifier.VerifyIL(".cctor", expectedPIDStaticConstructorIL); verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnreachableCode, "Console").WithLocation(16, 9)); } [Fact] public void MethodsOfGenericTypesCoverage() { string source = @" using System; class MyBox<T> where T : class { readonly T _value; public MyBox(T value) { _value = value; } public T GetValue() { if (_value == null) { return null; } return _value; } } public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() { MyBox<object> x = new MyBox<object>(null); Console.WriteLine(x.GetValue() == null ? ""null"" : x.GetValue().ToString()); MyBox<string> s = new MyBox<string>(""Hello""); Console.WriteLine(s.GetValue() == null ? ""null"" : s.GetValue()); } } "; // All instrumentation points in method 2 are True because they are covered by at least one specialization. // // This test verifies that the payloads of methods of generic types are in terms of method definitions and // not method references -- the indices for the methods would be different for references. string expectedOutput = @"null Hello Flushing Method 1 File 1 True True Method 2 File 1 True True True True Method 3 File 1 True True True Method 4 File 1 True True True True True Method 7 File 1 True True False True True True True True True True True True True True True True "; string expectedReleaseGetValueIL = @"{ // Code size 98 (0x62) .maxstack 5 .locals init (bool[] V_0, T V_1) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""T MyBox<T>.GetValue()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""T MyBox<T>.GetValue()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""T MyBox<T>.GetValue()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.4 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld ""T MyBox<T>._value"" IL_0042: box ""T"" IL_0047: brtrue.s IL_0057 IL_0049: ldloc.0 IL_004a: ldc.i4.1 IL_004b: ldc.i4.1 IL_004c: stelem.i1 IL_004d: ldloca.s V_1 IL_004f: initobj ""T"" IL_0055: ldloc.1 IL_0056: ret IL_0057: ldloc.0 IL_0058: ldc.i4.3 IL_0059: ldc.i4.1 IL_005a: stelem.i1 IL_005b: ldarg.0 IL_005c: ldfld ""T MyBox<T>._value"" IL_0061: ret }"; string expectedDebugGetValueIL = @"{ // Code size 110 (0x6e) .maxstack 5 .locals init (bool[] V_0, bool V_1, T V_2, T V_3) IL_0000: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0005: ldtoken ""T MyBox<T>.GetValue()"" IL_000a: ldelem.ref IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: brtrue.s IL_0034 IL_000f: ldsfld ""System.Guid <PrivateImplementationDetails>.MVID"" IL_0014: ldtoken ""T MyBox<T>.GetValue()"" IL_0019: ldtoken Source Document 0 IL_001e: ldsfld ""bool[][] <PrivateImplementationDetails>.PayloadRoot0"" IL_0023: ldtoken ""T MyBox<T>.GetValue()"" IL_0028: ldelema ""bool[]"" IL_002d: ldc.i4.4 IL_002e: call ""bool[] Microsoft.CodeAnalysis.Runtime.Instrumentation.CreatePayload(System.Guid, int, int, ref bool[], int)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: ldc.i4.0 IL_0036: ldc.i4.1 IL_0037: stelem.i1 IL_0038: ldloc.0 IL_0039: ldc.i4.2 IL_003a: ldc.i4.1 IL_003b: stelem.i1 IL_003c: ldarg.0 IL_003d: ldfld ""T MyBox<T>._value"" IL_0042: box ""T"" IL_0047: ldnull IL_0048: ceq IL_004a: stloc.1 IL_004b: ldloc.1 IL_004c: brfalse.s IL_005f IL_004e: nop IL_004f: ldloc.0 IL_0050: ldc.i4.1 IL_0051: ldc.i4.1 IL_0052: stelem.i1 IL_0053: ldloca.s V_2 IL_0055: initobj ""T"" IL_005b: ldloc.2 IL_005c: stloc.3 IL_005d: br.s IL_006c IL_005f: ldloc.0 IL_0060: ldc.i4.3 IL_0061: ldc.i4.1 IL_0062: stelem.i1 IL_0063: ldarg.0 IL_0064: ldfld ""T MyBox<T>._value"" IL_0069: stloc.3 IL_006a: br.s IL_006c IL_006c: ldloc.3 IL_006d: ret }"; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyIL("MyBox<T>.GetValue", expectedReleaseGetValueIL); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe); verifier.VerifyIL("MyBox<T>.GetValue", expectedDebugGetValueIL); verifier.VerifyDiagnostics(); } [Fact] public void NonStaticImplicitBlockMethodsCoverage() { string source = @" using System; public class Program { public int Prop { get; } public int Prop2 { get; } = 25; public int Prop3 { get; set; } // Methods 3 and 4 public Program() // Method 5 { Prop = 12; Prop3 = 12; Prop2 = Prop3; } public static void Main(string[] args) // Method 6 { new Program(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(3, 1, "public int Prop3") .True("get"); checker.Method(4, 1, "public int Prop3") .True("set"); checker.Method(5, 1, "public Program()") .True("25") .True("Prop = 12;") .True("Prop3 = 12;") .True("Prop2 = Prop3;"); checker.Method(6, 1, "public static void Main") .True("new Program();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(8, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); } [Fact] public void ImplicitBlockMethodsCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { int x = Count; x += Prop; Prop = x; x += Prop2; Lambda(x, (y) => y + 1); } static int Function(int x) => x; static int Count => Function(44); static int Prop { get; set; } static int Prop2 { get; set; } = 12; static int Lambda(int x, Func<int, int> l) { return l(x); } // Method 11 is a synthesized static constructor. } "; // There is no entry for method '8' since it's a Prop2_set which is never called. string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True Method 6 File 1 True True Method 7 File 1 True True Method 9 File 1 True True Method 11 File 1 True Method 13 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void LocalFunctionWithLambdaCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { new D().M1(); } } public class D { public void M1() // Method 4 { L1(); void L1() { var f = new Func<int>( () => 1 ); var f1 = new Func<int>( () => 2 ); var f2 = new Func<int, int>( (x) => x + 3 ); var f3 = new Func<int, int>( x => x + 4 ); f(); f3(2); } } // Method 5 is the synthesized instance constructor for D. } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, "public static void Main") .True("TestMain();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(2, 1, "static void TestMain") .True("new D().M1();"); checker.Method(4, 1, "public void M1()") .True("L1();") .True("1") .True("var f = new Func<int>") .False("2") .True("var f1 = new Func<int>") .False("x + 3") .True("var f2 = new Func<int, int>") .True("x + 4") .True("var f3 = new Func<int, int>") .True("f();") .True("f3(2);"); checker.Method(5, 1, snippet: null, expectBodySpan: false); checker.Method(7, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); CompilationVerifier verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); verifier = CompileAndVerify(source, expectedOutput: checker.ExpectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); checker.CompleteCheck(verifier.Compilation, source); } [Fact] public void MultipleFilesCoverage() { string source = @" using System; public class Program { #line 10 ""File1.cs"" public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } #line 20 ""File2.cs"" static void TestMain() // Method 2 { Fred(); Program p = new Program(); return; } #line 30 ""File3.cs"" static void Fred() // Method 3 { return; } #line 40 ""File5.cs"" // The synthesized instance constructor is method 4 and // appears in the original source file, which gets file index 4. } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 2 True True True True Method 3 File 3 True True Method 4 File 4 Method 6 File 5 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void MultipleDeclarationsCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { int x; int a, b; DoubleDeclaration(5); DoubleForDeclaration(5); } static int DoubleDeclaration(int x) // Method 3 { int c = x; int a, b; int f; a = b = f = c; int d = a, e = b; return d + e + f; } static int DoubleForDeclaration(int x) // Method 4 { for(int a = x, b = x; a + b < 10; a++) { Console.WriteLine(""Cannot get here.""); x++; } return x; } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True True True True True Method 4 File 1 True True True False False False True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_UnreferencedVar, "x").WithArguments("x").WithLocation(14, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(15, 13), Diagnostic(ErrorCode.WRN_UnreferencedVar, "b").WithArguments("b").WithLocation(15, 16)); } [Fact] public void UsingAndFixedCoverage() { string source = @" using System; using System.IO; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { using (var memoryStream = new MemoryStream()) { ; } using (MemoryStream s1 = new MemoryStream(), s2 = new MemoryStream()) { ; } var otherStream = new MemoryStream(); using (otherStream) { ; } unsafe { double[] a = { 1, 2, 3 }; fixed(double* p = a) { ; } fixed(double* q = a, r = a) { ; } } } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True True True True True True True True True True Method 5 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.UnsafeDebugExe, expectedOutput: expectedOutput, verify: Verification.Fails); verifier.VerifyDiagnostics(); } [Fact] public void ManyStatementsCoverage() // Method 3 { string source = @" using System; public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() { VariousStatements(2); Empty(); } static void VariousStatements(int z) { int x = z + 10; switch (z) { case 1: break; case 2: break; case 3: break; default: break; } if (x > 10) { x++; } else { x--; } for (int y = 0; y < 50; y++) { if (y < 30) { x++; continue; } else break; } int[] a = new int[] { 1, 2, 3, 4 }; foreach (int i in a) { x++; } while (x < 100) { x++; } try { x++; if (x > 10) { throw new System.Exception(); } x++; } catch (System.Exception) { x++; } finally { x++; } lock (new object()) { ; } Console.WriteLine(x); try { using ((System.IDisposable)new object()) { ; } } catch (System.Exception) { } // Include an infinite loop to make sure that a compiler optimization doesn't eliminate the instrumentation. while (true) { return; } } static void Empty() // Method 4 { } } "; string expectedOutput = @"103 Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True False True False False True True False True True True True True True True True True True True True True True True False True True True True True False True True True Method 4 File 1 True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void PatternsCoverage() { string source = @" using System; public class C { public static void Main() { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { Student s = new Student(); s.Name = ""Bozo""; s.GPA = s.Name switch { _ => 2.3 }; // switch expression is not instrumented Operate(s); } static string Operate(Person p) // Method 3 { switch (p) { case Student s when s.GPA > 3.5: return $""Student {s.Name} ({s.GPA:N1})""; case Student s: return $""Student {s.Name} ({s.GPA:N1})""; case Teacher t: return $""Teacher {t.Name} of {t.Subject}""; default: return $""Person {p.Name}""; } } } class Person { public string Name; } class Teacher : Person { public string Subject; } class Student : Person { public double GPA; } // Methods 5 and 7 are implicit constructors. "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True False True False False True Method 5 File 1 Method 7 File 1 Method 9 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Subject").WithArguments("Teacher.Subject", "null").WithLocation(37, 40)); } /// <see cref="DynamicAnalysisResourceTests.TestPatternSpans_WithSharedWhenExpression"/> /// for meaning of the spans [Fact] public void PatternsCoverage_WithSharedWhenExpression() { string source = @" using System; public class C { public static void Main() { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } public static void TestMain() { Method3(1, b1: false, b2: false); } static string Method3(int i, bool b1, bool b2) // Method 3 { switch (i) { case not 1 when b1: return ""b1""; case var _ when b2: return ""b2""; case 1: return ""1""; default: return ""default""; } } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True False True False False True False True Method 6 File 1 True True False True True True True True True True True True True True True True "; CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); } [Fact] public void DeconstructionStatementCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain2(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain2() // Method 2 { var (x, y) = new C(); } static void TestMain3() // Method 3 { var (x, y) = new C(); } public C() // Method 4 { } public void Deconstruct(out int x, out int y) // Method 5 { x = 1; y = 1 switch { 1 => 2, 3 => 4, _ => 5 }; // switch expression is not instrumented } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 4 File 1 True Method 5 File 1 True True True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); } [Fact] public void DeconstructionForeachStatementCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain2(new C[] { new C() }); TestMain3(new C[] { }); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain2(C[] a) // Method 2 { foreach ( var (x, y) in a) ; } static void TestMain3(C[] a) // Method 3 { foreach ( var (x, y) in a) ; } public C() // Method 4 { } public void Deconstruct(out int x, out int y) // Method 5 { x = 1; y = 2; } } "; string expectedOutput = @"Flushing Method 1 File 1 True True True True Method 2 File 1 True True True Method 3 File 1 True False False Method 4 File 1 True Method 5 File 1 True True True Method 7 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); } [Fact] public void LambdaCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); // Method 2 } static void TestMain() { int y = 5; Func<int, int> tester = (x) => { while (x > 10) { return y; } return x; }; y = 75; if (tester(20) > 50) Console.WriteLine(""OK""); else Console.WriteLine(""Bad""); } } "; string expectedOutput = @"OK Flushing Method 1 File 1 True True True Method 2 File 1 True True True True False True True True False True Method 5 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void AsyncCoverage() { string source = @" using System; using System.Threading.Tasks; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { Console.WriteLine(Outer(""Goo"").Result); } async static Task<string> Outer(string s) // Method 3 { string s1 = await First(s); string s2 = await Second(s); return s1 + s2; } async static Task<string> First(string s) // Method 4 { string result = await Second(s) + ""Glue""; if (result.Length > 2) return result; else return ""Too short""; } async static Task<string> Second(string s) // Method 5 { string doubled = """"; if (s.Length > 2) doubled = s + s; else doubled = ""HuhHuh""; return await Task.Factory.StartNew(() => doubled); } } "; string expectedOutput = @"GooGooGlueGooGoo Flushing Method 1 File 1 True True True Method 2 File 1 True True Method 3 File 1 True True True True Method 4 File 1 True True True False True Method 5 File 1 True True True False True True True Method 8 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void IteratorCoverage() { string source = @" using System; public class Program { public static void Main(string[] args) // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { foreach (var i in Goo()) { Console.WriteLine(i); } foreach (var i in Goo()) { Console.WriteLine(i); } } public static System.Collections.Generic.IEnumerable<int> Goo() { for (int i = 0; i < 5; ++i) { yield return i; } } } "; string expectedOutput = @"0 1 2 3 4 0 1 2 3 4 Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True Method 3 File 1 True True True True Method 6 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void TestFieldInitializerCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { C local = new C(); local = new C(1, s_z); } static int Init() => 33; // Method 3 C() // Method 4 { _z = 12; } static C() // Method 5 { s_z = 123; } int _x = Init(); int _y = Init() + 12; int _z; static int s_x = Init(); static int s_y = Init() + 153; static int s_z; C(int x) // Method 6 { _z = x; } C(int a, int b) // Method 7 { _z = a + b; } int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; string expectedOutput = @" Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 4 File 1 True True True True True Method 5 File 1 True True True True True Method 7 File 1 True True True True True Method 11 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void TestImplicitConstructorCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { C local = new C(); int x = local._x + local._y + C.s_x + C.s_y + C.s_z; } static int Init() => 33; // Method 3 // Method 6 is the implicit instance constructor. // Method 7 is the implicit shared constructor. int _x = Init(); int _y = Init() + 12; static int s_x = Init(); static int s_y = Init() + 153; static int s_z = 144; int Prop1 { get; } = 15; static int Prop2 { get; } = 255; } "; string expectedOutput = @" Flushing Method 1 File 1 True True True Method 2 File 1 True True True Method 3 File 1 True True Method 6 File 1 True True True Method 7 File 1 True True True True Method 9 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void TestImplicitConstructorsWithLambdasCoverage() { string source = @" using System; public class C { public static void Main() // Method 1 { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void TestMain() // Method 2 { int y = s_c._function(); D d = new D(); int z = d._c._function(); int zz = D.s_c._function(); int zzz = d._c1._function(); } public C(Func<int> f) // Method 3 { _function = f; } static C s_c = new C(() => 115); Func<int> _function; } partial class D { } partial class D { } partial class D { public C _c = new C(() => 120); public static C s_c = new C(() => 144); public C _c1 = new C(() => 130); public static C s_c1 = new C(() => 156); } partial class D { } partial struct E { } partial struct E { public static C s_c = new C(() => 1444); public static C s_c1 = new C(() => { return 1567; }); } // Method 4 is the synthesized static constructor for C. // Method 5 is the synthesized instance constructor for D. // Method 6 is the synthesized static constructor for D. "; string expectedOutput = @" Flushing Method 1 File 1 True True True Method 2 File 1 True True True True True True Method 3 File 1 True True Method 4 File 1 True True Method 5 File 1 True True True True Method 6 File 1 True False True True Method 9 File 1 True True False True True True True True True True True True True True True True "; CompilationVerifier verifier = CompileAndVerify(source + InstrumentationHelperSource, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); } [Fact] public void MissingMethodNeededForAnalysis() { string source = @" namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class Exception { } public class ValueType { } public class Enum { } public struct Void { } public class Guid { } } public class Console { public static void WriteLine(string s) { } public static void WriteLine(int i) { } public static void WriteLine(bool b) { } } public class Program { public static void Main(string[] args) { TestMain(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static int TestMain() { return 3; } } "; ImmutableArray<Diagnostic> diagnostics = CreateEmptyCompilation(source + InstrumentationHelperSource).GetEmitDiagnostics(EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); foreach (Diagnostic diagnostic in diagnostics) { if (diagnostic.Code == (int)ErrorCode.ERR_MissingPredefinedMember && diagnostic.Arguments[0].Equals("System.Guid") && diagnostic.Arguments[1].Equals(".ctor")) { return; } } Assert.True(false); } [Fact] public void ExcludeFromCodeCoverageAttribute_Method() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] void M1() { Console.WriteLine(1); } void M2() { Console.WriteLine(1); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.M1"); AssertInstrumented(verifier, "C.M2"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Ctor() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { int a = 1; [ExcludeFromCodeCoverage] public C() { Console.WriteLine(3); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..ctor"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Cctor() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static int a = 1; [ExcludeFromCodeCoverage] static C() { Console.WriteLine(3); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..cctor"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InMethod() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] static void M1() { L1(); void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); } } static void M2() { L2(); void L2() { new Action(() => { Console.WriteLine(2); }).Invoke(); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.M1"); AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0"); AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1"); AssertInstrumented(verifier, "C.M2"); AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>g__L2|0"); // M2:L2 AssertInstrumented(verifier, "C.<>c__DisplayClass1_0.<M2>b__1"); // M2:L2 lambda } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static void M1() { L1(); [ExcludeFromCodeCoverage] void L1() { new Action(() => { Console.WriteLine(1); }).Invoke(); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertInstrumented(verifier, "C.M1"); AssertNotInstrumented(verifier, "C.<M1>g__L1|0_0()"); AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_1()"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Multiple() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static void M1() { #pragma warning disable 8321 // Unreferenced local function void L1() { Console.WriteLine(1); } [ExcludeFromCodeCoverage] void L2() { Console.WriteLine(2); } void L3() { Console.WriteLine(3); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertInstrumented(verifier, "C.M1"); AssertInstrumented(verifier, "C.<M1>g__L1|0_0(ref C.<>c__DisplayClass0_0)"); AssertNotInstrumented(verifier, "C.<M1>g__L2|0_1()"); AssertInstrumented(verifier, "C.<M1>g__L3|0_2(ref C.<>c__DisplayClass0_0)"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionAttributes_Nested() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { static void M1() { L1(); void L1() { new Action(() => { L2(); [ExcludeFromCodeCoverage] void L2() { new Action(() => { L3(); void L3() { Console.WriteLine(1); } }).Invoke(); } }).Invoke(); } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertInstrumented(verifier, "C.M1"); AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>g__L1|0()"); AssertInstrumented(verifier, "C.<>c__DisplayClass0_0.<M1>b__1()"); AssertNotInstrumented(verifier, "C.<M1>g__L2|0_2()"); AssertNotInstrumented(verifier, "C.<>c.<M1>b__0_3"); AssertNotInstrumented(verifier, "C.<M1>g__L3|0_4()"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InInitializers() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { Action IF = new Action(() => { Console.WriteLine(1); }); Action IP { get; } = new Action(() => { Console.WriteLine(2); }); static Action SF = new Action(() => { Console.WriteLine(3); }); static Action SP { get; } = new Action(() => { Console.WriteLine(4); }); [ExcludeFromCodeCoverage] C() {} static C() {} } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..ctor"); AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_0"); AssertNotInstrumented(verifier, "C.<>c.<.ctor>b__8_1"); AssertInstrumented(verifier, "C..cctor"); AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__0"); AssertInstrumented(verifier, "C.<>c__DisplayClass9_0.<.cctor>b__1"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LocalFunctionsAndLambdas_InAccessors() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] int P1 { get { L1(); void L1() { Console.WriteLine(1); } return 1; } set { L2(); void L2() { Console.WriteLine(2); } } } int P2 { get { L3(); void L3() { Console.WriteLine(3); } return 3; } set { L4(); void L4() { Console.WriteLine(4); } } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.P1.get"); AssertNotInstrumented(verifier, "C.P1.set"); AssertNotInstrumented(verifier, "C.<get_P1>g__L1|1_0"); AssertNotInstrumented(verifier, "C.<set_P1>g__L2|2_0"); AssertInstrumented(verifier, "C.P2.get"); AssertInstrumented(verifier, "C.P2.set"); AssertInstrumented(verifier, "C.<get_P2>g__L3|4_0"); AssertInstrumented(verifier, "C.<set_P2>g__L4|5_0"); } [Fact] public void ExcludeFromCodeCoverageAttribute_LambdaAttributes() { string source = @"using System; using System.Diagnostics.CodeAnalysis; class Program { static void M1() { Action a1 = static () => { Func<bool, int> f1 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; }; Func<bool, int> f2 = static (bool b) => { if (b) return 0; return 1; }; }; } static void M2() { Action a2 = [ExcludeFromCodeCoverage] static () => { Func<bool, int> f3 = [ExcludeFromCodeCoverage] static (bool b) => { if (b) return 0; return 1; }; Func<bool, int> f4 = static (bool b) => { if (b) return 0; return 1; }; }; } }"; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll, parseOptions: TestOptions.RegularPreview); AssertInstrumented(verifier, "Program.M1"); AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__0()"); AssertNotInstrumented(verifier, "Program.<>c.<M1>b__0_1(bool)"); AssertInstrumented(verifier, "Program.<>c__DisplayClass0_0.<M1>b__2(bool)"); AssertInstrumented(verifier, "Program.M2"); AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_0()"); AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_1(bool)"); AssertNotInstrumented(verifier, "Program.<>c.<M2>b__1_2(bool)"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Type() { string source = @" using System; using System.Diagnostics.CodeAnalysis; [ExcludeFromCodeCoverage] class C { int x = 1; static C() { } void M1() { Console.WriteLine(1); } int P { get => 1; set { } } event Action E { add { } remove { } } } class D { int x = 1; static D() { } void M1() { Console.WriteLine(1); } int P { get => 1; set { } } event Action E { add { } remove { } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C..ctor"); AssertNotInstrumented(verifier, "C..cctor"); AssertNotInstrumented(verifier, "C.M1"); AssertNotInstrumented(verifier, "C.P.get"); AssertNotInstrumented(verifier, "C.P.set"); AssertNotInstrumented(verifier, "C.E.add"); AssertNotInstrumented(verifier, "C.E.remove"); AssertInstrumented(verifier, "D..ctor"); AssertInstrumented(verifier, "D..cctor"); AssertInstrumented(verifier, "D.M1"); AssertInstrumented(verifier, "D.P.get"); AssertInstrumented(verifier, "D.P.set"); AssertInstrumented(verifier, "D.E.add"); AssertInstrumented(verifier, "D.E.remove"); } [Fact] public void ExcludeFromCodeCoverageAttribute_NestedType() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class A { class B1 { [ExcludeFromCodeCoverage] class C { void M1() { Console.WriteLine(1); } } void M2() { Console.WriteLine(2); } } [ExcludeFromCodeCoverage] partial class B2 { partial class C1 { void M3() { Console.WriteLine(3); } } class C2 { void M4() { Console.WriteLine(4); } } void M5() { Console.WriteLine(5); } } partial class B2 { [ExcludeFromCodeCoverage] partial class C1 { void M6() { Console.WriteLine(6); } } void M7() { Console.WriteLine(7); } } void M8() { Console.WriteLine(8); } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "A.B1.C.M1"); AssertInstrumented(verifier, "A.B1.M2"); AssertNotInstrumented(verifier, "A.B2.C1.M3"); AssertNotInstrumented(verifier, "A.B2.C2.M4"); AssertNotInstrumented(verifier, "A.B2.C1.M6"); AssertNotInstrumented(verifier, "A.B2.M7"); AssertInstrumented(verifier, "A.M8"); } [Fact] public void ExcludeFromCodeCoverageAttribute_Accessors() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] int P1 { get => 1; set {} } [ExcludeFromCodeCoverage] event Action E1 { add { } remove { } } int P2 { get => 1; set {} } event Action E2 { add { } remove { } } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); AssertNotInstrumented(verifier, "C.P1.get"); AssertNotInstrumented(verifier, "C.P1.set"); AssertNotInstrumented(verifier, "C.E1.add"); AssertNotInstrumented(verifier, "C.E1.remove"); AssertInstrumented(verifier, "C.P2.get"); AssertInstrumented(verifier, "C.P2.set"); AssertInstrumented(verifier, "C.E2.add"); AssertInstrumented(verifier, "C.E2.remove"); } [CompilerTrait(CompilerFeature.InitOnlySetters)] [Fact] public void ExcludeFromCodeCoverageAttribute_Accessors_Init() { string source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [ExcludeFromCodeCoverage] int P1 { get => 1; init {} } int P2 { get => 1; init {} } } "; var verifier = CompileAndVerify(source + InstrumentationHelperSource + IsExternalInitTypeDefinition, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular9); AssertNotInstrumented(verifier, "C.P1.get"); AssertNotInstrumented(verifier, "C.P1.init"); AssertInstrumented(verifier, "C.P2.get"); AssertInstrumented(verifier, "C.P2.init"); } [Fact] public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Good() { string source = @" using System; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class)] public sealed class ExcludeFromCodeCoverageAttribute : Attribute { public ExcludeFromCodeCoverageAttribute() {} } } [ExcludeFromCodeCoverage] class C { void M() {} } class D { void M() {} } "; var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); c.VerifyEmitDiagnostics(); AssertNotInstrumented(verifier, "C.M"); AssertInstrumented(verifier, "D.M"); } [Fact] public void ExcludeFromCodeCoverageAttribute_CustomDefinition_Bad() { string source = @" using System; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Class)] public sealed class ExcludeFromCodeCoverageAttribute : Attribute { public ExcludeFromCodeCoverageAttribute(int x) {} } } [ExcludeFromCodeCoverage(1)] class C { void M() {} } class D { void M() {} } "; var c = CreateCompilationWithMscorlib40(source + InstrumentationHelperSource, options: TestOptions.ReleaseDll); c.VerifyDiagnostics(); var verifier = CompileAndVerify(c, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); c.VerifyEmitDiagnostics(); AssertInstrumented(verifier, "C.M"); AssertInstrumented(verifier, "D.M"); } [Fact] public void TestPartialMethodsWithImplementation() { var source = @" using System; public partial class Class1<T> { partial void Method1<U>(int x); public void Method2(int x) { Console.WriteLine($""Method2: x = {x}""); Method1<T>(x); } } public partial class Class1<T> { partial void Method1<U>(int x) { Console.WriteLine($""Method1: x = {x}""); if (x > 0) { Console.WriteLine(""Method1: x > 0""); Method1<U>(0); } else if (x < 0) { Console.WriteLine(""Method1: x < 0""); } } } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); c.Method2(1); } } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, "partial void Method1<U>(int x)") .True(@"Console.WriteLine($""Method1: x = {x}"");") .True(@"Console.WriteLine(""Method1: x > 0"");") .True("Method1<U>(0);") .False(@"Console.WriteLine(""Method1: x < 0"");") .True("x < 0)") .True("x > 0)"); checker.Method(2, 1, "public void Method2(int x)") .True(@"Console.WriteLine($""Method2: x = {x}"");") .True("Method1<T>(x);"); checker.Method(3, 1, ".ctor()", expectBodySpan: false); checker.Method(4, 1, "public static void Main(string[] args)") .True("Test();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(5, 1, "static void Test()") .True(@"Console.WriteLine(""Test"");") .True("var c = new Class1<int>();") .True("c.Method2(1);"); checker.Method(8, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); var expectedOutput = @"Test Method2: x = 1 Method1: x = 1 Method1: x > 0 Method1: x = 0 " + checker.ExpectedOutput; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); } [Fact] public void TestPartialMethodsWithoutImplementation() { var source = @" using System; public partial class Class1<T> { partial void Method1<U>(int x); public void Method2(int x) { Console.WriteLine($""Method2: x = {x}""); Method1<T>(x); } } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); c.Method2(1); } } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, "public void Method2(int x)") .True(@"Console.WriteLine($""Method2: x = {x}"");"); checker.Method(2, 1, ".ctor()", expectBodySpan: false); checker.Method(3, 1, "public static void Main(string[] args)") .True("Test();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();"); checker.Method(4, 1, "static void Test()") .True(@"Console.WriteLine(""Test"");") .True("var c = new Class1<int>();") .True("c.Method2(1);"); checker.Method(7, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); var expectedOutput = @"Test Method2: x = 1 " + checker.ExpectedOutput; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); } [Fact] public void TestSynthesizedConstructorWithSpansInMultipleFilesCoverage() { var source1 = @" using System; public partial class Class1<T> { private int x = 1; } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); c.Method1(1); } } " + InstrumentationHelperSource; var source2 = @" public partial class Class1<T> { private int y = 2; } public partial class Class1<T> { private int z = 3; }"; var source3 = @" using System; public partial class Class1<T> { private Action<int> a = i => { Console.WriteLine(i); }; public void Method1(int i) { a(i); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } }"; var sources = new[] { (Name: "b.cs", Content: source1), (Name: "c.cs", Content: source2), (Name: "a.cs", Content: source3) }; var expectedOutput = @"Test 1 1 2 3 Flushing Method 1 File 1 True True True True True Method 2 File 1 File 2 File 3 True True True True True Method 3 File 2 True True True Method 4 File 2 True True True True Method 7 File 2 True True False True True True True True True True True True True True True True "; var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void TestSynthesizedStaticConstructorWithSpansInMultipleFilesCoverage() { var source1 = @" using System; public partial class Class1<T> { private static int x = 1; } public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { Console.WriteLine(""Test""); var c = new Class1<int>(); Class1<int>.Method1(1); } } " + InstrumentationHelperSource; var source2 = @" public partial class Class1<T> { private static int y = 2; } public partial class Class1<T> { private static int z = 3; }"; var source3 = @" using System; public partial class Class1<T> { private static Action<int> a = i => { Console.WriteLine(i); }; public static void Method1(int i) { a(i); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(z); } }"; var sources = new[] { (Name: "b.cs", Content: source1), (Name: "c.cs", Content: source2), (Name: "a.cs", Content: source3) }; var expectedOutput = @"Test 1 1 2 3 Flushing Method 1 File 1 True True True True True Method 2 File 2 Method 3 File 1 File 2 File 3 True True True True True Method 4 File 2 True True True Method 5 File 2 True True True True Method 8 File 2 True True False True True True True True True True True True True True True True "; var verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(sources, expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] public void TestLineDirectiveCoverage() { var source = @" using System; public class Program { public static void Main(string[] args) { Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); } static void Test() { #line 300 ""File2.cs"" Console.WriteLine(""Start""); #line hidden Console.WriteLine(""Hidden""); #line default Console.WriteLine(""Visible""); #line 400 ""File3.cs"" Console.WriteLine(""End""); } } " + InstrumentationHelperSource; var expectedOutput = @"Start Hidden Visible End Flushing Method 1 File 1 True True True Method 2 File 1 File 2 File 3 True True True True True Method 5 File 3 True True False True True True True True True True True True True True True True "; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe); verifier.VerifyDiagnostics(); } [Fact] [CompilerTrait(CompilerFeature.TopLevelStatements)] public void TopLevelStatements_01() { var source = @" using System; Test(); Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload(); static void Test() { Console.WriteLine(""Test""); } " + InstrumentationHelperSource; var checker = new CSharpInstrumentationChecker(); checker.Method(1, 1, snippet: "", expectBodySpan: false) .True("Test();") .True("Microsoft.CodeAnalysis.Runtime.Instrumentation.FlushPayload();") .True(@"Console.WriteLine(""Test"");"); checker.Method(5, 1) .True() .False() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True() .True(); var expectedOutput = @"Test " + checker.ExpectedOutput; var verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular9); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); verifier = CompileAndVerify(source, expectedOutput, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); checker.CompleteCheck(verifier.Compilation, source); verifier.VerifyDiagnostics(); } private static void AssertNotInstrumented(CompilationVerifier verifier, string qualifiedMethodName) => AssertInstrumented(verifier, qualifiedMethodName, expected: false); private static void AssertInstrumented(CompilationVerifier verifier, string qualifiedMethodName, bool expected = true) { string il = verifier.VisualizeIL(qualifiedMethodName); // Tests using this helper are constructed such that instrumented methods contain a call to CreatePayload, // lambdas a reference to payload bool array. bool instrumented = il.Contains("CreatePayload") || il.Contains("bool[]"); Assert.True(expected == instrumented, $"Method '{qualifiedMethodName}' should {(expected ? "be" : "not be")} instrumented. Actual IL:{Environment.NewLine}{il}"); } private CompilationVerifier CompileAndVerify(string source, string expectedOutput = null, CSharpCompilationOptions options = null, CSharpParseOptions parseOptions = null, Verification verify = Verification.Passes) { return base.CompileAndVerify( source, expectedOutput: expectedOutput, options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true), parseOptions: parseOptions, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage)), verify: verify); } private CompilationVerifier CompileAndVerify((string Path, string Content)[] sources, string expectedOutput = null, CSharpCompilationOptions options = null) { var trees = ArrayBuilder<SyntaxTree>.GetInstance(); foreach (var source in sources) { // The trees must be assigned unique file names in order for instrumentation to work correctly. trees.Add(Parse(source.Content, filename: source.Path)); } var compilation = CreateCompilation(trees.ToArray(), options: (options ?? TestOptions.ReleaseExe).WithDeterministic(true)); trees.Free(); return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, emitOptions: EmitOptions.Default.WithInstrumentationKinds(ImmutableArray.Create(InstrumentationKind.TestCoverage))); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./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 is SymbolKind.Method or SymbolKind.Property or SymbolKind.Event or 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 is SymbolKind.Property or SymbolKind.Event or 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 is SymbolKind.Method or SymbolKind.Property or SymbolKind.Event or 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 is SymbolKind.Property or SymbolKind.Event or 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,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Symbols/Source/SynthesizedEntryPointSymbol.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.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents an interactive code entry point that is inserted into the compilation if there is not an existing one. ''' </summary> Friend MustInherit Class SynthesizedEntryPointSymbol Inherits SynthesizedMethodBase Friend Const MainName = "<Main>" Friend Const FactoryName = "<Factory>" Private ReadOnly _containingType As NamedTypeSymbol Private ReadOnly _returnType As TypeSymbol Friend Shared Function Create(initializerMethod As SynthesizedInteractiveInitializerMethod, diagnostics As BindingDiagnosticBag) As SynthesizedEntryPointSymbol Dim containingType = initializerMethod.ContainingType Dim compilation = ContainingType.DeclaringCompilation If compilation.IsSubmission Then Dim submissionArrayType = compilation.CreateArrayTypeSymbol(compilation.GetSpecialType(SpecialType.System_Object)) ReportUseSiteInfo(submissionArrayType, diagnostics) Return New SubmissionEntryPoint(containingType, initializerMethod.ReturnType, submissionArrayType) Else Dim taskType = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task) Debug.Assert(taskType.IsErrorType() OrElse initializerMethod.ReturnType.IsOrDerivedFrom(taskType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) ReportUseSiteInfo(taskType, diagnostics) Dim getAwaiterMethod = If(taskType.IsErrorType(), Nothing, GetRequiredMethod(taskType, WellKnownMemberNames.GetAwaiter, diagnostics)) Dim getResultMethod = If(getAwaiterMethod Is Nothing, Nothing, GetRequiredMethod(getAwaiterMethod.ReturnType, WellKnownMemberNames.GetResult, diagnostics)) Return New ScriptEntryPoint( containingType, compilation.GetSpecialType(SpecialType.System_Void), getAwaiterMethod, getResultMethod) End If End Function Private Sub New(containingType As NamedTypeSymbol, returnType As TypeSymbol) MyBase.New(containingType) Debug.Assert(containingType IsNot Nothing) Debug.Assert(returnType IsNot Nothing) _containingType = containingType _returnType = returnType End Sub Friend MustOverride Function CreateBody() As BoundBlock Public MustOverride Overrides ReadOnly Property Name As String Friend Overrides ReadOnly Property HasSpecialName 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 Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False 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 ' the method is Shared Return False End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Private End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey Return LexicalSortKey.NotInSource End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType 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 TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Private Function GetSyntax() As VisualBasicSyntaxNode Return VisualBasicSyntaxTree.Dummy.GetRoot() End Function Private Shared Sub ReportUseSiteInfo(symbol As Symbol, diagnostics As BindingDiagnosticBag) diagnostics.Add(symbol.GetUseSiteInfo(), NoLocation.Singleton) End Sub Private Shared Function GetRequiredMethod(type As TypeSymbol, methodName As String, diagnostics As BindingDiagnosticBag) As MethodSymbol Dim method = TryCast(type.GetMembers(methodName).SingleOrDefault(), MethodSymbol) If method Is Nothing Then diagnostics.Add( ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper, type.MetadataName & "." & methodName), NoLocation.Singleton) End If Return method End Function Private Shared Function CreateParameterlessCall(syntax As VisualBasicSyntaxNode, receiver As BoundExpression, method As MethodSymbol) As BoundCall Return New BoundCall( syntax, method, methodGroupOpt:=Nothing, receiverOpt:=receiver.MakeRValue(), arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, suppressObjectClone:=False, type:=method.ReturnType).MakeCompilerGenerated() End Function Private NotInheritable Class ScriptEntryPoint Inherits SynthesizedEntryPointSymbol Private ReadOnly _getAwaiterMethod As MethodSymbol Private ReadOnly _getResultMethod As MethodSymbol Friend Sub New(containingType As NamedTypeSymbol, returnType As TypeSymbol, getAwaiterMethod As MethodSymbol, getResultMethod As MethodSymbol) MyBase.New(containingType, returnType) Debug.Assert(containingType.IsScriptClass) Debug.Assert(returnType.SpecialType = SpecialType.System_Void) _getAwaiterMethod = getAwaiterMethod _getResultMethod = getResultMethod End Sub Public Overrides ReadOnly Property Name As String Get Return MainName End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return ImmutableArray(Of ParameterSymbol).Empty End Get End Property ' Private Shared Sub <Main>() ' Dim script As New Script() ' script.<Initialize>().GetAwaiter().GetResult() ' End Sub Friend Overrides Function CreateBody() As BoundBlock ' CreateBody should only be called if no errors. Debug.Assert(_getAwaiterMethod IsNot Nothing) Debug.Assert(_getResultMethod IsNot Nothing) Dim syntax = GetSyntax() Dim ctor = _containingType.GetScriptConstructor() Debug.Assert(ctor.ParameterCount = 0) Dim initializer = _containingType.GetScriptInitializer() Debug.Assert(initializer.ParameterCount = 0) Dim scriptLocal = New BoundLocal( syntax, New SynthesizedLocal(Me, _containingType, SynthesizedLocalKind.LoweringTemp), _containingType).MakeCompilerGenerated() ' Dim script As New Script() Dim scriptAssignment = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, scriptLocal, New BoundObjectCreationExpression( syntax, ctor, ImmutableArray(Of BoundExpression).Empty, initializerOpt:=Nothing, type:=_containingType).MakeCompilerGenerated(), suppressObjectClone:=False).MakeCompilerGenerated()).MakeCompilerGenerated() ' script.<Initialize>().GetAwaiter().GetResult() Dim scriptInitialize = New BoundExpressionStatement( syntax, CreateParameterlessCall( syntax, CreateParameterlessCall( syntax, CreateParameterlessCall( syntax, scriptLocal, initializer), _getAwaiterMethod), _getResultMethod)).MakeCompilerGenerated() ' Return Dim returnStatement = New BoundReturnStatement( syntax, Nothing, Nothing, Nothing).MakeCompilerGenerated() Return New BoundBlock( syntax, Nothing, ImmutableArray.Create(Of LocalSymbol)(scriptLocal.LocalSymbol), ImmutableArray.Create(Of BoundStatement)(scriptAssignment, scriptInitialize, returnStatement)).MakeCompilerGenerated() End Function End Class Private NotInheritable Class SubmissionEntryPoint Inherits SynthesizedEntryPointSymbol Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Friend Sub New(containingType As NamedTypeSymbol, returnType As TypeSymbol, submissionArrayType As TypeSymbol) MyBase.New(containingType, returnType) Debug.Assert(containingType.IsSubmissionClass) _parameters = ImmutableArray.Create(Of ParameterSymbol)(New SynthesizedParameterSymbol(Me, submissionArrayType, ordinal:=0, isByRef:=False, name:="submissionArray")) End Sub Public Overrides ReadOnly Property Name As String Get Return FactoryName End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property ' Private Shared Function <Factory>(submissionArray As Object()) As T ' Dim submission As New Submission#N(submissionArray) ' Return submission.<Initialize>() ' End Function Friend Overrides Function CreateBody() As BoundBlock Dim syntax = GetSyntax() Dim ctor = _containingType.GetScriptConstructor() Debug.Assert(ctor.ParameterCount = 1) Dim initializer = _containingType.GetScriptInitializer() Debug.Assert(initializer.ParameterCount = 0) Dim parameter = _parameters(0) Dim submissionArrayParameter = New BoundParameter( syntax, parameter, isLValue:=False, type:=parameter.Type).MakeCompilerGenerated() Dim submissionLocal = New BoundLocal( syntax, New SynthesizedLocal(Me, _containingType, SynthesizedLocalKind.LoweringTemp), _containingType).MakeCompilerGenerated() ' Dim submission As New Submission#N(submissionArray) Dim submissionAssignment = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, submissionLocal, New BoundObjectCreationExpression( syntax, ctor, ImmutableArray.Create(Of BoundExpression)(submissionArrayParameter), initializerOpt:=Nothing, type:=_containingType).MakeCompilerGenerated(), suppressObjectClone:=False).MakeCompilerGenerated()).MakeCompilerGenerated() ' Return submission.<Initialize>() Dim returnStatement = New BoundReturnStatement( syntax, CreateParameterlessCall( syntax, submissionLocal, initializer).MakeRValue(), functionLocalOpt:=Nothing, exitLabelOpt:=Nothing).MakeCompilerGenerated() Return New BoundBlock( syntax, Nothing, ImmutableArray.Create(Of LocalSymbol)(submissionLocal.LocalSymbol), ImmutableArray.Create(Of BoundStatement)(submissionAssignment, returnStatement)).MakeCompilerGenerated() 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.Linq Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents an interactive code entry point that is inserted into the compilation if there is not an existing one. ''' </summary> Friend MustInherit Class SynthesizedEntryPointSymbol Inherits SynthesizedMethodBase Friend Const MainName = "<Main>" Friend Const FactoryName = "<Factory>" Private ReadOnly _containingType As NamedTypeSymbol Private ReadOnly _returnType As TypeSymbol Friend Shared Function Create(initializerMethod As SynthesizedInteractiveInitializerMethod, diagnostics As BindingDiagnosticBag) As SynthesizedEntryPointSymbol Dim containingType = initializerMethod.ContainingType Dim compilation = ContainingType.DeclaringCompilation If compilation.IsSubmission Then Dim submissionArrayType = compilation.CreateArrayTypeSymbol(compilation.GetSpecialType(SpecialType.System_Object)) ReportUseSiteInfo(submissionArrayType, diagnostics) Return New SubmissionEntryPoint(containingType, initializerMethod.ReturnType, submissionArrayType) Else Dim taskType = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task) Debug.Assert(taskType.IsErrorType() OrElse initializerMethod.ReturnType.IsOrDerivedFrom(taskType, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) ReportUseSiteInfo(taskType, diagnostics) Dim getAwaiterMethod = If(taskType.IsErrorType(), Nothing, GetRequiredMethod(taskType, WellKnownMemberNames.GetAwaiter, diagnostics)) Dim getResultMethod = If(getAwaiterMethod Is Nothing, Nothing, GetRequiredMethod(getAwaiterMethod.ReturnType, WellKnownMemberNames.GetResult, diagnostics)) Return New ScriptEntryPoint( containingType, compilation.GetSpecialType(SpecialType.System_Void), getAwaiterMethod, getResultMethod) End If End Function Private Sub New(containingType As NamedTypeSymbol, returnType As TypeSymbol) MyBase.New(containingType) Debug.Assert(containingType IsNot Nothing) Debug.Assert(returnType IsNot Nothing) _containingType = containingType _returnType = returnType End Sub Friend MustOverride Function CreateBody() As BoundBlock Public MustOverride Overrides ReadOnly Property Name As String Friend Overrides ReadOnly Property HasSpecialName 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 Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return Nothing End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False 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 ' the method is Shared Return False End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Private End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey Return LexicalSortKey.NotInSource End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray(Of Location).Empty End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType 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 TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.Ordinary End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Private Function GetSyntax() As VisualBasicSyntaxNode Return VisualBasicSyntaxTree.Dummy.GetRoot() End Function Private Shared Sub ReportUseSiteInfo(symbol As Symbol, diagnostics As BindingDiagnosticBag) diagnostics.Add(symbol.GetUseSiteInfo(), NoLocation.Singleton) End Sub Private Shared Function GetRequiredMethod(type As TypeSymbol, methodName As String, diagnostics As BindingDiagnosticBag) As MethodSymbol Dim method = TryCast(type.GetMembers(methodName).SingleOrDefault(), MethodSymbol) If method Is Nothing Then diagnostics.Add( ErrorFactory.ErrorInfo(ERRID.ERR_MissingRuntimeHelper, type.MetadataName & "." & methodName), NoLocation.Singleton) End If Return method End Function Private Shared Function CreateParameterlessCall(syntax As VisualBasicSyntaxNode, receiver As BoundExpression, method As MethodSymbol) As BoundCall Return New BoundCall( syntax, method, methodGroupOpt:=Nothing, receiverOpt:=receiver.MakeRValue(), arguments:=ImmutableArray(Of BoundExpression).Empty, constantValueOpt:=Nothing, suppressObjectClone:=False, type:=method.ReturnType).MakeCompilerGenerated() End Function Private NotInheritable Class ScriptEntryPoint Inherits SynthesizedEntryPointSymbol Private ReadOnly _getAwaiterMethod As MethodSymbol Private ReadOnly _getResultMethod As MethodSymbol Friend Sub New(containingType As NamedTypeSymbol, returnType As TypeSymbol, getAwaiterMethod As MethodSymbol, getResultMethod As MethodSymbol) MyBase.New(containingType, returnType) Debug.Assert(containingType.IsScriptClass) Debug.Assert(returnType.SpecialType = SpecialType.System_Void) _getAwaiterMethod = getAwaiterMethod _getResultMethod = getResultMethod End Sub Public Overrides ReadOnly Property Name As String Get Return MainName End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return ImmutableArray(Of ParameterSymbol).Empty End Get End Property ' Private Shared Sub <Main>() ' Dim script As New Script() ' script.<Initialize>().GetAwaiter().GetResult() ' End Sub Friend Overrides Function CreateBody() As BoundBlock ' CreateBody should only be called if no errors. Debug.Assert(_getAwaiterMethod IsNot Nothing) Debug.Assert(_getResultMethod IsNot Nothing) Dim syntax = GetSyntax() Dim ctor = _containingType.GetScriptConstructor() Debug.Assert(ctor.ParameterCount = 0) Dim initializer = _containingType.GetScriptInitializer() Debug.Assert(initializer.ParameterCount = 0) Dim scriptLocal = New BoundLocal( syntax, New SynthesizedLocal(Me, _containingType, SynthesizedLocalKind.LoweringTemp), _containingType).MakeCompilerGenerated() ' Dim script As New Script() Dim scriptAssignment = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, scriptLocal, New BoundObjectCreationExpression( syntax, ctor, ImmutableArray(Of BoundExpression).Empty, initializerOpt:=Nothing, type:=_containingType).MakeCompilerGenerated(), suppressObjectClone:=False).MakeCompilerGenerated()).MakeCompilerGenerated() ' script.<Initialize>().GetAwaiter().GetResult() Dim scriptInitialize = New BoundExpressionStatement( syntax, CreateParameterlessCall( syntax, CreateParameterlessCall( syntax, CreateParameterlessCall( syntax, scriptLocal, initializer), _getAwaiterMethod), _getResultMethod)).MakeCompilerGenerated() ' Return Dim returnStatement = New BoundReturnStatement( syntax, Nothing, Nothing, Nothing).MakeCompilerGenerated() Return New BoundBlock( syntax, Nothing, ImmutableArray.Create(Of LocalSymbol)(scriptLocal.LocalSymbol), ImmutableArray.Create(Of BoundStatement)(scriptAssignment, scriptInitialize, returnStatement)).MakeCompilerGenerated() End Function End Class Private NotInheritable Class SubmissionEntryPoint Inherits SynthesizedEntryPointSymbol Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) Friend Sub New(containingType As NamedTypeSymbol, returnType As TypeSymbol, submissionArrayType As TypeSymbol) MyBase.New(containingType, returnType) Debug.Assert(containingType.IsSubmissionClass) _parameters = ImmutableArray.Create(Of ParameterSymbol)(New SynthesizedParameterSymbol(Me, submissionArrayType, ordinal:=0, isByRef:=False, name:="submissionArray")) End Sub Public Overrides ReadOnly Property Name As String Get Return FactoryName End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property ' Private Shared Function <Factory>(submissionArray As Object()) As T ' Dim submission As New Submission#N(submissionArray) ' Return submission.<Initialize>() ' End Function Friend Overrides Function CreateBody() As BoundBlock Dim syntax = GetSyntax() Dim ctor = _containingType.GetScriptConstructor() Debug.Assert(ctor.ParameterCount = 1) Dim initializer = _containingType.GetScriptInitializer() Debug.Assert(initializer.ParameterCount = 0) Dim parameter = _parameters(0) Dim submissionArrayParameter = New BoundParameter( syntax, parameter, isLValue:=False, type:=parameter.Type).MakeCompilerGenerated() Dim submissionLocal = New BoundLocal( syntax, New SynthesizedLocal(Me, _containingType, SynthesizedLocalKind.LoweringTemp), _containingType).MakeCompilerGenerated() ' Dim submission As New Submission#N(submissionArray) Dim submissionAssignment = New BoundExpressionStatement( syntax, New BoundAssignmentOperator( syntax, submissionLocal, New BoundObjectCreationExpression( syntax, ctor, ImmutableArray.Create(Of BoundExpression)(submissionArrayParameter), initializerOpt:=Nothing, type:=_containingType).MakeCompilerGenerated(), suppressObjectClone:=False).MakeCompilerGenerated()).MakeCompilerGenerated() ' Return submission.<Initialize>() Dim returnStatement = New BoundReturnStatement( syntax, CreateParameterlessCall( syntax, submissionLocal, initializer).MakeRValue(), functionLocalOpt:=Nothing, exitLabelOpt:=Nothing).MakeCompilerGenerated() Return New BoundBlock( syntax, Nothing, ImmutableArray.Create(Of LocalSymbol)(submissionLocal.LocalSymbol), ImmutableArray.Create(Of BoundStatement)(submissionAssignment, returnStatement)).MakeCompilerGenerated() End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/CodeAnalysisTest/CryptoBlobParserTests.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 Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Security.Cryptography; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CryptoBlobParserTests : TestBase { private const int HEADER_LEN = 20; private const int MOD_LEN = 128; private const int HALF_LEN = 64; [Fact] public void GetPrivateKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Debug.Assert(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPrivateKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Assert.True(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPublicKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey, pubKey); } [Fact] public void GetPublicKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey2, pubKey); } [Fact] public void SnPublicKeyIsReturnedAsIs() { var key = ImmutableArray.Create(TestResources.General.snPublicKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(key, pubKey); } [Fact] public void GetSnPublicKeyFromPublicKeyBlob() { // A Strongname public key blob includes an additional header on top // of the wincrypt.h public key blob var snBlob = TestResources.General.snPublicKey; var buf = new byte[snBlob.Length - CryptoBlobParser.s_publicKeyHeaderSize]; Array.Copy(snBlob, CryptoBlobParser.s_publicKeyHeaderSize, buf, 0, buf.Length); var publicKeyBlob = ImmutableArray.Create(buf); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(publicKeyBlob, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(snBlob, pubKey); } [Fact] public void TryGetPublicKeyFailsForInvalidKeyBlobs() { var invalidKeyBlobs = new[] { string.Empty, new string('0', 160 * 2), // 160 * 2 - the length of a public key, 2 - 2 chars per byte new string('0', 596 * 2), // 596 * 2 - the length of a key pair, 2 - 2 chars per byte "0702000000240000DEADBEEF" + new string('0', 584 * 2), // private key blob without magic private key "0602000000240000DEADBEEF" + new string('0', 136 * 2), // public key blob without magic public key }; Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[0]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[1]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[2]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[3]), out _, out _)); } private static ImmutableArray<byte> HexToBin(string input) { Assert.True(input != null && (input.Length & 1) == 0, "invalid input string."); var result = new byte[input.Length >> 1]; for (var i = 0; i < result.Length; i++) { result[i] = byte.Parse(input.Substring(i << 1, 2), NumberStyles.HexNumber); } return ImmutableArray.Create(result); } } }
// 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 Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Security.Cryptography; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class CryptoBlobParserTests : TestBase { private const int HEADER_LEN = 20; private const int MOD_LEN = 128; private const int HALF_LEN = 64; [Fact] public void GetPrivateKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Debug.Assert(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPrivateKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); RSAParameters? privateKeyOpt; Assert.True(CryptoBlobParser.TryParseKey(key, out _, out privateKeyOpt)); Assert.True(privateKeyOpt.HasValue); var privKey = privateKeyOpt.Value; AssertEx.Equal(privKey.Exponent, new byte[] { 0x01, 0x00, 0x01 }); var expectedModulus = key.Skip(HEADER_LEN).Take(MOD_LEN).ToArray(); Array.Reverse(expectedModulus); AssertEx.Equal(expectedModulus, privKey.Modulus); var expectedP = key.Skip(HEADER_LEN + MOD_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedP); AssertEx.Equal(expectedP, privKey.P); var expectedQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN).Take(HALF_LEN).ToArray(); Array.Reverse(expectedQ); AssertEx.Equal(expectedQ, privKey.Q); var expectedDP = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 2).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDP); AssertEx.Equal(expectedDP, privKey.DP); var expectedDQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 3).Take(HALF_LEN).ToArray(); Array.Reverse(expectedDQ); AssertEx.Equal(expectedDQ, privKey.DQ); var expectedInverseQ = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 4).Take(HALF_LEN).ToArray(); Array.Reverse(expectedInverseQ); AssertEx.Equal(expectedInverseQ, privKey.InverseQ); var expectedD = key.Skip(HEADER_LEN + MOD_LEN + HALF_LEN * 5).Take(MOD_LEN).ToArray(); Array.Reverse(expectedD); AssertEx.Equal(expectedD, privKey.D); Assert.True(key.Skip(HEADER_LEN + MOD_LEN * 2 + HALF_LEN * 5).ToArray().Length == 0); } [Fact] public void GetPublicKeyFromKeyPair() { var key = ImmutableArray.Create(TestResources.General.snKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey, pubKey); } [Fact] public void GetPublicKeyFromKeyPair2() { var key = ImmutableArray.Create(TestResources.General.snKey2); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(TestResources.General.snPublicKey2, pubKey); } [Fact] public void SnPublicKeyIsReturnedAsIs() { var key = ImmutableArray.Create(TestResources.General.snPublicKey); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(key, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(key, pubKey); } [Fact] public void GetSnPublicKeyFromPublicKeyBlob() { // A Strongname public key blob includes an additional header on top // of the wincrypt.h public key blob var snBlob = TestResources.General.snPublicKey; var buf = new byte[snBlob.Length - CryptoBlobParser.s_publicKeyHeaderSize]; Array.Copy(snBlob, CryptoBlobParser.s_publicKeyHeaderSize, buf, 0, buf.Length); var publicKeyBlob = ImmutableArray.Create(buf); ImmutableArray<byte> pubKey; Assert.True(CryptoBlobParser.TryParseKey(publicKeyBlob, out pubKey, out _)); Assert.True(CryptoBlobParser.IsValidPublicKey(pubKey)); AssertEx.Equal(snBlob, pubKey); } [Fact] public void TryGetPublicKeyFailsForInvalidKeyBlobs() { var invalidKeyBlobs = new[] { string.Empty, new string('0', 160 * 2), // 160 * 2 - the length of a public key, 2 - 2 chars per byte new string('0', 596 * 2), // 596 * 2 - the length of a key pair, 2 - 2 chars per byte "0702000000240000DEADBEEF" + new string('0', 584 * 2), // private key blob without magic private key "0602000000240000DEADBEEF" + new string('0', 136 * 2), // public key blob without magic public key }; Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[0]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[1]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[2]), out _, out _)); Assert.False(CryptoBlobParser.TryParseKey(HexToBin(invalidKeyBlobs[3]), out _, out _)); } private static ImmutableArray<byte> HexToBin(string input) { Assert.True(input != null && (input.Length & 1) == 0, "invalid input string."); var result = new byte[input.Length >> 1]; for (var i = 0; i < result.Length; i++) { result[i] = byte.Parse(input.Substring(i << 1, 2), NumberStyles.HexNumber); } return ImmutableArray.Create(result); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/CodeFixSuggestedAction.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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.UnifiedSuggestions.UnifiedSuggestedActions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { /// <summary> /// Represents light bulb menu item for code fixes. /// </summary> internal sealed class CodeFixSuggestedAction : SuggestedActionWithNestedFlavors, ICodeFixSuggestedAction, ITelemetryDiagnosticID<string> { public CodeFix CodeFix { get; } public CodeFixSuggestedAction( IThreadingContext threadingContext, SuggestedActionsSourceProvider sourceProvider, Workspace workspace, ITextBuffer subjectBuffer, CodeFix fix, object provider, CodeAction action, SuggestedActionSet fixAllFlavors) : base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, action, fixAllFlavors) { CodeFix = fix; } public string GetDiagnosticID() => CodeFix.PrimaryDiagnostic.GetTelemetryDiagnosticID(); protected override DiagnosticData GetDiagnostic() => CodeFix.GetPrimaryDiagnosticData(); } }
// 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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.UnifiedSuggestions.UnifiedSuggestedActions; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { /// <summary> /// Represents light bulb menu item for code fixes. /// </summary> internal sealed class CodeFixSuggestedAction : SuggestedActionWithNestedFlavors, ICodeFixSuggestedAction, ITelemetryDiagnosticID<string> { public CodeFix CodeFix { get; } public CodeFixSuggestedAction( IThreadingContext threadingContext, SuggestedActionsSourceProvider sourceProvider, Workspace workspace, ITextBuffer subjectBuffer, CodeFix fix, object provider, CodeAction action, SuggestedActionSet fixAllFlavors) : base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, action, fixAllFlavors) { CodeFix = fix; } public string GetDiagnosticID() => CodeFix.PrimaryDiagnostic.GetTelemetryDiagnosticID(); protected override DiagnosticData GetDiagnostic() => CodeFix.GetPrimaryDiagnosticData(); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/CodeAnalysisTest/VersionHelperTests.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.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class VersionHelperTests { [Fact] public void ParseGood() { Version version; Assert.True(VersionHelper.TryParseAssemblyVersion("3.2.*", allowWildcard: true, version: out version)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(65535, version.Build); Assert.Equal(65535, version.Revision); Assert.True(VersionHelper.TryParseAssemblyVersion("1.2.3.*", allowWildcard: true, version: out version)); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(3, version.Build); Assert.Equal(65535, version.Revision); } [Fact] public void TimeBased() { var now = DateTime.Now; int days, seconds; VersionTestHelpers.GetDefaultVersion(now, out days, out seconds); var version = VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, new Version(3, 2, 65535, 65535)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(days, version.Build); Assert.Equal(seconds, version.Revision); version = VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, new Version(1, 2, 3, 65535)); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(3, version.Build); Assert.Equal(seconds, version.Revision); version = VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, new Version(1, 2, 3, 4)); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(3, version.Build); Assert.Equal(4, version.Revision); Assert.Null(VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, null)); } [Fact] public void ParseGood2() { Version version; Assert.True(VersionHelper.TryParse("1.234.56.7", out version)); Assert.Equal(1, version.Major); Assert.Equal(234, version.Minor); Assert.Equal(56, version.Build); Assert.Equal(7, version.Revision); Assert.True(VersionHelper.TryParse("3.2.1", out version)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(1, version.Build); Assert.Equal(0, version.Revision); Assert.True(VersionHelper.TryParse("3.2", out version)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(0, version.Build); Assert.Equal(0, version.Revision); Assert.True(VersionHelper.TryParse("3", out version)); Assert.Equal(3, version.Major); Assert.Equal(0, version.Minor); Assert.Equal(0, version.Build); Assert.Equal(0, version.Revision); } [Fact] public void ParseBad() { var expected = new Version(0, 0, 0, 0); Version version; Assert.False(VersionHelper.TryParseAssemblyVersion("1.234.56.7.*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.234.56.7.1", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2. *", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2.* ", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.1.*.*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(" ", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(null, allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("a", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("********", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("...", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(".a.b.", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(".0.1.", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("65535.65535.65535.65535", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("65535.65535.65535.65535", allowWildcard: false, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(" 1.2.3.4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1 .2.3.4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2.3.4 ", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2.3. 4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2. 3.4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); // U+FF11 FULLWIDTH DIGIT ONE Assert.False(VersionHelper.TryParseAssemblyVersion("\uFF11.\uFF10.\uFF10.\uFF10", allowWildcard: true, version: out version)); Assert.Equal(expected, version); } [Fact] public void ParseBad2() { var expected = new Version(0, 0, 0, 0); Version version; Assert.False(VersionHelper.TryParse("", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse(null, out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("a", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("********", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("...", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse(".a.b.", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse(".1.2.", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("1.234.56.7.8", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("*", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("-1.2.3.4", out version)); Assert.Equal(expected, version); // U+FF11 FULLWIDTH DIGIT ONE Assert.False(VersionHelper.TryParse("\uFF11.\uFF10.\uFF10.\uFF10", out version)); Assert.Equal(expected, version); } [Fact] public void ParsePartial() { var expected = new Version(0, 0, 0, 0); Version version; Assert.False(VersionHelper.TryParse("1.2. 3", out version)); Assert.Equal(new Version(1, 2, 0, 0), version); Assert.False(VersionHelper.TryParse("1.2.3 ", out version)); Assert.Equal(new Version(1, 2, 3, 0), version); Assert.False(VersionHelper.TryParse("1.a", out version)); Assert.Equal(new Version(1, 0, 0, 0), version); Assert.False(VersionHelper.TryParse("1.2.a.b", out version)); Assert.Equal(new Version(1, 2, 0, 0), version); Assert.False(VersionHelper.TryParse("1.-2.3.4", out version)); Assert.Equal(new Version(1, 0, 0, 0), version); Assert.False(VersionHelper.TryParse("1..1.2", out version)); Assert.Equal(new Version(1, 0, 0, 0), version); Assert.False(VersionHelper.TryParse("1.1.65536", out version)); Assert.Equal(new Version(1, 1, 0, 0), version); Assert.False(VersionHelper.TryParse("1.1.1.10000000", out version)); Assert.Equal(new Version(1, 1, 1, 38528), version); Assert.False(VersionHelper.TryParse("1.1.18446744073709551617999999999999999999999999900001.1", out version)); Assert.Equal(new Version(1, 1, 31073, 1), version); Assert.False(VersionHelper.TryParse("1.1.18446744073709551617999999999999999999999999900001garbage.1", out version)); Assert.Equal(new Version(1, 1, 31073, 0), version); Assert.False(VersionHelper.TryParse("1.1.18446744073709551617999999999999999999999999900001.23garbage", out version)); Assert.Equal(new Version(1, 1, 31073, 23), version); Assert.False(VersionHelper.TryParse("65536.2.65536.1", out version)); Assert.Equal(new Version(0, 2, 0, 1), version); } } }
// 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.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class VersionHelperTests { [Fact] public void ParseGood() { Version version; Assert.True(VersionHelper.TryParseAssemblyVersion("3.2.*", allowWildcard: true, version: out version)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(65535, version.Build); Assert.Equal(65535, version.Revision); Assert.True(VersionHelper.TryParseAssemblyVersion("1.2.3.*", allowWildcard: true, version: out version)); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(3, version.Build); Assert.Equal(65535, version.Revision); } [Fact] public void TimeBased() { var now = DateTime.Now; int days, seconds; VersionTestHelpers.GetDefaultVersion(now, out days, out seconds); var version = VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, new Version(3, 2, 65535, 65535)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(days, version.Build); Assert.Equal(seconds, version.Revision); version = VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, new Version(1, 2, 3, 65535)); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(3, version.Build); Assert.Equal(seconds, version.Revision); version = VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, new Version(1, 2, 3, 4)); Assert.Equal(1, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(3, version.Build); Assert.Equal(4, version.Revision); Assert.Null(VersionHelper.GenerateVersionFromPatternAndCurrentTime(now, null)); } [Fact] public void ParseGood2() { Version version; Assert.True(VersionHelper.TryParse("1.234.56.7", out version)); Assert.Equal(1, version.Major); Assert.Equal(234, version.Minor); Assert.Equal(56, version.Build); Assert.Equal(7, version.Revision); Assert.True(VersionHelper.TryParse("3.2.1", out version)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(1, version.Build); Assert.Equal(0, version.Revision); Assert.True(VersionHelper.TryParse("3.2", out version)); Assert.Equal(3, version.Major); Assert.Equal(2, version.Minor); Assert.Equal(0, version.Build); Assert.Equal(0, version.Revision); Assert.True(VersionHelper.TryParse("3", out version)); Assert.Equal(3, version.Major); Assert.Equal(0, version.Minor); Assert.Equal(0, version.Build); Assert.Equal(0, version.Revision); } [Fact] public void ParseBad() { var expected = new Version(0, 0, 0, 0); Version version; Assert.False(VersionHelper.TryParseAssemblyVersion("1.234.56.7.*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.234.56.7.1", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2. *", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2.* ", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.1.*.*", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(" ", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(null, allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("a", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("********", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("...", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(".a.b.", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(".0.1.", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("65535.65535.65535.65535", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("65535.65535.65535.65535", allowWildcard: false, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion(" 1.2.3.4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1 .2.3.4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2.3.4 ", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2.3. 4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParseAssemblyVersion("1.2. 3.4", allowWildcard: true, version: out version)); Assert.Equal(expected, version); // U+FF11 FULLWIDTH DIGIT ONE Assert.False(VersionHelper.TryParseAssemblyVersion("\uFF11.\uFF10.\uFF10.\uFF10", allowWildcard: true, version: out version)); Assert.Equal(expected, version); } [Fact] public void ParseBad2() { var expected = new Version(0, 0, 0, 0); Version version; Assert.False(VersionHelper.TryParse("", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse(null, out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("a", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("********", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("...", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse(".a.b.", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse(".1.2.", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("1.234.56.7.8", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("*", out version)); Assert.Equal(expected, version); Assert.False(VersionHelper.TryParse("-1.2.3.4", out version)); Assert.Equal(expected, version); // U+FF11 FULLWIDTH DIGIT ONE Assert.False(VersionHelper.TryParse("\uFF11.\uFF10.\uFF10.\uFF10", out version)); Assert.Equal(expected, version); } [Fact] public void ParsePartial() { var expected = new Version(0, 0, 0, 0); Version version; Assert.False(VersionHelper.TryParse("1.2. 3", out version)); Assert.Equal(new Version(1, 2, 0, 0), version); Assert.False(VersionHelper.TryParse("1.2.3 ", out version)); Assert.Equal(new Version(1, 2, 3, 0), version); Assert.False(VersionHelper.TryParse("1.a", out version)); Assert.Equal(new Version(1, 0, 0, 0), version); Assert.False(VersionHelper.TryParse("1.2.a.b", out version)); Assert.Equal(new Version(1, 2, 0, 0), version); Assert.False(VersionHelper.TryParse("1.-2.3.4", out version)); Assert.Equal(new Version(1, 0, 0, 0), version); Assert.False(VersionHelper.TryParse("1..1.2", out version)); Assert.Equal(new Version(1, 0, 0, 0), version); Assert.False(VersionHelper.TryParse("1.1.65536", out version)); Assert.Equal(new Version(1, 1, 0, 0), version); Assert.False(VersionHelper.TryParse("1.1.1.10000000", out version)); Assert.Equal(new Version(1, 1, 1, 38528), version); Assert.False(VersionHelper.TryParse("1.1.18446744073709551617999999999999999999999999900001.1", out version)); Assert.Equal(new Version(1, 1, 31073, 1), version); Assert.False(VersionHelper.TryParse("1.1.18446744073709551617999999999999999999999999900001garbage.1", out version)); Assert.Equal(new Version(1, 1, 31073, 0), version); Assert.False(VersionHelper.TryParse("1.1.18446744073709551617999999999999999999999999900001.23garbage", out version)); Assert.Equal(new Version(1, 1, 31073, 23), version); Assert.False(VersionHelper.TryParse("65536.2.65536.1", out version)); Assert.Equal(new Version(0, 2, 0, 1), version); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests_Tuples.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.Reflection.Metadata Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Tuples Inherits BasicTestBase Private Const s_tuplesTestSource As String = "Imports System Public Class Base0 End Class Public Class Base1(Of T) End Class Public Class Base2(Of T, U) End Class Public Class Outer(Of T) Inherits Base1(Of (key As Integer, val As Integer)) Public Class Inner(Of U, V) Inherits Base2(Of (key2 As Integer, val2 As Integer), V) Public Class InnerInner(Of W) Inherits Base1(Of (key3 As Integer, val2 As Integer)) End Class End Class End Class Public Class Derived(Of T) Inherits Outer(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))). Inner(Of Outer(Of (e5 As Integer, e6 As Integer)). Inner(Of (e7 As Integer, e8 As Integer)(), (e9 As Integer, e10 As Integer)). InnerInner(Of Integer)(), (e13 As (e11 As Integer, e12 As Integer), e14 As Integer)). InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) Public Shared Field1 As (e1 As Integer, e2 As Integer) Public Shared Field2 As (e1 As Integer, e2 As Integer) Public Shared Field3 As Base1(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))) Public Shared Field4 As ValueTuple(Of Base1(Of (e1 As Integer, e2 As (Integer, (Object, Object)))), Integer) Public Shared Field5 As Outer(Of (e1 As Object, e2 As Object)).Inner(Of (e3 As Object, e4 As Object), ValueTuple(Of Object, Object)) ' No names Public Shared Field6 As Base1(Of (Integer, ValueTuple(Of Integer, ValueTuple))) Public Shared Field7 As ValueTuple ' Long tuples Public Shared Field8 As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) Public Shared Field9 As Base1(Of (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer)) Public Shared Function Method1() As (e1 As Integer, e2 As Integer) Return Nothing End Function Public Shared Sub Method2(x As (e1 As Integer, e2 As Integer)) End Sub Public Shared Function Method3(x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) Return x End Function Public Shared Function Method4(ByRef x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) Return x End Function Public Shared Function Method5(ByRef x As (Object, Object)) As ((Integer, (Object, (Object, Object)), Object, Integer), ValueTuple) Return Nothing End Function Public Shared Function Method6() As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) Return Nothing End Function Public Shared ReadOnly Property Prop1 As (e1 As Integer, e2 As Integer) Get Return Nothing End Get End Property Public Shared Property Prop2 As (e1 As Integer, e2 As Integer) Public Default Property Prop3(param As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) Get Return param End Get Set End Set End Property Public Delegate Sub Delegate1(Of V)(sender As Object, args As ValueTuple(Of V, (e4 As (e1 As Object, e2 As Object, e3 As Object), e5 As Object), (Object, Object))) Public Shared Custom Event Event1 As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object)))) AddHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) End AddHandler RemoveHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class" Private Shared ReadOnly s_valueTupleRefs As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef} <Fact> Public Sub TestCompile() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:=s_valueTupleRefs) CompileAndVerify(comp) End Sub <Fact> Public Sub TestTupleAttributes() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:=s_valueTupleRefs) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) TupleAttributeValidator.ValidateTupleAttributes(m.ContainingAssembly)) End Sub <Fact> Public Sub TupleAttributeWithOnlyOneConstructor() Const attributeSource = "Namespace System.Runtime.CompilerServices Public Class TupleElementNamesAttribute Inherits Attribute Public Sub New(names() As String) End Sub End Class End Namespace" Dim comp0 = CreateCSharpCompilation(TestResources.NetFX.ValueTuple.tuplelib_cs) comp0.VerifyDiagnostics() Dim ref0 = comp0.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource, attributeSource}, options:=TestOptions.ReleaseDll, references:={SystemRuntimeFacadeRef, ref0}) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) TupleAttributeValidator.ValidateTupleAttributes(m.ContainingAssembly)) End Sub <Fact> Public Sub TupleLambdaParametersMissingString() Const source0 = "Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure Public Class MulticastDelegate End Class Public Interface IAsyncResult End Interface Public Class AsyncCallback End Class End Namespace" Const source1 = "Delegate Sub D(Of T)(o As T) Class C Shared Sub Main() Dim d As D(Of (x As Integer, y As Integer)) = Sub(o) End Sub d((0, 0)) End Sub End Class" Dim comp = CreateEmptyCompilation({source0}, assemblyName:="corelib") comp.AssertTheseDiagnostics() Dim ref0 = comp.EmitToImageReference() comp = CreateEmptyCompilation({source1}, references:={ValueTupleRef, SystemRuntimeFacadeRef, ref0}) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type 'ValueType'. Add one to your project. Dim d As D(Of (x As Integer, y As Integer)) = Sub(o) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'String' from assembly or module 'corelib.dll' failed. Dim d As D(Of (x As Integer, y As Integer)) = Sub(o) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type 'ValueType'. Add one to your project. d((0, 0)) ~~~~~~ </expected>) End Sub <Fact> Public Sub TupleInDeclarationFailureWithoutString() Const source0 = "Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure End Namespace" Const source1 = "Class C Shared Function M() As (x As Integer, y As Integer) Return Nothing End Function End Class" Dim comp = CreateEmptyCompilation({source0}, assemblyName:="corelib") comp.AssertTheseDiagnostics() Dim ref0 = comp.EmitToImageReference() comp = CreateEmptyCompilation({source1}, references:={ValueTupleRef, SystemRuntimeFacadeRef, ref0}) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type 'ValueType'. Add one to your project. Shared Function M() As (x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'String' from assembly or module 'corelib.dll' failed. Shared Function M() As (x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub RoundTrip() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:=s_valueTupleRefs) Dim sourceModule As ModuleSymbol = Nothing Dim peModule As ModuleSymbol = Nothing CompileAndVerify(comp, sourceSymbolValidator:=Sub(m) sourceModule = m, symbolValidator:=Sub(m) peModule = m) Dim srcTypes = sourceModule.GlobalNamespace.GetTypeMembers() Dim peTypes = peModule.GlobalNamespace.GetTypeMembers().WhereAsArray(Function(t) t.Name <> "<Module>") Assert.Equal(srcTypes.Length, peTypes.Count) For i = 0 To srcTypes.Length - 1 Dim srcType = srcTypes(i) Dim peType = peTypes(i) Assert.Equal(ToTestString(srcType.BaseType), ToTestString(peType.BaseType)) Dim srcMembers = srcType.GetMembers().Where(AddressOf IncludeMember).Select(AddressOf ToTestString).ToList() Dim peMembers = peType.GetMembers().Select(AddressOf ToTestString).ToList() srcMembers.Sort() peMembers.Sort() AssertEx.Equal(srcMembers, peMembers) Next End Sub Private Shared Function IncludeMember(s As Symbol) As Boolean Select Case s.Kind Case SymbolKind.Method If DirectCast(s, MethodSymbol).MethodKind = MethodKind.EventRaise Then Return False End If Case SymbolKind.Field If DirectCast(s, FieldSymbol).AssociatedSymbol IsNot Nothing Then Return False End If End Select Return True End Function Private Shared Function ToTestString(symbol As Symbol) As String Dim typeSymbols = ArrayBuilder(Of TypeSymbol).GetInstance() Select Case symbol.Kind Case SymbolKind.Method Dim method = DirectCast(symbol, MethodSymbol) typeSymbols.Add(method.ReturnType) typeSymbols.AddRange(method.Parameters.SelectAsArray(Function(p) p.Type)) Case SymbolKind.NamedType Dim type = DirectCast(symbol, NamedTypeSymbol) typeSymbols.Add(If(type.BaseType, type)) Case SymbolKind.Field typeSymbols.Add(DirectCast(symbol, FieldSymbol).Type) Case SymbolKind.Property typeSymbols.Add(DirectCast(symbol, PropertySymbol).Type) Case SymbolKind.Event typeSymbols.Add(DirectCast(symbol, EventSymbol).Type) End Select Dim symbolString = String.Join(" | ", typeSymbols.Select(Function(s) s.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))) typeSymbols.Free() Return $"{symbol.Name}: {symbolString}" End Function Private Structure TupleAttributeValidator Private ReadOnly _base0Class As NamedTypeSymbol Private ReadOnly _base1Class As NamedTypeSymbol Private ReadOnly _base2Class As NamedTypeSymbol Private ReadOnly _outerClass As NamedTypeSymbol Private ReadOnly _derivedClass As NamedTypeSymbol Private Sub New(assembly As AssemblySymbol) Dim globalNs = assembly.GlobalNamespace _base0Class = globalNs.GetTypeMember("Base0") _base1Class = globalNs.GetTypeMember("Base1") _base2Class = globalNs.GetTypeMember("Base2") _outerClass = globalNs.GetTypeMember("Outer") _derivedClass = globalNs.GetTypeMember("Derived") End Sub Shared Sub ValidateTupleAttributes(assembly As AssemblySymbol) Dim validator = New TupleAttributeValidator(assembly) validator.ValidateAttributesOnNamedTypes() validator.ValidateAttributesOnFields() validator.ValidateAttributesOnMethods() validator.ValidateAttributesOnProperties() validator.ValidateAttributesOnEvents() validator.ValidateAttributesOnDelegates() End Sub Private Sub ValidateAttributesOnDelegates() Dim delegate1 = _derivedClass.GetMember(Of NamedTypeSymbol)("Delegate1") Assert.True(delegate1.IsDelegateType()) Dim invokeMethod = delegate1.DelegateInvokeMethod ValidateTupleNameAttribute(invokeMethod, expectedTupleNamesAttribute:=False) Assert.Equal(2, invokeMethod.ParameterCount) Dim sender = invokeMethod.Parameters(0) Assert.Equal("sender", sender.Name) Assert.Equal(SpecialType.System_Object, sender.Type.SpecialType) ValidateTupleNameAttribute(sender, expectedTupleNamesAttribute:=False) Dim args = invokeMethod.Parameters(1) Assert.Equal("args", args.Name) ValidateTupleNameAttribute(args, expectedTupleNamesAttribute:=True, expectedElementNames:={Nothing, Nothing, Nothing, "e4", "e5", "e1", "e2", "e3", Nothing, Nothing}) End Sub Private Sub ValidateAttributesOnEvents() Dim event1 = _derivedClass.GetMember(Of EventSymbol)("Event1") ValidateTupleNameAttribute(event1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e4", Nothing, "e2", "e3"}) End Sub Private Sub ValidateAttributesOnNamedTypes() ValidateTupleNameAttribute(_base0Class, expectedTupleNamesAttribute:=False) ValidateTupleNameAttribute(_base1Class, expectedTupleNamesAttribute:=False) ValidateTupleNameAttribute(_base2Class, expectedTupleNamesAttribute:=False) Assert.True(_outerClass.BaseType.ContainsTuple()) ValidateTupleNameAttribute(_outerClass, expectedTupleNamesAttribute:=True, expectedElementNames:={"key", "val"}) ValidateTupleNameAttribute( _derivedClass, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e4", "e2", "e3", "e5", "e6", "e7", "e8", "e9", "e10", "e13", "e14", "e11", "e12", "e17", "e22", "e15", "e16", "e18", "e21", "e19", "e20"}) End Sub Private Sub ValidateAttributesOnFields() Dim field1 = _derivedClass.GetMember(Of FieldSymbol)("Field1") ValidateTupleNameAttribute(field1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim field2 = _derivedClass.GetMember(Of FieldSymbol)("Field2") ValidateTupleNameAttribute(field2, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim field3 = _derivedClass.GetMember(Of FieldSymbol)("Field3") ValidateTupleNameAttribute(field3, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e4", "e2", "e3"}) Dim field4 = _derivedClass.GetMember(Of FieldSymbol)("Field4") ValidateTupleNameAttribute(field4, expectedTupleNamesAttribute:=True, expectedElementNames:={Nothing, Nothing, "e1", "e2", Nothing, Nothing, Nothing, Nothing}) Dim field5 = _derivedClass.GetMember(Of FieldSymbol)("Field5") ValidateTupleNameAttribute(field5, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", Nothing, Nothing}) Dim field6 = _derivedClass.GetMember(Of FieldSymbol)("Field6") ValidateTupleNameAttribute(field6, expectedTupleNamesAttribute:=False) Dim field6Type = DirectCast(field6.Type, NamedTypeSymbol) Assert.Equal("Base1", field6Type.Name) Assert.Equal(1, field6Type.TypeParameters.Length) Dim firstTuple = field6Type.TypeArguments.Single() Assert.True(firstTuple.IsTupleType) Assert.True(firstTuple.TupleElementNames.IsDefault) Assert.Equal(2, firstTuple.TupleElementTypes.Length) Dim secondTuple = firstTuple.TupleElementTypes(1) Assert.True(secondTuple.IsTupleType) Assert.True(secondTuple.TupleElementNames.IsDefault) Assert.Equal(2, secondTuple.TupleElementTypes.Length) Dim field7 = _derivedClass.GetMember(Of FieldSymbol)("Field7") ValidateTupleNameAttribute(field7, expectedTupleNamesAttribute:=False) Assert.False(field7.Type.IsTupleType) Dim field8 = _derivedClass.GetMember(Of FieldSymbol)("Field8") ValidateTupleNameAttribute(field8, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", Nothing, Nothing}) Dim field9 = _derivedClass.GetMember(Of FieldSymbol)("Field9") ValidateTupleNameAttribute(field9, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", Nothing, Nothing}) End Sub Private Sub ValidateAttributesOnMethods() Dim method1 = _derivedClass.GetMember(Of MethodSymbol)("Method1") ValidateTupleNameAttribute(method1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}, forReturnType:=True) Dim method2 = _derivedClass.GetMember(Of MethodSymbol)("Method2") ValidateTupleNameAttribute(method2.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim method3 = _derivedClass.GetMember(Of MethodSymbol)("Method3") ValidateTupleNameAttribute(method3, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}, forReturnType:=True) ValidateTupleNameAttribute(method3.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e3", "e4"}) Dim method4 = _derivedClass.GetMember(Of MethodSymbol)("Method4") ValidateTupleNameAttribute(method4, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}, forReturnType:=True) ValidateTupleNameAttribute(method4.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e3", "e4"}) Dim method5 = _derivedClass.GetMember(Of MethodSymbol)("Method5") ValidateTupleNameAttribute(method5, expectedTupleNamesAttribute:=False, forReturnType:=True) ValidateTupleNameAttribute(method5.Parameters.Single(), expectedTupleNamesAttribute:=False) Dim method6 = _derivedClass.GetMember(Of MethodSymbol)("Method6") ValidateTupleNameAttribute(method6, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", Nothing, Nothing}, forReturnType:=True) End Sub Private Sub ValidateAttributesOnProperties() Dim prop1 = _derivedClass.GetMember(Of PropertySymbol)("Prop1") ValidateTupleNameAttribute(prop1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim prop2 = _derivedClass.GetMember(Of PropertySymbol)("Prop2") ValidateTupleNameAttribute(prop2, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim prop3 = _derivedClass.GetMember(Of PropertySymbol)("Prop3") ValidateTupleNameAttribute(prop3, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) ValidateTupleNameAttribute(prop3.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e3", "e4"}) End Sub Private Sub ValidateTupleNameAttribute( symbol As Symbol, expectedTupleNamesAttribute As Boolean, Optional expectedElementNames As String() = Nothing, Optional forReturnType As Boolean = False) Dim tupleElementNamesAttr = If(forReturnType, DirectCast(symbol, MethodSymbol).GetReturnTypeAttributes(), symbol.GetAttributes()). Where(Function(attr) String.Equals(attr.AttributeClass.Name, "TupleElementNamesAttribute", StringComparison.Ordinal)). AsImmutable() If Not expectedTupleNamesAttribute Then Assert.Empty(tupleElementNamesAttr) Assert.Null(expectedElementNames) Else Dim tupleAttr = tupleElementNamesAttr.Single() Assert.Equal("System.Runtime.CompilerServices.TupleElementNamesAttribute", tupleAttr.AttributeClass.ToTestDisplayString()) Assert.Equal("System.String()", tupleAttr.AttributeConstructor.Parameters.Single().Type.ToTestDisplayString()) If expectedElementNames Is Nothing Then Assert.True(tupleAttr.CommonConstructorArguments.IsEmpty) Else Dim arg = tupleAttr.CommonConstructorArguments.Single() Assert.Equal(TypedConstantKind.Array, arg.Kind) Dim actualElementNames = arg.Values.SelectAsArray(AddressOf TypedConstantString) AssertEx.Equal(expectedElementNames, actualElementNames) End If End If End Sub Private Shared Function TypedConstantString(constant As TypedConstant) As String Assert.True(constant.Type.SpecialType = SpecialType.System_String) Return DirectCast(constant.Value, String) End Function End Structure <Fact> Public Sub TupleAttributeMissing() Dim comp0 = CreateCSharpCompilation(TestResources.NetFX.ValueTuple.tuplelib_cs) comp0.VerifyDiagnostics() Dim ref0 = comp0.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:={SystemRuntimeFacadeRef, ref0}) comp.AssertTheseDiagnostics( <expected> BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base1(Of (key As Integer, val As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base2(Of (key2 As Integer, val2 As Integer), V) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base1(Of (key3 As Integer, val2 As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Outer(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Outer(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Outer(Of (e5 As Integer, e6 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inner(Of (e7 As Integer, e8 As Integer)(), (e9 As Integer, e10 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inner(Of (e7 As Integer, e8 As Integer)(), (e9 As Integer, e10 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? (e13 As (e11 As Integer, e12 As Integer), e14 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? (e13 As (e11 As Integer, e12 As Integer), e14 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field1 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field2 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field3 As Base1(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field3 As Base1(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field4 As ValueTuple(Of Base1(Of (e1 As Integer, e2 As (Integer, (Object, Object)))), Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field5 As Outer(Of (e1 As Object, e2 As Object)).Inner(Of (e3 As Object, e4 As Object), ValueTuple(Of Object, Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field5 As Outer(Of (e1 As Object, e2 As Object)).Inner(Of (e3 As Object, e4 As Object), ValueTuple(Of Object, Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field8 As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field9 As Base1(Of (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method1() As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Sub Method2(x As (e1 As Integer, e2 As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method3(x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method3(x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method4(ByRef x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method4(ByRef x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method6() As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared ReadOnly Property Prop1 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Property Prop2 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Default Property Prop3(param As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Default Property Prop3(param As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Delegate Sub Delegate1(Of V)(sender As Object, args As ValueTuple(Of V, (e4 As (e1 As Object, e2 As Object, e3 As Object), e5 As Object), (Object, Object))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Delegate Sub Delegate1(Of V)(sender As Object, args As ValueTuple(Of V, (e4 As (e1 As Object, e2 As Object, e3 As Object), e5 As Object), (Object, Object))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Custom Event Event1 As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object)))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Custom Event Event1 As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object)))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? AddHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? AddHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? RemoveHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? RemoveHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ExplicitTupleNamesAttribute() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoTuples"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices <TupleElementNames({"a", "b"})> Public Class C <TupleElementNames({Nothing, Nothing})> Public Field1 As ValueTuple(Of Integer, Integer) <TupleElementNames({"x", "y"})> Public ReadOnly Prop1 As ValueTuple(Of Integer, Integer) Public ReadOnly Property Prop2 As Integer <TupleElementNames({"x", "y"})> Get Return Nothing End Get End Property Public Function M(<TupleElementNames({Nothing})> x As ValueTuple) As <TupleElementNames({Nothing, Nothing})> ValueTuple(Of Integer, Integer) Return (0, 0) End Function Public Delegate Sub Delegate1(Of T)(sender As Object, <TupleElementNames({"x"})> args As ValueTuple(Of T)) <TupleElementNames({"y"})> Public Custom Event Event1 As Delegate1(Of ValueTuple(Of Integer)) AddHandler(value As Delegate1(Of ValueTuple(Of Integer))) End AddHandler RemoveHandler(value As Delegate1(Of ValueTuple(Of Integer))) End RemoveHandler RaiseEvent(sender As Object, args As ValueTuple(Of ValueTuple(Of Integer))) End RaiseEvent End Event <TupleElementNames({"a", "b"})> Default Public ReadOnly Property Item1(<TupleElementNames> t As (a As Integer, b As Integer)) As (a As Integer, b As Integer) Get Return t End Get End Property End Class <TupleElementNames({"a", "b"})> Public Structure S End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> <![CDATA[ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"a", "b"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({Nothing, Nothing})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"x", "y"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31445: Attribute 'TupleElementNamesAttribute' cannot be applied to 'Get' of 'Prop2' because the attribute is not valid on this declaration type. <TupleElementNames({"x", "y"})> ~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Public Function M(<TupleElementNames({Nothing})> x As ValueTuple) As <TupleElementNames({Nothing, Nothing})> ValueTuple(Of Integer, Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Public Function M(<TupleElementNames({Nothing})> x As ValueTuple) As <TupleElementNames({Nothing, Nothing})> ValueTuple(Of Integer, Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Public Delegate Sub Delegate1(Of T)(sender As Object, <TupleElementNames({"x"})> args As ValueTuple(Of T)) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'TupleElementNamesAttribute' cannot be applied to 'Event1' because the attribute is not valid on this declaration type. <TupleElementNames({"y"})> ~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"a", "b"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Default Public ReadOnly Property Item1(<TupleElementNames> t As (a As Integer, b As Integer)) As (a As Integer, b As Integer) ~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"a", "b"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) End Sub <Fact> <WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")> Public Sub AttributesOnTypeConstraints() Dim src = <compilation> <file src="a.vb"> <![CDATA[ Public Interface I1(Of T) End Interface Public Interface I2(Of T As I1(Of (a as Integer, b as Integer))) End Interface Public Interface I3(Of T As I1(Of (c as Integer, d as Integer))) End Interface ]]> </file> </compilation> Dim validator = Sub(assembly As PEAssembly) Dim reader = assembly.ManifestModule.MetadataReader Dim verifyTupleConstraint = Sub(def As TypeDefinition, tupleNames As String()) Dim typeParams = def.GetGenericParameters() Assert.Equal(1, typeParams.Count) Dim typeParam = reader.GetGenericParameter(typeParams(0)) Dim constraintHandles = typeParam.GetConstraints() Assert.Equal(1, constraintHandles.Count) Dim constraint = reader.GetGenericParameterConstraint(constraintHandles(0)) Dim Attributes = constraint.GetCustomAttributes() Assert.Equal(1, Attributes.Count) Dim attr = reader.GetCustomAttribute(Attributes.Single()) ' Verify that the attribute contains an array of matching tuple names Dim argsReader = reader.GetBlobReader(attr.Value) ' Prolog Assert.Equal(1, argsReader.ReadUInt16()) ' Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()) For Each name In tupleNames Assert.Equal(name, argsReader.ReadSerializedString()) Next End Sub For Each typeHandle In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(typeHandle) Dim name = reader.GetString(def.Name) Select Case name Case "I1`1" Case "<Module>" Continue For Case "I2`1" verifyTupleConstraint(def, {"a", "b"}) Exit For Case "I3`1" verifyTupleConstraint(def, {"c", "d"}) Exit For Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next End Sub Dim symbolValidator = Sub(m As ModuleSymbol) Dim verifyTupleImpls = Sub(t As NamedTypeSymbol, tupleNames As String()) Dim typeParam = t.TypeParameters.Single() Dim constraint = DirectCast(typeParam.ConstraintTypes.Single(), NamedTypeSymbol) Dim typeArg = constraint.TypeArguments.Single() Assert.True(typeArg.IsTupleType) Assert.Equal(tupleNames, typeArg.TupleElementNames) End Sub For Each t In m.GlobalNamespace.GetTypeMembers() Select Case t.Name Case "I1" Case "<Module>" Continue For Case "I2" verifyTupleImpls(t, {"a", "b"}) Exit For Case "I3" verifyTupleImpls(t, {"c", "d"}) Exit For Case Else Throw TestExceptionUtilities.UnexpectedValue(t.Name) End Select Next End Sub CompileAndVerify(src, references:={ValueTupleRef, SystemRuntimeFacadeRef}, validator:=validator, symbolValidator:=symbolValidator) End Sub <Fact> <WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")> Public Sub AttributesOnInterfaceImplementations() Dim src = <compilation> <file name="a.vb"> <![CDATA[ Public Interface I1(Of T) End Interface Public Interface I2 Inherits I1(Of (a as Integer, b as Integer)) End Interface Public Interface I3 Inherits I1(Of (c as Integer, d as Integer)) End Interface ]]> </file> </compilation> Dim validator = Sub(assembly As PEAssembly) Dim reader = assembly.ManifestModule.MetadataReader Dim verifyTupleImpls = Sub(def As TypeDefinition, tupleNames As String()) Dim interfaceImpls = def.GetInterfaceImplementations() Assert.Equal(1, interfaceImpls.Count) Dim interfaceImpl = reader.GetInterfaceImplementation(interfaceImpls.Single()) Dim attributes = interfaceImpl.GetCustomAttributes() Assert.Equal(1, attributes.Count) Dim attr = reader.GetCustomAttribute(attributes.Single()) ' Verify that the attribute contains an array of matching tuple names Dim argsReader = reader.GetBlobReader(attr.Value) ' Prolog Assert.Equal(1, argsReader.ReadUInt16()) ' Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()) For Each name In tupleNames Assert.Equal(name, argsReader.ReadSerializedString()) Next End Sub For Each typeHandle In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(typeHandle) Dim name = reader.GetString(def.Name) Select Case name Case "I1`1" Case "<Module>" Continue For Case "I2" verifyTupleImpls(def, {"a", "b"}) Exit Select Case "I3" verifyTupleImpls(def, {"c", "d"}) Exit Select Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next End Sub Dim symbolValidator = Sub(m As ModuleSymbol) Dim VerifyTupleImpls = Sub(t As NamedTypeSymbol, tupleNames As String()) Dim interfaceImpl = t.Interfaces.Single() Dim typeArg = interfaceImpl.TypeArguments.Single() Assert.True(typeArg.IsTupleType) Assert.Equal(tupleNames, typeArg.TupleElementNames) End Sub For Each t In m.GlobalNamespace.GetTypeMembers() Select Case t.Name Case "I1" Case "<Module>" Continue For Case "I2" VerifyTupleImpls(t, {"a", "b"}) Exit Select Case "I3" VerifyTupleImpls(t, {"c", "d"}) Exit Select Case Else Throw TestExceptionUtilities.UnexpectedValue(t.Name) End Select Next End Sub CompileAndVerify(src, references:={ValueTupleRef, SystemRuntimeFacadeRef}, validator:=validator, symbolValidator:=symbolValidator) 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.Reflection Imports System.Reflection.Metadata Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests_Tuples Inherits BasicTestBase Private Const s_tuplesTestSource As String = "Imports System Public Class Base0 End Class Public Class Base1(Of T) End Class Public Class Base2(Of T, U) End Class Public Class Outer(Of T) Inherits Base1(Of (key As Integer, val As Integer)) Public Class Inner(Of U, V) Inherits Base2(Of (key2 As Integer, val2 As Integer), V) Public Class InnerInner(Of W) Inherits Base1(Of (key3 As Integer, val2 As Integer)) End Class End Class End Class Public Class Derived(Of T) Inherits Outer(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))). Inner(Of Outer(Of (e5 As Integer, e6 As Integer)). Inner(Of (e7 As Integer, e8 As Integer)(), (e9 As Integer, e10 As Integer)). InnerInner(Of Integer)(), (e13 As (e11 As Integer, e12 As Integer), e14 As Integer)). InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) Public Shared Field1 As (e1 As Integer, e2 As Integer) Public Shared Field2 As (e1 As Integer, e2 As Integer) Public Shared Field3 As Base1(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))) Public Shared Field4 As ValueTuple(Of Base1(Of (e1 As Integer, e2 As (Integer, (Object, Object)))), Integer) Public Shared Field5 As Outer(Of (e1 As Object, e2 As Object)).Inner(Of (e3 As Object, e4 As Object), ValueTuple(Of Object, Object)) ' No names Public Shared Field6 As Base1(Of (Integer, ValueTuple(Of Integer, ValueTuple))) Public Shared Field7 As ValueTuple ' Long tuples Public Shared Field8 As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) Public Shared Field9 As Base1(Of (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer)) Public Shared Function Method1() As (e1 As Integer, e2 As Integer) Return Nothing End Function Public Shared Sub Method2(x As (e1 As Integer, e2 As Integer)) End Sub Public Shared Function Method3(x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) Return x End Function Public Shared Function Method4(ByRef x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) Return x End Function Public Shared Function Method5(ByRef x As (Object, Object)) As ((Integer, (Object, (Object, Object)), Object, Integer), ValueTuple) Return Nothing End Function Public Shared Function Method6() As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) Return Nothing End Function Public Shared ReadOnly Property Prop1 As (e1 As Integer, e2 As Integer) Get Return Nothing End Get End Property Public Shared Property Prop2 As (e1 As Integer, e2 As Integer) Public Default Property Prop3(param As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) Get Return param End Get Set End Set End Property Public Delegate Sub Delegate1(Of V)(sender As Object, args As ValueTuple(Of V, (e4 As (e1 As Object, e2 As Object, e3 As Object), e5 As Object), (Object, Object))) Public Shared Custom Event Event1 As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object)))) AddHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) End AddHandler RemoveHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class" Private Shared ReadOnly s_valueTupleRefs As MetadataReference() = New MetadataReference() {ValueTupleRef, SystemRuntimeFacadeRef} <Fact> Public Sub TestCompile() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:=s_valueTupleRefs) CompileAndVerify(comp) End Sub <Fact> Public Sub TestTupleAttributes() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:=s_valueTupleRefs) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) TupleAttributeValidator.ValidateTupleAttributes(m.ContainingAssembly)) End Sub <Fact> Public Sub TupleAttributeWithOnlyOneConstructor() Const attributeSource = "Namespace System.Runtime.CompilerServices Public Class TupleElementNamesAttribute Inherits Attribute Public Sub New(names() As String) End Sub End Class End Namespace" Dim comp0 = CreateCSharpCompilation(TestResources.NetFX.ValueTuple.tuplelib_cs) comp0.VerifyDiagnostics() Dim ref0 = comp0.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource, attributeSource}, options:=TestOptions.ReleaseDll, references:={SystemRuntimeFacadeRef, ref0}) CompileAndVerify(comp, symbolValidator:=Sub(m As ModuleSymbol) TupleAttributeValidator.ValidateTupleAttributes(m.ContainingAssembly)) End Sub <Fact> Public Sub TupleLambdaParametersMissingString() Const source0 = "Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure Public Class MulticastDelegate End Class Public Interface IAsyncResult End Interface Public Class AsyncCallback End Class End Namespace" Const source1 = "Delegate Sub D(Of T)(o As T) Class C Shared Sub Main() Dim d As D(Of (x As Integer, y As Integer)) = Sub(o) End Sub d((0, 0)) End Sub End Class" Dim comp = CreateEmptyCompilation({source0}, assemblyName:="corelib") comp.AssertTheseDiagnostics() Dim ref0 = comp.EmitToImageReference() comp = CreateEmptyCompilation({source1}, references:={ValueTupleRef, SystemRuntimeFacadeRef, ref0}) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type 'ValueType'. Add one to your project. Dim d As D(Of (x As Integer, y As Integer)) = Sub(o) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'String' from assembly or module 'corelib.dll' failed. Dim d As D(Of (x As Integer, y As Integer)) = Sub(o) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type 'ValueType'. Add one to your project. d((0, 0)) ~~~~~~ </expected>) End Sub <Fact> Public Sub TupleInDeclarationFailureWithoutString() Const source0 = "Namespace System Public Class [Object] End Class Public Structure Void End Structure Public Class ValueType End Class Public Structure IntPtr End Structure Public Structure Int32 End Structure End Namespace" Const source1 = "Class C Shared Function M() As (x As Integer, y As Integer) Return Nothing End Function End Class" Dim comp = CreateEmptyCompilation({source0}, assemblyName:="corelib") comp.AssertTheseDiagnostics() Dim ref0 = comp.EmitToImageReference() comp = CreateEmptyCompilation({source1}, references:={ValueTupleRef, SystemRuntimeFacadeRef, ref0}) comp.AssertTheseDiagnostics( <expected> BC30652: Reference required to assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' containing the type 'ValueType'. Add one to your project. Shared Function M() As (x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31091: Import of type 'String' from assembly or module 'corelib.dll' failed. Shared Function M() As (x As Integer, y As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub RoundTrip() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:=s_valueTupleRefs) Dim sourceModule As ModuleSymbol = Nothing Dim peModule As ModuleSymbol = Nothing CompileAndVerify(comp, sourceSymbolValidator:=Sub(m) sourceModule = m, symbolValidator:=Sub(m) peModule = m) Dim srcTypes = sourceModule.GlobalNamespace.GetTypeMembers() Dim peTypes = peModule.GlobalNamespace.GetTypeMembers().WhereAsArray(Function(t) t.Name <> "<Module>") Assert.Equal(srcTypes.Length, peTypes.Count) For i = 0 To srcTypes.Length - 1 Dim srcType = srcTypes(i) Dim peType = peTypes(i) Assert.Equal(ToTestString(srcType.BaseType), ToTestString(peType.BaseType)) Dim srcMembers = srcType.GetMembers().Where(AddressOf IncludeMember).Select(AddressOf ToTestString).ToList() Dim peMembers = peType.GetMembers().Select(AddressOf ToTestString).ToList() srcMembers.Sort() peMembers.Sort() AssertEx.Equal(srcMembers, peMembers) Next End Sub Private Shared Function IncludeMember(s As Symbol) As Boolean Select Case s.Kind Case SymbolKind.Method If DirectCast(s, MethodSymbol).MethodKind = MethodKind.EventRaise Then Return False End If Case SymbolKind.Field If DirectCast(s, FieldSymbol).AssociatedSymbol IsNot Nothing Then Return False End If End Select Return True End Function Private Shared Function ToTestString(symbol As Symbol) As String Dim typeSymbols = ArrayBuilder(Of TypeSymbol).GetInstance() Select Case symbol.Kind Case SymbolKind.Method Dim method = DirectCast(symbol, MethodSymbol) typeSymbols.Add(method.ReturnType) typeSymbols.AddRange(method.Parameters.SelectAsArray(Function(p) p.Type)) Case SymbolKind.NamedType Dim type = DirectCast(symbol, NamedTypeSymbol) typeSymbols.Add(If(type.BaseType, type)) Case SymbolKind.Field typeSymbols.Add(DirectCast(symbol, FieldSymbol).Type) Case SymbolKind.Property typeSymbols.Add(DirectCast(symbol, PropertySymbol).Type) Case SymbolKind.Event typeSymbols.Add(DirectCast(symbol, EventSymbol).Type) End Select Dim symbolString = String.Join(" | ", typeSymbols.Select(Function(s) s.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))) typeSymbols.Free() Return $"{symbol.Name}: {symbolString}" End Function Private Structure TupleAttributeValidator Private ReadOnly _base0Class As NamedTypeSymbol Private ReadOnly _base1Class As NamedTypeSymbol Private ReadOnly _base2Class As NamedTypeSymbol Private ReadOnly _outerClass As NamedTypeSymbol Private ReadOnly _derivedClass As NamedTypeSymbol Private Sub New(assembly As AssemblySymbol) Dim globalNs = assembly.GlobalNamespace _base0Class = globalNs.GetTypeMember("Base0") _base1Class = globalNs.GetTypeMember("Base1") _base2Class = globalNs.GetTypeMember("Base2") _outerClass = globalNs.GetTypeMember("Outer") _derivedClass = globalNs.GetTypeMember("Derived") End Sub Shared Sub ValidateTupleAttributes(assembly As AssemblySymbol) Dim validator = New TupleAttributeValidator(assembly) validator.ValidateAttributesOnNamedTypes() validator.ValidateAttributesOnFields() validator.ValidateAttributesOnMethods() validator.ValidateAttributesOnProperties() validator.ValidateAttributesOnEvents() validator.ValidateAttributesOnDelegates() End Sub Private Sub ValidateAttributesOnDelegates() Dim delegate1 = _derivedClass.GetMember(Of NamedTypeSymbol)("Delegate1") Assert.True(delegate1.IsDelegateType()) Dim invokeMethod = delegate1.DelegateInvokeMethod ValidateTupleNameAttribute(invokeMethod, expectedTupleNamesAttribute:=False) Assert.Equal(2, invokeMethod.ParameterCount) Dim sender = invokeMethod.Parameters(0) Assert.Equal("sender", sender.Name) Assert.Equal(SpecialType.System_Object, sender.Type.SpecialType) ValidateTupleNameAttribute(sender, expectedTupleNamesAttribute:=False) Dim args = invokeMethod.Parameters(1) Assert.Equal("args", args.Name) ValidateTupleNameAttribute(args, expectedTupleNamesAttribute:=True, expectedElementNames:={Nothing, Nothing, Nothing, "e4", "e5", "e1", "e2", "e3", Nothing, Nothing}) End Sub Private Sub ValidateAttributesOnEvents() Dim event1 = _derivedClass.GetMember(Of EventSymbol)("Event1") ValidateTupleNameAttribute(event1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e4", Nothing, "e2", "e3"}) End Sub Private Sub ValidateAttributesOnNamedTypes() ValidateTupleNameAttribute(_base0Class, expectedTupleNamesAttribute:=False) ValidateTupleNameAttribute(_base1Class, expectedTupleNamesAttribute:=False) ValidateTupleNameAttribute(_base2Class, expectedTupleNamesAttribute:=False) Assert.True(_outerClass.BaseType.ContainsTuple()) ValidateTupleNameAttribute(_outerClass, expectedTupleNamesAttribute:=True, expectedElementNames:={"key", "val"}) ValidateTupleNameAttribute( _derivedClass, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e4", "e2", "e3", "e5", "e6", "e7", "e8", "e9", "e10", "e13", "e14", "e11", "e12", "e17", "e22", "e15", "e16", "e18", "e21", "e19", "e20"}) End Sub Private Sub ValidateAttributesOnFields() Dim field1 = _derivedClass.GetMember(Of FieldSymbol)("Field1") ValidateTupleNameAttribute(field1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim field2 = _derivedClass.GetMember(Of FieldSymbol)("Field2") ValidateTupleNameAttribute(field2, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim field3 = _derivedClass.GetMember(Of FieldSymbol)("Field3") ValidateTupleNameAttribute(field3, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e4", "e2", "e3"}) Dim field4 = _derivedClass.GetMember(Of FieldSymbol)("Field4") ValidateTupleNameAttribute(field4, expectedTupleNamesAttribute:=True, expectedElementNames:={Nothing, Nothing, "e1", "e2", Nothing, Nothing, Nothing, Nothing}) Dim field5 = _derivedClass.GetMember(Of FieldSymbol)("Field5") ValidateTupleNameAttribute(field5, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", Nothing, Nothing}) Dim field6 = _derivedClass.GetMember(Of FieldSymbol)("Field6") ValidateTupleNameAttribute(field6, expectedTupleNamesAttribute:=False) Dim field6Type = DirectCast(field6.Type, NamedTypeSymbol) Assert.Equal("Base1", field6Type.Name) Assert.Equal(1, field6Type.TypeParameters.Length) Dim firstTuple = field6Type.TypeArguments.Single() Assert.True(firstTuple.IsTupleType) Assert.True(firstTuple.TupleElementNames.IsDefault) Assert.Equal(2, firstTuple.TupleElementTypes.Length) Dim secondTuple = firstTuple.TupleElementTypes(1) Assert.True(secondTuple.IsTupleType) Assert.True(secondTuple.TupleElementNames.IsDefault) Assert.Equal(2, secondTuple.TupleElementTypes.Length) Dim field7 = _derivedClass.GetMember(Of FieldSymbol)("Field7") ValidateTupleNameAttribute(field7, expectedTupleNamesAttribute:=False) Assert.False(field7.Type.IsTupleType) Dim field8 = _derivedClass.GetMember(Of FieldSymbol)("Field8") ValidateTupleNameAttribute(field8, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", Nothing, Nothing}) Dim field9 = _derivedClass.GetMember(Of FieldSymbol)("Field9") ValidateTupleNameAttribute(field9, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", Nothing, Nothing}) End Sub Private Sub ValidateAttributesOnMethods() Dim method1 = _derivedClass.GetMember(Of MethodSymbol)("Method1") ValidateTupleNameAttribute(method1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}, forReturnType:=True) Dim method2 = _derivedClass.GetMember(Of MethodSymbol)("Method2") ValidateTupleNameAttribute(method2.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim method3 = _derivedClass.GetMember(Of MethodSymbol)("Method3") ValidateTupleNameAttribute(method3, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}, forReturnType:=True) ValidateTupleNameAttribute(method3.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e3", "e4"}) Dim method4 = _derivedClass.GetMember(Of MethodSymbol)("Method4") ValidateTupleNameAttribute(method4, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}, forReturnType:=True) ValidateTupleNameAttribute(method4.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e3", "e4"}) Dim method5 = _derivedClass.GetMember(Of MethodSymbol)("Method5") ValidateTupleNameAttribute(method5, expectedTupleNamesAttribute:=False, forReturnType:=True) ValidateTupleNameAttribute(method5.Parameters.Single(), expectedTupleNamesAttribute:=False) Dim method6 = _derivedClass.GetMember(Of MethodSymbol)("Method6") ValidateTupleNameAttribute(method6, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", Nothing, Nothing}, forReturnType:=True) End Sub Private Sub ValidateAttributesOnProperties() Dim prop1 = _derivedClass.GetMember(Of PropertySymbol)("Prop1") ValidateTupleNameAttribute(prop1, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim prop2 = _derivedClass.GetMember(Of PropertySymbol)("Prop2") ValidateTupleNameAttribute(prop2, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) Dim prop3 = _derivedClass.GetMember(Of PropertySymbol)("Prop3") ValidateTupleNameAttribute(prop3, expectedTupleNamesAttribute:=True, expectedElementNames:={"e1", "e2"}) ValidateTupleNameAttribute(prop3.Parameters.Single(), expectedTupleNamesAttribute:=True, expectedElementNames:={"e3", "e4"}) End Sub Private Sub ValidateTupleNameAttribute( symbol As Symbol, expectedTupleNamesAttribute As Boolean, Optional expectedElementNames As String() = Nothing, Optional forReturnType As Boolean = False) Dim tupleElementNamesAttr = If(forReturnType, DirectCast(symbol, MethodSymbol).GetReturnTypeAttributes(), symbol.GetAttributes()). Where(Function(attr) String.Equals(attr.AttributeClass.Name, "TupleElementNamesAttribute", StringComparison.Ordinal)). AsImmutable() If Not expectedTupleNamesAttribute Then Assert.Empty(tupleElementNamesAttr) Assert.Null(expectedElementNames) Else Dim tupleAttr = tupleElementNamesAttr.Single() Assert.Equal("System.Runtime.CompilerServices.TupleElementNamesAttribute", tupleAttr.AttributeClass.ToTestDisplayString()) Assert.Equal("System.String()", tupleAttr.AttributeConstructor.Parameters.Single().Type.ToTestDisplayString()) If expectedElementNames Is Nothing Then Assert.True(tupleAttr.CommonConstructorArguments.IsEmpty) Else Dim arg = tupleAttr.CommonConstructorArguments.Single() Assert.Equal(TypedConstantKind.Array, arg.Kind) Dim actualElementNames = arg.Values.SelectAsArray(AddressOf TypedConstantString) AssertEx.Equal(expectedElementNames, actualElementNames) End If End If End Sub Private Shared Function TypedConstantString(constant As TypedConstant) As String Assert.True(constant.Type.SpecialType = SpecialType.System_String) Return DirectCast(constant.Value, String) End Function End Structure <Fact> Public Sub TupleAttributeMissing() Dim comp0 = CreateCSharpCompilation(TestResources.NetFX.ValueTuple.tuplelib_cs) comp0.VerifyDiagnostics() Dim ref0 = comp0.EmitToImageReference() Dim comp = CreateCompilationWithMscorlib40({s_tuplesTestSource}, options:=TestOptions.ReleaseDll, references:={SystemRuntimeFacadeRef, ref0}) comp.AssertTheseDiagnostics( <expected> BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base1(Of (key As Integer, val As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base2(Of (key2 As Integer, val2 As Integer), V) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Base1(Of (key3 As Integer, val2 As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Outer(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inherits Outer(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Outer(Of (e5 As Integer, e6 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inner(Of (e7 As Integer, e8 As Integer)(), (e9 As Integer, e10 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Inner(Of (e7 As Integer, e8 As Integer)(), (e9 As Integer, e10 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? (e13 As (e11 As Integer, e12 As Integer), e14 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? (e13 As (e11 As Integer, e12 As Integer), e14 As Integer)). ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? InnerInner(Of (e17 As (e15 As Integer, e16 As Integer), e22 As (e18 As Integer, e21 As Base1(Of (e19 As Integer, e20 As Integer))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field1 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field2 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field3 As Base1(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field3 As Base1(Of (e1 As Integer, e4 As (e2 As Integer, e3 As Integer))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field4 As ValueTuple(Of Base1(Of (e1 As Integer, e2 As (Integer, (Object, Object)))), Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field5 As Outer(Of (e1 As Object, e2 As Object)).Inner(Of (e3 As Object, e4 As Object), ValueTuple(Of Object, Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field5 As Outer(Of (e1 As Object, e2 As Object)).Inner(Of (e3 As Object, e4 As Object), ValueTuple(Of Object, Object)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field8 As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Field9 As Base1(Of (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method1() As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Sub Method2(x As (e1 As Integer, e2 As Integer)) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method3(x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method3(x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method4(ByRef x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method4(ByRef x As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Function Method6() As (e1 As Integer, e2 As Integer, e3 As Integer, e4 As Integer, e5 As Integer, e6 As Integer, e7 As Integer, e8 As Integer, e9 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared ReadOnly Property Prop1 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Property Prop2 As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Default Property Prop3(param As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Default Property Prop3(param As (e3 As Integer, e4 As Integer)) As (e1 As Integer, e2 As Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Delegate Sub Delegate1(Of V)(sender As Object, args As ValueTuple(Of V, (e4 As (e1 As Object, e2 As Object, e3 As Object), e5 As Object), (Object, Object))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Delegate Sub Delegate1(Of V)(sender As Object, args As ValueTuple(Of V, (e4 As (e1 As Object, e2 As Object, e3 As Object), e5 As Object), (Object, Object))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Custom Event Event1 As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object)))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? Public Shared Custom Event Event1 As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object)))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? AddHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? AddHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? RemoveHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37268: Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference? RemoveHandler(value As Delegate1(Of (e1 As Object, e4 As ValueTuple(Of (e2 As Object, e3 As Object))))) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ExplicitTupleNamesAttribute() Dim comp = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NoTuples"> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices <TupleElementNames({"a", "b"})> Public Class C <TupleElementNames({Nothing, Nothing})> Public Field1 As ValueTuple(Of Integer, Integer) <TupleElementNames({"x", "y"})> Public ReadOnly Prop1 As ValueTuple(Of Integer, Integer) Public ReadOnly Property Prop2 As Integer <TupleElementNames({"x", "y"})> Get Return Nothing End Get End Property Public Function M(<TupleElementNames({Nothing})> x As ValueTuple) As <TupleElementNames({Nothing, Nothing})> ValueTuple(Of Integer, Integer) Return (0, 0) End Function Public Delegate Sub Delegate1(Of T)(sender As Object, <TupleElementNames({"x"})> args As ValueTuple(Of T)) <TupleElementNames({"y"})> Public Custom Event Event1 As Delegate1(Of ValueTuple(Of Integer)) AddHandler(value As Delegate1(Of ValueTuple(Of Integer))) End AddHandler RemoveHandler(value As Delegate1(Of ValueTuple(Of Integer))) End RemoveHandler RaiseEvent(sender As Object, args As ValueTuple(Of ValueTuple(Of Integer))) End RaiseEvent End Event <TupleElementNames({"a", "b"})> Default Public ReadOnly Property Item1(<TupleElementNames> t As (a As Integer, b As Integer)) As (a As Integer, b As Integer) Get Return t End Get End Property End Class <TupleElementNames({"a", "b"})> Public Structure S End Structure ]]></file> </compilation>, additionalRefs:=s_valueTupleRefs) comp.AssertTheseDiagnostics( <errors> <![CDATA[ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"a", "b"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({Nothing, Nothing})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"x", "y"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC31445: Attribute 'TupleElementNamesAttribute' cannot be applied to 'Get' of 'Prop2' because the attribute is not valid on this declaration type. <TupleElementNames({"x", "y"})> ~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Public Function M(<TupleElementNames({Nothing})> x As ValueTuple) As <TupleElementNames({Nothing, Nothing})> ValueTuple(Of Integer, Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Public Function M(<TupleElementNames({Nothing})> x As ValueTuple) As <TupleElementNames({Nothing, Nothing})> ValueTuple(Of Integer, Integer) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Public Delegate Sub Delegate1(Of T)(sender As Object, <TupleElementNames({"x"})> args As ValueTuple(Of T)) ~~~~~~~~~~~~~~~~~~~~~~~~ BC30662: Attribute 'TupleElementNamesAttribute' cannot be applied to 'Event1' because the attribute is not valid on this declaration type. <TupleElementNames({"y"})> ~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"a", "b"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. Default Public ReadOnly Property Item1(<TupleElementNames> t As (a As Integer, b As Integer)) As (a As Integer, b As Integer) ~~~~~~~~~~~~~~~~~ BC37269: Cannot reference 'System.Runtime.CompilerServices.TupleElementNamesAttribute' explicitly. Use the tuple syntax to define tuple names. <TupleElementNames({"a", "b"})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]> </errors>) End Sub <Fact> <WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")> Public Sub AttributesOnTypeConstraints() Dim src = <compilation> <file src="a.vb"> <![CDATA[ Public Interface I1(Of T) End Interface Public Interface I2(Of T As I1(Of (a as Integer, b as Integer))) End Interface Public Interface I3(Of T As I1(Of (c as Integer, d as Integer))) End Interface ]]> </file> </compilation> Dim validator = Sub(assembly As PEAssembly) Dim reader = assembly.ManifestModule.MetadataReader Dim verifyTupleConstraint = Sub(def As TypeDefinition, tupleNames As String()) Dim typeParams = def.GetGenericParameters() Assert.Equal(1, typeParams.Count) Dim typeParam = reader.GetGenericParameter(typeParams(0)) Dim constraintHandles = typeParam.GetConstraints() Assert.Equal(1, constraintHandles.Count) Dim constraint = reader.GetGenericParameterConstraint(constraintHandles(0)) Dim Attributes = constraint.GetCustomAttributes() Assert.Equal(1, Attributes.Count) Dim attr = reader.GetCustomAttribute(Attributes.Single()) ' Verify that the attribute contains an array of matching tuple names Dim argsReader = reader.GetBlobReader(attr.Value) ' Prolog Assert.Equal(1, argsReader.ReadUInt16()) ' Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()) For Each name In tupleNames Assert.Equal(name, argsReader.ReadSerializedString()) Next End Sub For Each typeHandle In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(typeHandle) Dim name = reader.GetString(def.Name) Select Case name Case "I1`1" Case "<Module>" Continue For Case "I2`1" verifyTupleConstraint(def, {"a", "b"}) Exit For Case "I3`1" verifyTupleConstraint(def, {"c", "d"}) Exit For Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next End Sub Dim symbolValidator = Sub(m As ModuleSymbol) Dim verifyTupleImpls = Sub(t As NamedTypeSymbol, tupleNames As String()) Dim typeParam = t.TypeParameters.Single() Dim constraint = DirectCast(typeParam.ConstraintTypes.Single(), NamedTypeSymbol) Dim typeArg = constraint.TypeArguments.Single() Assert.True(typeArg.IsTupleType) Assert.Equal(tupleNames, typeArg.TupleElementNames) End Sub For Each t In m.GlobalNamespace.GetTypeMembers() Select Case t.Name Case "I1" Case "<Module>" Continue For Case "I2" verifyTupleImpls(t, {"a", "b"}) Exit For Case "I3" verifyTupleImpls(t, {"c", "d"}) Exit For Case Else Throw TestExceptionUtilities.UnexpectedValue(t.Name) End Select Next End Sub CompileAndVerify(src, references:={ValueTupleRef, SystemRuntimeFacadeRef}, validator:=validator, symbolValidator:=symbolValidator) End Sub <Fact> <WorkItem(14844, "https://github.com/dotnet/roslyn/issues/14844")> Public Sub AttributesOnInterfaceImplementations() Dim src = <compilation> <file name="a.vb"> <![CDATA[ Public Interface I1(Of T) End Interface Public Interface I2 Inherits I1(Of (a as Integer, b as Integer)) End Interface Public Interface I3 Inherits I1(Of (c as Integer, d as Integer)) End Interface ]]> </file> </compilation> Dim validator = Sub(assembly As PEAssembly) Dim reader = assembly.ManifestModule.MetadataReader Dim verifyTupleImpls = Sub(def As TypeDefinition, tupleNames As String()) Dim interfaceImpls = def.GetInterfaceImplementations() Assert.Equal(1, interfaceImpls.Count) Dim interfaceImpl = reader.GetInterfaceImplementation(interfaceImpls.Single()) Dim attributes = interfaceImpl.GetCustomAttributes() Assert.Equal(1, attributes.Count) Dim attr = reader.GetCustomAttribute(attributes.Single()) ' Verify that the attribute contains an array of matching tuple names Dim argsReader = reader.GetBlobReader(attr.Value) ' Prolog Assert.Equal(1, argsReader.ReadUInt16()) ' Array size Assert.Equal(tupleNames.Length, argsReader.ReadInt32()) For Each name In tupleNames Assert.Equal(name, argsReader.ReadSerializedString()) Next End Sub For Each typeHandle In reader.TypeDefinitions Dim def = reader.GetTypeDefinition(typeHandle) Dim name = reader.GetString(def.Name) Select Case name Case "I1`1" Case "<Module>" Continue For Case "I2" verifyTupleImpls(def, {"a", "b"}) Exit Select Case "I3" verifyTupleImpls(def, {"c", "d"}) Exit Select Case Else Throw TestExceptionUtilities.UnexpectedValue(name) End Select Next End Sub Dim symbolValidator = Sub(m As ModuleSymbol) Dim VerifyTupleImpls = Sub(t As NamedTypeSymbol, tupleNames As String()) Dim interfaceImpl = t.Interfaces.Single() Dim typeArg = interfaceImpl.TypeArguments.Single() Assert.True(typeArg.IsTupleType) Assert.Equal(tupleNames, typeArg.TupleElementNames) End Sub For Each t In m.GlobalNamespace.GetTypeMembers() Select Case t.Name Case "I1" Case "<Module>" Continue For Case "I2" VerifyTupleImpls(t, {"a", "b"}) Exit Select Case "I3" VerifyTupleImpls(t, {"c", "d"}) Exit Select Case Else Throw TestExceptionUtilities.UnexpectedValue(t.Name) End Select Next End Sub CompileAndVerify(src, references:={ValueTupleRef, SystemRuntimeFacadeRef}, validator:=validator, symbolValidator:=symbolValidator) End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Test/Resources/Core/SymbolsTests/UseSiteErrors/ILErrors.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL!PP!  ) @@ `@D)W@  H.text  `.reloc @ @B)H  * ***( * ** ** * ***( ***( ***( ***( *BSJB v4.0.30319l@#~H#Strings#US#GUID #BlobG %3 '  * P un| n     %!5 #Q&P g%S s+V 2X 9Z Jg%s+29b %e 2g +j 9l %o +r 2t 9v J % 2 + 9 % + 2 9 ~ A A J A A J A A M M J M M JJJ. j.s  >>>> > Y_"f*Y/_4Y9_Y_*Y/_4Y9_    !"  #$ & '    <Module>System.Runtime.CompilerServicesCompilationRelaxationsAttribute.ctorRuntimeCompatibilityAttributeSystemObjectUnavailableClassAction`1ILErrors.dllUnavailablemscorlibClassMethodsILErrorsInterfaceMethodsClassPropertiesInterfacePropertiesClassEventsClassEventsNonVirtualInterfaceEventsModReqClassEventsNonVirtualModReqInterfaceEventsReturnType1ReturnType2ParameterType1uParameterType2get_GetSet1set_GetSet1valueget_GetSet2set_GetSet2get_Get1get_Get2set_Set1set_Set2add_Event1remove_Event1GetSet1GetSet2GetSet3Get1Get2Set1Set2Event1 c:Kq%?ų   z\V4          ( ( (TWrapNonExceptionThrowsl)) )_CorDllMainmscoree.dll% @ 9
MZ@ !L!This program cannot be run in DOS mode. $PEL!PP!  ) @@ `@D)W@  H.text  `.reloc @ @B)H  * ***( * ** ** * ***( ***( ***( ***( *BSJB v4.0.30319l@#~H#Strings#US#GUID #BlobG %3 '  * P un| n     %!5 #Q&P g%S s+V 2X 9Z Jg%s+29b %e 2g +j 9l %o +r 2t 9v J % 2 + 9 % + 2 9 ~ A A J A A J A A M M J M M JJJ. j.s  >>>> > Y_"f*Y/_4Y9_Y_*Y/_4Y9_    !"  #$ & '    <Module>System.Runtime.CompilerServicesCompilationRelaxationsAttribute.ctorRuntimeCompatibilityAttributeSystemObjectUnavailableClassAction`1ILErrors.dllUnavailablemscorlibClassMethodsILErrorsInterfaceMethodsClassPropertiesInterfacePropertiesClassEventsClassEventsNonVirtualInterfaceEventsModReqClassEventsNonVirtualModReqInterfaceEventsReturnType1ReturnType2ParameterType1uParameterType2get_GetSet1set_GetSet1valueget_GetSet2set_GetSet2get_Get1get_Get2set_Set1set_Set2add_Event1remove_Event1GetSet1GetSet2GetSet3Get1Get2Set1Set2Event1 c:Kq%?ų   z\V4          ( ( (TWrapNonExceptionThrowsl)) )_CorDllMainmscoree.dll% @ 9
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/CSharpTest2/Recommendations/ExplicitKeywordRecommenderTests.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 ExplicitKeywordRecommenderTests : 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 TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalUsing() { await VerifyAbsenceAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace() { await VerifyAbsenceAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeDeclaration() { await VerifyAbsenceAsync(@"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateDeclaration() { await VerifyAbsenceAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethod() { await VerifyAbsenceAsync(@"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodInPartialType() { await VerifyAbsenceAsync( @"partial class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFieldInPartialClass() { await VerifyAbsenceAsync( @"partial class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertyInPartialClass() { await VerifyAbsenceAsync( @"partial class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync( @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync( @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAssemblyAttribute() { await VerifyAbsenceAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAttributeInPartialClass() { await VerifyAbsenceAsync( @"partial class C { [goo] $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStruct() { await VerifyAbsenceAsync(@"struct S { $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsidePartialStruct() { await VerifyAbsenceAsync( @"partial struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideInterface() { await VerifyAbsenceAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsidePartialClass() { await VerifyAbsenceAsync( @"partial class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublicInClass() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStaticPublicInInterface() { await VerifyAbsenceAsync( @"interface C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstractPublicInInterface() { await VerifyAbsenceAsync( @"interface C { abstract public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticAbstractPublicInInterface() { await VerifyKeywordAsync( @"interface C { static abstract public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstractStaticPublicInInterface() { await VerifyKeywordAsync( @"interface C { abstract static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticAbstractInInterface() { await VerifyKeywordAsync( @"interface C { static abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstractStaticInInterface() { await VerifyKeywordAsync( @"interface C { abstract static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStaticInInterface() { await VerifyAbsenceAsync( @"interface C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublicStatic() => await VerifyAbsenceAsync(@"public static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStaticInClass() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPublicStaticInInterface() { await VerifyAbsenceAsync( @"interface C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPublicAbstractInInterface() { await VerifyAbsenceAsync( @"interface C { public abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStaticAbstractInInterface() { await VerifyKeywordAsync( @"interface C { public static abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicAbstractStaticInInterface() { await VerifyKeywordAsync( @"interface C { public abstract 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 TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterProtected() => await VerifyAbsenceAsync(@"protected $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenUsings() { await VerifyAbsenceAsync( @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenGlobalUsings_01() { await VerifyAbsenceAsync( @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenGlobalUsings_02() { await VerifyAbsenceAsync( @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstractInClass() { await VerifyAbsenceAsync(@"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtualInClass() { await VerifyAbsenceAsync(@"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverrideInClass() { await VerifyAbsenceAsync(@"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealedInClass() { await VerifyAbsenceAsync(@"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedReadOnlyInClass() { await VerifyAbsenceAsync(@"class C { readonly $$"); } [WorkItem(544102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544102")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedUnsafeStaticPublicInClass() { await VerifyKeywordAsync(@"class C { unsafe static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstractInInterface() { await VerifyAbsenceAsync(@"interface C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtualInInterface() { await VerifyAbsenceAsync(@"interface C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverrideInInterface() { await VerifyAbsenceAsync(@"interface C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealedInInterface() { await VerifyAbsenceAsync(@"interface C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedReadOnlyInInterface() { await VerifyAbsenceAsync(@"interface C { readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUnsafeStaticAbstractInInterface() { await VerifyKeywordAsync(@"interface C { unsafe static abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternStaticAbstractInInterface() { await VerifyAbsenceAsync(@"interface C { extern static abstract $$"); } } }
// 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 ExplicitKeywordRecommenderTests : 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 TestNotInEmptyStatement() { await VerifyAbsenceAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCompilationUnit() => await VerifyAbsenceAsync(@"$$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExtern() { await VerifyAbsenceAsync(@"extern alias Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterUsing() { await VerifyAbsenceAsync(@"using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterGlobalUsing() { await VerifyAbsenceAsync(@"global using Goo; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNamespace() { await VerifyAbsenceAsync(@"namespace N {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterTypeDeclaration() { await VerifyAbsenceAsync(@"class C {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateDeclaration() { await VerifyAbsenceAsync(@"delegate void Goo(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethod() { await VerifyAbsenceAsync(@"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterMethodInPartialType() { await VerifyAbsenceAsync( @"partial class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterFieldInPartialClass() { await VerifyAbsenceAsync( @"partial class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPropertyInPartialClass() { await VerifyAbsenceAsync( @"partial class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeUsing() { await VerifyAbsenceAsync( @"$$ using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBeforeGlobalUsing() { await VerifyAbsenceAsync( @"$$ global using Goo;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAssemblyAttribute() { await VerifyAbsenceAsync(@"[assembly: goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterRootAttribute() { await VerifyAbsenceAsync(@"[goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAttributeInPartialClass() { await VerifyAbsenceAsync( @"partial class C { [goo] $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideStruct() { await VerifyAbsenceAsync(@"struct S { $$"); } // This will be fixed once we have accessibility for members [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsidePartialStruct() { await VerifyAbsenceAsync( @"partial struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsideInterface() { await VerifyAbsenceAsync(@"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInsidePartialClass() { await VerifyAbsenceAsync( @"partial class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAbstract() => await VerifyAbsenceAsync(@"abstract $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(@"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(@"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(@"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublicInClass() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStaticPublicInInterface() { await VerifyAbsenceAsync( @"interface C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstractPublicInInterface() { await VerifyAbsenceAsync( @"interface C { abstract public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticAbstractPublicInInterface() { await VerifyKeywordAsync( @"interface C { static abstract public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstractStaticPublicInInterface() { await VerifyKeywordAsync( @"interface C { abstract static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticAbstractInInterface() { await VerifyKeywordAsync( @"interface C { static abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstractStaticInInterface() { await VerifyKeywordAsync( @"interface C { abstract static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedStaticInInterface() { await VerifyAbsenceAsync( @"interface C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublicStatic() => await VerifyAbsenceAsync(@"public static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStaticInClass() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPublicStaticInInterface() { await VerifyAbsenceAsync( @"interface C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPublicAbstractInInterface() { await VerifyAbsenceAsync( @"interface C { public abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStaticAbstractInInterface() { await VerifyKeywordAsync( @"interface C { public static abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicAbstractStaticInInterface() { await VerifyKeywordAsync( @"interface C { public abstract 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 TestNotAfterPrivate() => await VerifyAbsenceAsync(@"private $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterProtected() => await VerifyAbsenceAsync(@"protected $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterSealed() => await VerifyAbsenceAsync(@"sealed $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStatic() => await VerifyAbsenceAsync(@"static $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterClass() => await VerifyAbsenceAsync(@"class $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegate() => await VerifyAbsenceAsync(@"delegate $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenUsings() { await VerifyAbsenceAsync( @"using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenGlobalUsings_01() { await VerifyAbsenceAsync( @"global using Goo; $$ using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotBetweenGlobalUsings_02() { await VerifyAbsenceAsync( @"global using Goo; $$ global using Bar;"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstractInClass() { await VerifyAbsenceAsync(@"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtualInClass() { await VerifyAbsenceAsync(@"class C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverrideInClass() { await VerifyAbsenceAsync(@"class C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealedInClass() { await VerifyAbsenceAsync(@"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedReadOnlyInClass() { await VerifyAbsenceAsync(@"class C { readonly $$"); } [WorkItem(544102, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544102")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedUnsafeStaticPublicInClass() { await VerifyKeywordAsync(@"class C { unsafe static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedAbstractInInterface() { await VerifyAbsenceAsync(@"interface C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedVirtualInInterface() { await VerifyAbsenceAsync(@"interface C { virtual $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedOverrideInInterface() { await VerifyAbsenceAsync(@"interface C { override $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedSealedInInterface() { await VerifyAbsenceAsync(@"interface C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedReadOnlyInInterface() { await VerifyAbsenceAsync(@"interface C { readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterUnsafeStaticAbstractInInterface() { await VerifyKeywordAsync(@"interface C { unsafe static abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterExternStaticAbstractInInterface() { await VerifyAbsenceAsync(@"interface C { extern static abstract $$"); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/TestUtilities/Diagnostics/GenerateType/TestProjectManagementService.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.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ProjectManagement; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType { [ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Default), Shared] internal class TestProjectManagementService : IProjectManagementService { private string _defaultNamespace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestProjectManagementService() { } public IList<string> GetFolders(ProjectId projectId, Workspace workspace) => null; public string GetDefaultNamespace(Project project, Workspace workspace) => _defaultNamespace; public void SetDefaultNamespace(string defaultNamespace) => _defaultNamespace = defaultNamespace; } }
// 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.Composition; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ProjectManagement; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType { [ExportWorkspaceService(typeof(IProjectManagementService), ServiceLayer.Default), Shared] internal class TestProjectManagementService : IProjectManagementService { private string _defaultNamespace; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestProjectManagementService() { } public IList<string> GetFolders(ProjectId projectId, Workspace workspace) => null; public string GetDefaultNamespace(Project project, Workspace workspace) => _defaultNamespace; public void SetDefaultNamespace(string defaultNamespace) => _defaultNamespace = defaultNamespace; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmEvaluationFlags.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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation { [Flags] public enum DkmEvaluationFlags { None, NoSideEffects = 4, ShowValueRaw = 128, HideNonPublicMembers = 512, NoToString = 1024, NoFormatting = 2048, NoRawView = 4096, // Not used in managed debugging NoQuotes = 8192, DynamicView = 16384, ResultsOnly = 32768, NoExpansion = 65536, FilterToFavorites = 0x40000, UseSimpleDisplayString = 0x80000, } }
// 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 #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; namespace Microsoft.VisualStudio.Debugger.Evaluation { [Flags] public enum DkmEvaluationFlags { None, NoSideEffects = 4, ShowValueRaw = 128, HideNonPublicMembers = 512, NoToString = 1024, NoFormatting = 2048, NoRawView = 4096, // Not used in managed debugging NoQuotes = 8192, DynamicView = 16384, ResultsOnly = 32768, NoExpansion = 65536, FilterToFavorites = 0x40000, UseSimpleDisplayString = 0x80000, } }
-1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/AbstractCSharpCompletionProviderTests.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.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Completion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Xunit; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public abstract class AbstractCSharpCompletionProviderTests : AbstractCSharpCompletionProviderTests<CSharpTestWorkspaceFixture> { } public abstract class AbstractCSharpCompletionProviderTests<TWorkspaceFixture> : AbstractCompletionProviderTests<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected const string NonBreakingSpaceString = "\x00A0"; protected static string GetMarkup(string source, LanguageVersion languageVersion) => $@"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" LanguageVersion=""{languageVersion.ToDisplayString()}""> <Document FilePath=""Test2.cs""> {source} </Document> </Project> </Workspace>"; protected override TestWorkspace CreateWorkspace(string fileContents) => TestWorkspace.CreateCSharp(fileContents, exportProvider: ExportProvider); internal override CompletionServiceWithProviders GetCompletionService(Project project) => Assert.IsType<CSharpCompletionService>(base.GetCompletionService(project)); private protected override Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected override async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfCommentAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); // Items cannot be partially written if we're checking for their absence, // or if we're verifying that the list will show up (without specifying an actual item) if (!checkForAbsence && expectedItemOrNull != null) { await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfComment_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } } protected override string ItemPartiallyWritten(string expectedItemOrNull) => expectedItemOrNull[0] == '@' ? expectedItemOrNull.Substring(1, 1) : expectedItemOrNull.Substring(0, 1); private Task VerifyInFrontOfCommentAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { code = code.Substring(0, position) + insertText + "/**/" + code.Substring(position); position += insertText.Length; return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null); } private Task VerifyInFrontOfCommentAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { return VerifyInFrontOfCommentAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } private protected Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { return VerifyInFrontOfCommentAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } protected static string AddInsideMethod(string text) { return @"class C { void F() { " + text + @" } }"; } protected static string AddUsingDirectives(string usingDirectives, string text) { return usingDirectives + @" " + text; } protected async Task VerifySendEnterThroughToEnterAsync(string initialMarkup, string textTypedSoFar, EnterKeyRule sendThroughEnterOption, bool expected) { using var workspace = CreateWorkspace(initialMarkup); var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption( CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, sendThroughEnterOption))); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynTrigger.Invoke); var item = completionList.Items.First(i => (i.DisplayText + i.DisplayTextSuffix).StartsWith(textTypedSoFar)); Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(), item, textTypedSoFar)); } protected void TestCommonIsTextualTriggerCharacter() { var alwaysTriggerList = new[] { "goo$$.", }; foreach (var markup in alwaysTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true); } var triggerOnlyWithLettersList = new[] { "$$a", "$$_" }; foreach (var markup in triggerOnlyWithLettersList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: false); } var neverTriggerList = new[] { "goo$$x", "goo$$_" }; foreach (var markup in neverTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: false, shouldTriggerWithTriggerOnLettersDisabled: 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Editor.UnitTests.Completion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Xunit; using RoslynTrigger = Microsoft.CodeAnalysis.Completion.CompletionTrigger; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public abstract class AbstractCSharpCompletionProviderTests : AbstractCSharpCompletionProviderTests<CSharpTestWorkspaceFixture> { } public abstract class AbstractCSharpCompletionProviderTests<TWorkspaceFixture> : AbstractCompletionProviderTests<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected const string NonBreakingSpaceString = "\x00A0"; protected static string GetMarkup(string source, LanguageVersion languageVersion) => $@"<Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"" LanguageVersion=""{languageVersion.ToDisplayString()}""> <Document FilePath=""Test2.cs""> {source} </Document> </Project> </Workspace>"; protected override TestWorkspace CreateWorkspace(string fileContents) => TestWorkspace.CreateCSharp(fileContents, exportProvider: ExportProvider); internal override CompletionServiceWithProviders GetCompletionService(Project project) => Assert.IsType<CSharpCompletionService>(base.GetCompletionService(project)); private protected override Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { return base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags); } private protected override async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription = null, bool? isComplexTextEdit = null, List<CompletionFilter> matchingFilters = null, CompletionItemFlags? flags = null) { await VerifyAtPositionAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfCommentAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFileAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); // Items cannot be partially written if we're checking for their absence, // or if we're verifying that the list will show up (without specifying an actual item) if (!checkForAbsence && expectedItemOrNull != null) { await VerifyAtPosition_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyInFrontOfComment_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); await VerifyAtEndOfFile_ItemPartiallyWrittenAsync(code, position, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } } protected override string ItemPartiallyWritten(string expectedItemOrNull) => expectedItemOrNull[0] == '@' ? expectedItemOrNull.Substring(1, 1) : expectedItemOrNull.Substring(0, 1); private async Task VerifyInFrontOfCommentAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { code = code.Substring(0, position) + insertText + "/**/" + code.Substring(position); position += insertText.Length; await base.VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters, flags: null); } private async Task VerifyInFrontOfCommentAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { await VerifyInFrontOfCommentAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } private protected async Task VerifyInFrontOfComment_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority, bool? hasSuggestionItem, string displayTextSuffix, string displayTextPrefix, string inlineDescription, bool? isComplexTextEdit, List<CompletionFilter> matchingFilters) { await VerifyInFrontOfCommentAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority, hasSuggestionItem, displayTextSuffix, displayTextPrefix, inlineDescription, isComplexTextEdit, matchingFilters); } protected static string AddInsideMethod(string text) { return @"class C { void F() { " + text + @" } }"; } protected static string AddUsingDirectives(string usingDirectives, string text) { return usingDirectives + @" " + text; } protected async Task VerifySendEnterThroughToEnterAsync(string initialMarkup, string textTypedSoFar, EnterKeyRule sendThroughEnterOption, bool expected) { using var workspace = CreateWorkspace(initialMarkup); var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption( CompletionOptions.EnterKeyBehavior, LanguageNames.CSharp, sendThroughEnterOption))); var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, RoslynTrigger.Invoke); var item = completionList.Items.First(i => (i.DisplayText + i.DisplayTextSuffix).StartsWith(textTypedSoFar)); Assert.Equal(expected, CommitManager.SendEnterThroughToEditor(service.GetRules(), item, textTypedSoFar)); } protected void TestCommonIsTextualTriggerCharacter() { var alwaysTriggerList = new[] { "goo$$.", }; foreach (var markup in alwaysTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: true); } var triggerOnlyWithLettersList = new[] { "$$a", "$$_" }; foreach (var markup in triggerOnlyWithLettersList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: true, shouldTriggerWithTriggerOnLettersDisabled: false); } var neverTriggerList = new[] { "goo$$x", "goo$$_" }; foreach (var markup in neverTriggerList) { VerifyTextualTriggerCharacter(markup, shouldTriggerWithTriggerOnLettersEnabled: false, shouldTriggerWithTriggerOnLettersDisabled: false); } } } }
1
dotnet/roslyn
56,385
Add completion tests for parameters in top-level statements
See #55969
sharwell
"2021-09-14T19:31:23Z"
"2021-09-28T21:14:32Z"
ca9dba5fe617002a3abc0433a456dda80f4deec6
567c588b35e3f98f3e7aec09759981505971cf9b
Add completion tests for parameters in top-level statements. See #55969
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { [UseExportProvider] public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(SymbolCompletionProvider); [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFile(SourceCodeKind sourceCodeKind) { await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind) { await VerifyItemExistsAsync(@"using System; $$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"using System; $$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashR() => await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashLoad() => await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirective() { await VerifyItemIsAbsentAsync(@"using $$", @"String"); await VerifyItemIsAbsentAsync(@"using $$ = System", @"System"); await VerifyItemExistsAsync(@"using $$", @"System"); await VerifyItemExistsAsync(@"using T = $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegionWithUsing() { await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegionWithUsing() { await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineXmlComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenCharLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute1() { await VerifyItemExistsAsync(@"[assembly: $$]", @"System"); await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SystemAttributeIsNotAnAttribute() { var content = @"[$$] class CL {}"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeAttribute() { var content = @"[$$] class CL {}"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamAttribute() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodAttribute() { var content = @"class CL { [$$] void Method() {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodTypeParamAttribute() { var content = @"class CL{ void Method<[A$$]T> () {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamAttribute() { var content = @"class CL{ void Method ([$$]int i) {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_TopLevel() { var source = @"namespace $$ { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_Nested() { var source = @"; namespace System { namespace $$ { } }"; await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers() { var source = @"using System; namespace $$"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace() { var source = @"using System; namespace $$;"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelWithPeer() { var source = @" namespace A { } namespace $$"; await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithNoPeers() { var source = @" namespace A { namespace $$ }"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithPeer() { var source = @" namespace A { namespace B { } namespace $$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() { var source = @"namespace N$$S"; await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNested() { var source = @" namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace $$ namespace C1 { } } namespace B.C2 { } } namespace A.B.C3 { }"; // Ideally, all the C* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // C1 => A.B.?.C1 // C2 => A.B.B.C2 // C3 => A.A.B.C3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); // Because of the above, B does end up in the completion list // since A.B.B appears to be a peer of the new declaration await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NoPeers() { var source = @"namespace A.$$"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer() { var source = @" namespace A.B { } namespace A.$$"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace() { var source = @" namespace A.B { } namespace A.$$;"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NestedWithPeer() { var source = @" namespace A { namespace B.C { } namespace B.$$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNested() { var source = @" namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem.Runtime { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnKeyword() { var source = @"name$$space System { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnNestedKeyword() { var source = @" namespace System { name$$space Runtime { } }"; await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace C.$$ namespace C.D1 { } } namespace B.C.D2 { } } namespace A.B.C.D3 { }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); // Ideally, all the D* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // D1 => A.B.C.C.?.D1 // D2 => A.B.B.C.D2 // D3 => A.A.B.C.D3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnderNamespace() { await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType1() { await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType2() { var content = @"namespace NS { class CL {} $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideProperty() { var content = @"class C { private string name; public string Name { set { name = $$"; await VerifyItemExistsAsync(content, @"value"); await VerifyItemExistsAsync(content, @"C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDot() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingAlias() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMember() { var content = @"class CL { $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMemberAccessibility() { var content = @"class CL { public $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BadStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameter() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameterList() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionTypePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StackAllocArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseTypeOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DeclarationStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VariableDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementNoToken() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldDeclaration() { var content = @"class CL { $$ i"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventFieldDeclaration() { var content = @"class CL { event $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclaration() { var content = @"class CL { explicit operator $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclarationNoToken() { var content = @"class CL { explicit $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PropertyDeclaration() { var content = @"class CL { $$ Prop {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventDeclaration() { var content = @"class CL { event $$ Event {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IndexerDeclaration() { var content = @"class CL { $$ this"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter() { var content = @"class CL { void Method($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayType() { var content = @"class CL { $$ ["; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PointerType() { var content = @"class CL { $$ *"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableType() { var content = @"class CL { $$ ?"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateDeclaration() { var content = @"class CL { delegate $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration() { var content = @"class CL { $$ M("; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OperatorDeclaration() { var content = @"class CL { $$ operator"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Argument() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseInPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LetClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OrderingExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SelectClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThrowStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System"); } [WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YieldReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LockStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EqualsValueClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementInitializersPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementConditionOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementIncrementorsPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhileStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayRankSpecifierSizesPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrefixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PostfixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenTruePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenFalsePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseInExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseLeftExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseRightExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhereClauseConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseGroupExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseByExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IfStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchLabelCase() { var content = @"switch(i) { case $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchPatternLabelCase() { var content = @"switch(i) { case $$ when"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionFirstBranch() { var content = @"i switch { $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionSecondBranch() { var content = @"i switch { 1 => true, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternFirstPosition() { var content = @"i is ($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternSecondPosition() { var content = @"i is (1, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternFirstPosition() { var content = @"i is { P: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternSecondPosition() { var content = @"i is { P1: 1, P2: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InitializerExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseList() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseAnotherWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause1() { await VerifyItemExistsAsync(@"class CL<T> where $$", @"T"); await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T"); await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause2() { await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause3() { await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1"); await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseListWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedName() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedNamespace() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedType() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstructorInitializer() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Checked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Unchecked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Locals() => await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameters() => await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AnonymousMethodDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommonTypesInNewExpressionContext() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionForUnboundTypes() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInTypeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInDefault() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInSizeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInGenericParameterList() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterNumericLiteral() { // NOTE: the Completion command handler will suppress this case if the user types '.', // but we still need to show members if the user specifically invokes statement completion here. await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterParenthesizedNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedNumericLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterArithmeticExpression() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals"); [WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceTypesAvailableInUsingAlias() => await VerifyItemExistsAsync(@"using S = System.$$", "String"); [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember1() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember2() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { this.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember3() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { base.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember1() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember2() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { B.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember3() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { A.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedInstanceAndStaticMembers() { var markup = @" class A { private static void HiddenStatic() { } protected static void GooStatic() { } private void HiddenInstance() { } protected void GooInstance() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "HiddenStatic"); await VerifyItemExistsAsync(markup, "GooStatic"); await VerifyItemIsAbsentAsync(markup, "HiddenInstance"); await VerifyItemExistsAsync(markup, "GooInstance"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer1() { var markup = @" class C { void M() { for (int i = 0; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer2() { var markup = @" class C { void M() { for (int i = 0; i < 10; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersInClass() { var markup = @" class C<T, R> { $$ } "; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(ref $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(out $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(in $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(ref String parameter) { M(ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(out String parameter) { M(out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(in String parameter) { M(in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefExpression_TypeAndVariable() { var markup = @" using System; class C { void M(String parameter) { ref var x = ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task AfterStaticLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { static $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("extern")] [InlineData("static extern")] [InlineData("extern static")] [InlineData("async")] [InlineData("static async")] [InlineData("async static")] [InlineData("unsafe")] [InlineData("static unsafe")] [InlineData("unsafe static")] [InlineData("async unsafe")] [InlineData("unsafe async")] [InlineData("unsafe extern")] [InlineData("extern unsafe")] [InlineData("extern unsafe async static")] public async Task AfterLocalFunction_TypeOnly(string keyword) { var markup = $@" using System; class C {{ void M(String parameter) {{ {keyword} $$ }} }} "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task AfterAsyncLocalFunctionWithTwoAsyncs() { var markup = @" using System; class C { void M(String parameter) { async async $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("void")] [InlineData("string")] [InlineData("String")] [InlineData("(int, int)")] [InlineData("async void")] [InlineData("async System.Threading.Tasks.Task")] [InlineData("int Function")] public async Task NotAfterReturnTypeInLocalFunction(string returnType) { var markup = @$" using System; class C {{ void M(String parameter) {{ static {returnType} $$ }} }} "; await VerifyItemIsAbsentAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref readonly $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType1() { var markup = @" class Q { $$ class R { } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType2() { var markup = @" class Q { class R { $$ } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType3() { var markup = @" class Q { class R { } $$ } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Regular() { var markup = @" class Q { class R { } } $$"; // At EOF // Top-level statements are not allowed to follow classes, but we still offer it in completion for a few // reasons: // // 1. The code is simpler // 2. It's a relatively rare coding practice to define types outside of namespaces // 3. It allows the compiler to produce a better error message when users type things in the wrong order await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Script() { var markup = @" class Q { class R { } } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType5() { var markup = @" class Q { class R { } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType6() { var markup = @" class Q { class R { $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenTypeAndLocal() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void goo() { int i = 5; i.$$ List<string> ml = new List<string>(); } }"; await VerifyItemExistsAsync(markup, "CompareTo"); } [WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType() { var markup = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { AwaitTest test = new AwaitTest(); test.Test1().Wait(); } } class AwaitTest { List<string> stringList = new List<string>(); public async Task<bool> Test1() { stringList.$$ await Test2(); return true; } public async Task<bool> Test2() { return true; } }"; await VerifyItemExistsAsync(markup, "Add"); } [WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterNewInScript() { var markup = @" using System; new $$"; await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodsInScript() { var markup = @" using System.Linq; var a = new int[] { 1, 2 }; a.$$"; await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionsInForLoopInitializer() { var markup = @" public class C { public void M() { int count = 0; for ($$ "; await VerifyItemExistsAsync(markup, "count"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression1() { var markup = @" public class C { public void M() { System.Func<int, int> f = arg => { arg = 2; return arg; }.$$ } } "; await VerifyItemIsAbsentAsync(markup, "ToString"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression2() { var markup = @" public class C { public void M() { ((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$ } } "; await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemExistsAsync(markup, "Invoke"); } [WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InMultiLineCommentAtEndOfFile() { var markup = @" using System; /*$$"; await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersAtEndOfFile() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Outer<T> { class Inner<U> { static void F(T t, U u) { return; } public static void F(T t) { Outer<$$"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForCase() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "case 0:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "default:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchPresentForDefault() { var markup = @" class Program { static void Main() { int x; switch (x) { default: goto $$"; await VerifyItemExistsAsync(markup, "default"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto1() { var markup = @" class Program { static void Main() { Goo: int Goo; goto $$"; await VerifyItemExistsAsync(markup, "Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto2() { var markup = @" class Program { static void Main() { Goo: int Goo; goto Goo $$"; await VerifyItemIsAbsentAsync(markup, "Goo"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeName() { var markup = @" using System; [$$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifier() { var markup = @" using System; [assembly:$$ "; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeList() { var markup = @" using System; [CLSCompliant, $$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameBeforeClass() { var markup = @" using System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifierBeforeClass() { var markup = @" using System; [assembly:$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeArgumentList() { var markup = @" using System; [CLSCompliant($$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInsideClass() { var markup = @" using System; class C { $$ }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName1() { var markup = @" using Alias = System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName2() { var markup = @" using Alias = Goo; namespace Goo { } [$$ class C { }"; await VerifyItemIsAbsentAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName3() { var markup = @" using Alias = Goo; namespace Goo { class A : System.Attribute { } } [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace() { var markup = @" namespace Test { class MyAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace2() { var markup = @" namespace Test { namespace Two { class MyAttribute : System.Attribute { } [Test.Two.$$ class Program { } } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task KeywordsUsedAsLocals() { var markup = @" class C { void M() { var error = 0; var method = 0; var @int = 0; Console.Write($$ } }"; // preprocessor keyword await VerifyItemExistsAsync(markup, "error"); await VerifyItemIsAbsentAsync(markup, "@error"); // contextual keyword await VerifyItemExistsAsync(markup, "method"); await VerifyItemIsAbsentAsync(markup, "@method"); // full keyword await VerifyItemExistsAsync(markup, "@int"); await VerifyItemIsAbsentAsync(markup, "int"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords1() { var markup = @" class C { void M() { var from = new[]{1,2,3}; var r = from x in $$ } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords2() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where $$ == @where.Length select @from; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords3() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where @from == @where.Length select $$; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAlias() { var markup = @" class MyAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() { var markup = @" class namespaceAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute1() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute2() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace2"); await VerifyItemExistsAsync(markup, "Namespace3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute3() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.$$]"; await VerifyItemExistsAsync(markup, "Namespace4"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute4() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.Namespace4.$$]"; await VerifyItemExistsAsync(markup, "Custom"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() { var markup = @" using Namespace1Alias = Namespace1; using Namespace2Alias = Namespace1.Namespace2; using Namespace3Alias = Namespace1.Namespace3; using Namespace4Alias = Namespace1.Namespace3.Namespace4; namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1Alias"); await VerifyItemIsAbsentAsync(markup, "Namespace2Alias"); await VerifyItemExistsAsync(markup, "Namespace3Alias"); await VerifyItemExistsAsync(markup, "Namespace4Alias"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithoutNestedAttribute() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } } } [$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace1"); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariableInQuerySelect() { var markup = @" using System.Linq; class P { void M() { var src = new string[] { ""Goo"", ""Bar"" }; var q = from x in src select x.$$"; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsPatternExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ 1"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchPatternCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$ when"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchGotoCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case MAX_SIZE: break; case GOO: goto case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInEnumMember() { var markup = @" class C { public const int GOO = 0; enum E { A = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute1() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage($$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute2() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(GOO, $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute3() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(validOn: $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute4() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(AllowMultiple = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInParameterDefaultValue() { var markup = @" class C { public const int GOO = 0; void M(int x = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstField() { var markup = @" class C { public const int GOO = 0; const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstLocal() { var markup = @" class C { public const int GOO = 0; void M() { const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1Overload() { var markup = @" class C { void M(int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2Overloads() { var markup = @" class C { void M(int i) { } void M(out int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1GenericOverload() { var markup = @" class C { void M<T>(T i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2GenericOverloads() { var markup = @" class C { void M<T>(int i) { } void M<T>(out int i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionNamedGenericType() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionParameter() { var markup = @" class C<T> { void M(T goo) { $$"; await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionGenericTypeParameter() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionAnonymousType() { var markup = @" class C { void M() { var a = new { }; $$ "; var expectedDescription = $@"({FeaturesResources.local_variable}) 'a a {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} new {{ }}"; await VerifyItemExistsAsync(markup, "a", expectedDescription); } [WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterNewInAnonymousType() { var markup = @" class Program { string field = 0; static void Main() { var an = new { new $$ }; } } "; await VerifyItemExistsAsync(markup, "Program"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticMethod() { var markup = @" class C { int x = 0; static void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticFieldInitializer() { var markup = @" class C { int x = 0; static int y = $$ } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticMethod() { var markup = @" class C { static int x = 0; static void M() { $$ } } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticFieldInitializer() { var markup = @" class C { static int x = 0; static int y = $$ } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { int i; class inner { void M() { $$ } } } "; await VerifyItemIsAbsentAsync(markup, "i"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { static int i; class inner { void M() { $$ } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyEnumMembersInEnumMemberAccess() { var markup = @" class C { enum x {a,b,c} void M() { x.$$ } } "; await VerifyItemExistsAsync(markup, "a"); await VerifyItemExistsAsync(markup, "b"); await VerifyItemExistsAsync(markup, "c"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoEnumMembersInEnumLocalAccess() { var markup = @" class C { enum x {a,b,c} void M() { var y = x.a; y.$$ } } "; await VerifyItemIsAbsentAsync(markup, "a"); await VerifyItemIsAbsentAsync(markup, "b"); await VerifyItemIsAbsentAsync(markup, "c"); await VerifyItemExistsAsync(markup, "Equals"); } [WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaParameterDot() { var markup = @" using System; using System.Linq; class A { public event Func<String, String> E; } class Program { static void Main(string[] args) { new A().E += ss => ss.$$ } } "; await VerifyItemExistsAsync(markup, "Substring"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAtRoot_Interactive() { await VerifyItemIsAbsentAsync( @"$$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterClass_Interactive() { await VerifyItemIsAbsentAsync( @"class C { } $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalStatement_Interactive() { await VerifyItemIsAbsentAsync( @"System.Console.WriteLine(); $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalVariableDeclaration_Interactive() { await VerifyItemIsAbsentAsync( @"int i = 0; $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInUsingAlias() { await VerifyItemIsAbsentAsync( @"using Goo = $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInEmptyStatement() { await VerifyItemIsAbsentAsync(AddInsideMethod( @"$$"), "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideSetter() { await VerifyItemExistsAsync( @"class C { int Goo { set { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideAdder() { await VerifyItemExistsAsync( @"class C { event int Goo { add { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideRemover() { await VerifyItemExistsAsync( @"class C { event int Goo { remove { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterDot() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { this.$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterArrow() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a->$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterColonColon() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a::$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInGetter() { await VerifyItemIsAbsentAsync( @"class C { int Goo { get { $$", "value"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterNullableTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkAndPartialIdentifierInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskAndPartialIdentifierInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* f$$", "goo"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterEventFieldDeclaredInSameType() { await VerifyItemExistsAsync( @"class C { public event System.EventHandler E; void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterFullEventDeclaredInSameType() { await VerifyItemIsAbsentAsync( @"class C { public event System.EventHandler E { add { } remove { } } void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterEventDeclaredInDifferentType() { await VerifyItemIsAbsentAsync( @"class C { void M() { System.Console.CancelKeyPress.$$", "Invoke"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotInObjectInitializerMemberContext() { await VerifyItemIsAbsentAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$", "x"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task AfterPointerMemberAccess() { await VerifyItemExistsAsync(@" struct MyStruct { public int MyField; } class Program { static unsafe void Main(string[] args) { MyStruct s = new MyStruct(); MyStruct* ptr = &s; ptr->$$ }}", "MyField"); } // After @ both X and XAttribute are legal. We think this is an edge case in the language and // are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed. [WorkItem(11931, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task VerbatimAttributes() { var code = @" using System; public class X : Attribute { } public class XAttribute : Attribute { } [@X$$] class Class3 { } "; await VerifyItemExistsAsync(code, "X"); await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute")); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; $$ } } ", "Console"); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for ($$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclaration() { // "int goo = goo = 1" is a legal declaration await VerifyItemExistsAsync(@" class Program { void M() { int goo = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclarator() { // "int bar = bar = 1" is legal in a declarator await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$, int baz = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclaration() { await VerifyItemIsAbsentAsync(@" class Program { void M() { $$ int goo = 0; } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclarator() { await VerifyItemIsAbsentAsync(@" class Program { void M() { int goo = $$, bar = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAfterDeclarator() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAsOutArgumentInInitializerExpression() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = Bar(out $$ } int Bar(out int x) { x = 3; return 5; } }", "goo"); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverriddenSymbolsFilteredFromCompletionList() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" public class B { public virtual void Goo(int original) { } } public class D : B { public override void Goo(int derived) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { C c = new C(); c.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Goo() { } } public class D : B { public void Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { $$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")] [WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")] [WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { public int Bar { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateNever() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAlways() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads1() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads2() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateNever() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAlways() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateNever() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAlways() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" public class Goo : Bar { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Bar { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAlways() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAdvanced() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Always() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Never() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 0, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestColorColor1() { var markup = @" class A { static void Goo() { } void Bar() { } static void Main() { A A = new A(); A.$$ } }"; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType1() { var markup = @" using System; class C { public static void Main() { $$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType2() { var markup = @" using System; class C { public static void Main() { C$$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "IndexProp", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } [WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDeclarationAmbiguity() { var markup = @" using System; class Program { void Main() { Environment.$$ var v; } }"; await VerifyItemExistsAsync(markup, "CommandLine"); } [WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldDeclarationAmbiguity() { var markup = @" using System; Environment.$$ var v; }"; await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCursorOnClassCloseBrace() { var markup = @" using System; class Outer { class Inner { } $$}"; await VerifyItemExistsAsync(markup, "Inner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync1() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync2() { var markup = @" using System.Threading.Tasks; class Program { public async T$$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterAsyncInMethodBody() { var markup = @" using System.Threading.Tasks; class Program { void goo() { var x = async $$ } }"; await VerifyItemIsAbsentAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable1() { var markup = @" class Program { void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable2() { var markup = @" class Program { async void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable1() { var markup = @" using System.Threading; using System.Threading.Tasks; class Program { async Task goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable2() { var markup = @" using System.Threading.Tasks; class Program { async Task<int> goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpression() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = await request.$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; // Nothing should be found: no awaiter for request. await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Task<Request>(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { $$ } }"; await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()"); } [WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersOnDottingIntoUnboundType() { var markup = @" class Program { RegistryKey goo; static void Main(string[] args) { goo.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeArgumentsInConstraintAfterBaselist() { var markup = @" public class Goo<T> : System.Object where $$ { }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDestructor() { var markup = @" class C { ~C() { $$ "; await VerifyItemIsAbsentAsync(markup, "Finalize"); } [WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodOnCovariantInterface() { var markup = @" class Schema<T> { } interface ISet<out T> { } static class SetMethods { public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { } } class Context { public ISet<T> Set<T>() { return null; } } class CustomSchema : Schema<int> { } class Program { static void Main(string[] args) { var set = new Context().Set<CustomSchema>(); set.$$ "; await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachInsideParentheses() { var markup = @" using System; class C { void M() { foreach($$) "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldInitializerInP2P() { var markup = @" class Class { int i = Consts.$$; }"; var referencedCode = @" public static class Consts { public const int C = 1; }"; await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false); } [WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowWithEqualsSign() { var markup = @" class c { public int value {set; get; }} class d { void goo() { c goo = new c { value$$= } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterThisDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { this.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { base.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInScriptContext() => await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script); [WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoNestedTypeWhenDisplayingInstance() { var markup = @" class C { class D { } void M2() { new C().$$ } }"; await VerifyItemIsAbsentAsync(markup, "D"); } [WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchVariableInExceptionFilter() { var markup = @" class C { void M() { try { } catch (System.Exception myExn) when ($$"; await VerifyItemExistsAsync(markup, "myExn"); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterExternAlias() { var markup = @" class C { void goo() { global::$$ } }"; await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExternAliasSuggested() { var markup = @" extern alias Bar; class C { void goo() { $$ } }"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassDestructor() { var markup = @" class C { class N { ~$$ } }"; await VerifyItemExistsAsync(markup, "N"); await VerifyItemIsAbsentAsync(markup, "C"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TildeOutsideClass() { var markup = @" class C { class N { } } ~$$"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "N"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StructDestructor() { var markup = @" struct C { ~$$ }"; await VerifyItemIsAbsentAsync(markup, "C"); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("record")] [InlineData("record class")] public async Task RecordDestructor(string record) { var markup = $@" {record} C {{ ~$$ }}"; await VerifyItemExistsAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RecordStructDestructor() { var markup = $@" record struct C {{ ~$$ }}"; await VerifyItemIsAbsentAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { int x; void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { $$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR class G { public void DoGStuff() {} } #endif void goo() { new G().$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { int xyz; $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { #if PROJ1 int xyz; #endif $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { LABEL: int xyz; goto $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.label}) LABEL"; await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] { 1, 2, 3 } select $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.range_variable}) ? y"; await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription); } [WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void Shared() { var x = GetThing(); x.$$ } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE public int x; #endif #if TWO public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({ FeaturesResources.field }) int C.x"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if TWO public int x; #endif #if ONE public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = "int C.x { get; set; }"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessWalkUp() { var markup = @" public class B { public A BA; public B BB; } class A { public A AA; public A AB; public int? x; public void goo() { A a = null; var q = a?.$$AB.BA.AB.BA; } }"; await VerifyItemExistsAsync(markup, "AA"); await VerifyItemExistsAsync(markup, "AB"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { A a = null; var q = a?.s?.$$; } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped2() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { var q = s?.$$i?.ToString(); } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt?.$$ } } "; await VerifyItemExistsAsync(markup, "Day"); await VerifyItemIsAbsentAsync(markup, "Value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableIsNotUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt.$$ } } "; await VerifyItemExistsAsync(markup, "Value"); await VerifyItemIsAbsentAsync(markup, "Day"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterConditionalIndexing() { var markup = @" public struct S { public int? i; } class A { public S[] s; public void goo() { A a = null; var q = a?.s?[$$; } }"; await VerifyItemExistsAsync(markup, "System"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses1() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.$$b?.c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses2() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.$$c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "c"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses3() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.c?.$$d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "d"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnSelf() { var markup = @"using System; [My] class X { [My$$] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnOuterType() { var markup = @"using System; [My] class Y { } [$$] class X { [My] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType() { var markup = @"abstract class Test { private int _field; public sealed class InnerTest : Test { public void SomeTest() { $$ } } }"; await VerifyItemExistsAsync(markup, "_field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType2() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { $$ // M recommended and accessible } class NN { void Test2() { // M inaccessible and not recommended } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType3() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN { void Test2() { $$ // M inaccessible and not recommended } } } }"; await VerifyItemIsAbsentAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType4() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN : N { void Test2() { $$ // M accessible and recommended. } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType5() { var markup = @" class D { public void Q() { } } class C<T> : D { class N { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "Q"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType6() { var markup = @" class Base<T> { public int X; } class Derived : Base<int> { class Nested { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "X"); } [WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoTypeParametersDefinedInCrefs() { var markup = @"using System; /// <see cref=""Program{T$$}""/> class Program<T> { }"; await VerifyItemIsAbsentAsync(markup, "T"); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList1() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList2() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<string,$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionInAliasedType() { var markup = @" using IAlias = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C { I$$ } "; await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinNameOf() { var markup = @" class C { void goo() { var x = nameof($$) } } "; await VerifyAnyItemExistsAsync(markup); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y1"); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y2"); } [WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteDeclarationExpressionType() { var markup = @" using System; class C { void goo() { var x = Console.$$ var y = 3; } } "; await VerifyItemExistsAsync(markup, "WriteLine"); } [WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticAndInstanceInNameOf() { var markup = @" using System; class C { class D { public int x; public static int y; } void goo() { var z = nameof(C.D.$$ } } "; await VerifyItemExistsAsync(markup, "x"); await VerifyItemExistsAsync(markup, "y"); } [WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForLocals() { var markup = @"class C { void M() { var x = nameof(T.z.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes2() { var markup = @"class C { void M() { var x = nameof(U.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes3() { var markup = @"class C { void M() { var x = nameof(N.$$) } } namespace N { public class U { public int nope; } } "; await VerifyItemExistsAsync(markup, "U"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes4() { var markup = @" using z = System; class C { void M() { var x = nameof(z.$$) } } "; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings1() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$ "; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings2() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$}""; } }"; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings3() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings4() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings5() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings6() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBeforeFirstStringHole() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBetweenStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task CompletionAfterTypeOfGetType() { await VerifyItemExistsAsync(AddInsideMethod( "typeof(int).GetType().$$"), "GUID"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives1() { var markup = @" using $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives2() { var markup = @" using N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives3() { var markup = @" using G = $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives4() { var markup = @" using G = N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives5() { var markup = @" using static $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives6() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates1() { var markup = @" using static $$ class A { } delegate void B(); namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates2() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } delegate void D(); namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces1() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } interface I { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces2() { var markup = @" using static $$ class A { } interface I { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods1() { var markup = @" using static A; using static B; static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods2() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods3() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods4() { var markup = @" using static N.A; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods5() { var markup = @" using static N.A; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods6() { var markup = @" using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods7() { var markup = @" using N; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$; } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinSameClassOfferedForCompletion() { var markup = @" public static class Test { static void TestB() { $$ } static void TestA(this string s) { } } "; await VerifyItemExistsAsync(markup, "TestA"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinParentClassOfferedForCompletion() { var markup = @" public static class Parent { static void TestA(this string s) { } static void TestC(string s) { } public static class Test { static void TestB() { $$ } } } "; await VerifyItemExistsAsync(markup, "TestA"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1() { var markup = @" using System; class C { void M(bool x) { try { } catch when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch when $$ "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when $$ "; await VerifyNoItemsExistAsync(markup); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause1() { var markup = @" class C { void M(bool x) { switch (1) { case 1 when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause2() { var markup = @" class C { void M(bool x) { switch (1) { case int i when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionContextCompletionWithinCast() { var markup = @" class Program { void M() { for (int i = 0; i < 5; i++) { var x = ($$) var y = 1; } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInPropertyInitializer() { var markup = @" class A { int abc; int B { get; } = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInPropertyInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInFieldLikeEventInitializer() { var markup = @" class A { Action abc; event Action B = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInFieldLikeEventInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldInitializer() { var markup = @" int aaa = 1; int bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldLikeEventInitializer() { var markup = @" Action aaa = null; event Action bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes1() { var markup = @" using A = System class C { A?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes2() { var markup = @" class C { System?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes3() { var markup = @" class C { System.Console?.$$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInIncompletePropertyDeclaration() { var markup = @" class Class1 { public string Property1 { get; set; } } class Class2 { public string Property { get { return this.Source.$$ public Class1 Source { get; set; } }"; await VerifyItemExistsAsync(markup, "Property1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionInShebangComments() { await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script); await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompoundNameTargetTypePreselection() { var markup = @" class Class1 { void goo() { int x = 3; string y = x.$$ } }"; await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer1() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer2() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { 1, $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer1() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer2() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = 1, Y = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElements() { var markup = @" class C { void goo() { var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9); t.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; await VerifyItemExistsAsync(markup, "Alice"); await VerifyItemExistsAsync(markup, "Bob"); await VerifyItemExistsAsync(markup, "CompareTo"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "GetType"); await VerifyItemExistsAsync(markup, "Item2"); await VerifyItemExistsAsync(markup, "ITEM3"); for (var i = 4; i <= 8; i++) { await VerifyItemExistsAsync(markup, "Item" + i); } await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemIsAbsentAsync(markup, "Item1"); await VerifyItemIsAbsentAsync(markup, "Item9"); await VerifyItemIsAbsentAsync(markup, "Rest"); await VerifyItemIsAbsentAsync(markup, "Item3"); } [WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementsCompletionOffMethodGroup() { var markup = @" class C { void goo() { new object().ToString.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; // should not crash await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task NoCompletionInLocalFuncGenericParamList() { var markup = @" class C { void M() { int Local<$$"; await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task CompletionForAwaitWithoutAsync() { var markup = @" class C { void M() { await Local<$$"; await VerifyAnyItemExistsAsync(markup); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel1() { await VerifyItemExistsAsync(@" class C { ($$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel2() { await VerifyItemExistsAsync(@" class C { ($$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel3() { await VerifyItemExistsAsync(@" class C { (C, $$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel4() { await VerifyItemExistsAsync(@" class C { (C, $$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInForeach() { await VerifyItemExistsAsync(@" class C { void M() { foreach ((C, $$ } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInParameterList() { await VerifyItemExistsAsync(@" class C { void M((C, $$) { } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInNameOf() { await VerifyItemExistsAsync(@" class C { void M() { var x = nameof((C, $$ } }", "C"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription() { await VerifyItemExistsAsync(@" class C { void M() { void Local() { } $$ } }", "Local", "void Local()"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription2() { await VerifyItemExistsAsync(@" using System; class C { class var { } void M() { Action<int> Local(string x, ref var @class, params Func<int, string> f) { return () => 0; } $$ } }", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)"); } [WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterDot() { var markup = @"namespace ConsoleApplication253 { class Program { static void Main(string[] args) { M(E.$$) } static void M(E e) { } } enum E { A, B, } } "; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup1() { var markup = @"namespace ConsoleApp { class Program { static void Main(string[] args) { Main.$$ } } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup2() { var markup = @"class C { void M<T>() {M<C>.$$ } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup3() { var markup = @"class C { void M() {M.$$} } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember() { var markup = @"public static class Extensions { public static T Get<T>(this object o) => $$} "; await VerifyItemExistsAsync(markup, "o"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task EnumConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Enum"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Delegate"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task MulticastDelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "MulticastDelegate"); } private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString) { var template = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ThenIncludeIntellisenseBug { class Program { static void Main(string[] args) { var registrations = new List<Registration>().AsQueryable(); var reg = registrations.Include(r => r.Activities).ThenInclude([1]); } } internal class Registration { public ICollection<Activity> Activities { get; set; } } public class Activity { public Task Task { get; set; } } public class Task { public string Name { get; set; } } public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity> { } public static class EntityFrameworkQuerybleExtensions { public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>( this IQueryable<TEntity> source, Expression<Func<TEntity, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } [2] } }"; return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenInclude() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoExpression() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgument() { var markup = CreateThenIncludeTestCode("0, b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentNoOverlap() { var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath, Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemIsAbsentAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeGenericAndNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<Registration, Activity> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<ICollection<Activity>, Activity> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Activity>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaWithOverloads() { var markup = @" using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ClassLibrary1 { class SomeItem { public string A; public int B; } class SomeCollection<T> : List<T> { public virtual SomeCollection<T> Include(string path) => null; } static class Extensions { public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path) => null; public static IList Include(this IList source, string path) => null; public static IList<T> Include<T>(this IList<T> source, string path) => null; } class Program { void M(SomeCollection<SomeItem> c) { var a = from m in c.Include(t => t.$$); } } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads2() { var markup = @" using System; class C { void M(Action<int> a) { } void M(string s) { } void Test() { M(p => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads3() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M((int p) => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads4() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M(p => p.$$); } }"; await VerifyItemExistsAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParameters() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new List<Product>(), arg => arg.$$); } static void Create<T>(List<T> list, Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1, Product2>(), arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads2() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1,Product2>(),arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } } class Product3 { public void MyProperty3() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); await VerifyItemExistsAsync(markup, "MyProperty3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClass() { var markup = @" using System; class Program<T> { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemIsAbsentAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType() { var markup = @" using System; class Program<T> where T : Product { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod() { var markup = @" using System; class Program { static void M() { Create(arg => arg.$$); } static void Create<T>(Action<T> expression) where T : Product { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x = 7, Action<string> y = null) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x, int z, Action<string> y) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive() { var markup = @" using System; static class CExtensions { public static void X(this C x, Action<string> y) { } } class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive() { var markup = @" using System; public static void X(this C x, Action<string> y) { } public class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithNonFunctionsAsArguments() { var markup = @" using System; class c { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> configure) { var builder = new Builder(); configure(builder); } } class Builder { public int Something { get; set; } }"; await VerifyItemExistsAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAsArguments() { var markup = @" using System; class Program { public delegate void Delegate1(Uri u); public delegate void Delegate2(Guid g); public void M(Delegate1 d) { } public void M(Delegate2 d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Uri await VerifyItemExistsAsync(markup, "AbsoluteUri"); await VerifyItemExistsAsync(markup, "Fragment"); await VerifyItemExistsAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments() { var markup = @" using System; class Program { public delegate void Delegate1<T1,T2>(T2 t2, T1 t1); public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1); public void M(Delegate1<Uri,Guid> d) { } public void M(Delegate2<Uri,Guid> d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Should not appear for Uri await VerifyItemIsAbsentAsync(markup, "AbsoluteUri"); await VerifyItemIsAbsentAsync(markup, "Fragment"); await VerifyItemIsAbsentAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsBeforeParams() { var markup = @" using System; class C { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "AnotherSomething"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "Something"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsInParams() { var markup = @" using System; class C { void M() { Goo(b0 => { }, b1 => {}, b2 => { b2.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "AnotherSomething"); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilterWithExperimentEnabled() { TargetTypedCompletionFilterFeatureFlag = true; var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestNoTargetTypeFilterWithExperimentDisabled() { TargetTypedCompletionFilterFeatureFlag = false; var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotOnObjectMembers() { TargetTypedCompletionFilterFeatureFlag = true; var markup = @"public class C { void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "GetHashCode", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotNamedTypes() { TargetTypedCompletionFilterFeatureFlag = true; var markup = @"public class C { void M(C c) { M($$); } }"; await VerifyItemExistsAsync( markup, "c", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter }); await VerifyItemExistsAsync( markup, "C", matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch() { var markup = @" public static class Ext { public static void DoSomething<T>(this T thing, string s) where T : class, I { } } public interface I { } public class C { public void M(string s) { this.$$ } }"; await VerifyItemExistsAsync(markup, "M"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>"); } [WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionInStaticMethod() { await VerifyItemExistsAsync(@" class C { static void M() { void Local() { } $$ } }", "Local"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")] public async Task NoItemWithEmptyDisplayName() { var markup = @" class C { static void M() { int$$ } } "; await VerifyItemIsAbsentAsync( markup, "", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter }); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar) { var markup = @" class Program { private void Bar() { F$$ } private void Foo(int i) { } private void Foo(int i, int c) { } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(){commitChar} }} private void Foo(int i) {{ }} private void Foo(int i, int c) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithSemicolonInNestedMethod(char commitChar) { var markup = @" class Program { private void Bar() { Foo(F$$); } private int Foo(int i) { return 1; } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(Foo(){commitChar}); }} private int Foo(int i) {{ return 1; }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar) { var markup = @" using System; class Program { private void Bar() { Bar2(F$$); } private void Foo() { } void Bar2(Action t) { } }"; var expected = $@" using System; class Program {{ private void Bar() {{ Bar2(Foo{commitChar}); }} private void Foo() {{ }} void Bar2(Action t) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar) { var markup = @" class Program { private static void Bar() { var o = new P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = new Program(){commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar) { var markup = @" class Program { private static void Bar() { var o = P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = Program{commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar) { var markup = @" using String2 = System.String; namespace Bar1 { class Program { private static void Bar() { var o = new S$$ } } }"; var expected = $@" using String2 = System.String; namespace Bar1 {{ class Program {{ private static void Bar() {{ var o = new String2(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionWithSemicolonUnderNameofContext() { var markup = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(B$$) } } }"; var expected = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(Bar;) } } }"; await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';'); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatchWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPropertyPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { public RankedMusicians R; void M(C m) { if (m is { R: RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ChildClassAfterPatternMatch() { var markup = @"namespace N { public class D { public class E { } } class C { void M(object m) { if (m is D.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "E"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpression() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpressionWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable() { var markup = @" public class C { [System.Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete() { var markup = @" public class C { [System.Obsolete] public void M() { } [System.Obsolete] public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreCustomObsoleteAttribute() { var markup = @" public class ObsoleteAttribute: System.Attribute { } public class C { [Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})"); } [InlineData("int", "")] [InlineData("int[]", "int a")] [Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList) { // Check the description displayed is based on symbol matches targeted type TargetTypedCompletionFilterFeatureFlag = true; var markup = $@"public class C {{ bool Bar(int a, int b) => false; int Bar() => 0; int[] Bar(int a) => null; bool N({targetType} x) => true; void M(C c) {{ N(c.$$); }} }}"; await VerifyItemExistsAsync( markup, "Bar", expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesNotSuggestedInDeclarationDeconstruction() { await VerifyItemIsAbsentAsync(@" class C { int M() { var (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { int y; (var x, $$) = (0, 0); } }", "y"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")] public async Task TestTypeParameterConstraintedToInterfaceWithStatics() { var source = @" interface I1 { static void M0(); static abstract void M1(); abstract static int P1 { get; set; } abstract static event System.Action E1; } interface I2 { static abstract void M2(); } class Test { void M<T>(T x) where T : I1, I2 { T.$$ } } "; await VerifyItemIsAbsentAsync(source, "M0"); await VerifyItemExistsAsync(source, "M1"); await VerifyItemExistsAsync(source, "M2"); await VerifyItemExistsAsync(source, "P1"); await VerifyItemExistsAsync(source, "E1"); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { [UseExportProvider] public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(SymbolCompletionProvider); [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFile(SourceCodeKind sourceCodeKind) { await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData(SourceCodeKind.Regular)] [InlineData(SourceCodeKind.Script)] public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind) { await VerifyItemExistsAsync(@"using System; $$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); await VerifyItemExistsAsync(@"using System; $$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashR() => await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterHashLoad() => await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirective() { await VerifyItemIsAbsentAsync(@"using $$", @"String"); await VerifyItemIsAbsentAsync(@"using $$ = System", @"System"); await VerifyItemExistsAsync(@"using $$", @"System"); await VerifyItemExistsAsync(@"using T = $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegion() { await VerifyItemIsAbsentAsync(@"class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InactiveRegionWithUsing() { await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { #if false $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ActiveRegionWithUsing() { await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"String"); await VerifyItemExistsAsync(@"using System; class C { #if true $$ #endif", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { // $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /* $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /* */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment1() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SingleLineXmlComment2() { await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); await VerifyItemIsAbsentAsync(@"using System; class C { /// $$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MultiLineXmlComment() { await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"String"); await VerifyItemIsAbsentAsync(@"using System; class C { /** $$ */", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); await VerifyItemExistsAsync(@"using System; class C { /** */$$ ", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenStringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StringLiteralInDirective() { await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OpenCharLiteral() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute1() { await VerifyItemExistsAsync(@"[assembly: $$]", @"System"); await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssemblyAttribute2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SystemAttributeIsNotAnAttribute() { var content = @"[$$] class CL {}"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeAttribute() { var content = @"[$$] class CL {}"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParamAttribute() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodAttribute() { var content = @"class CL { [$$] void Method() {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodTypeParamAttribute() { var content = @"class CL{ void Method<[A$$]T> () {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodParamAttribute() { var content = @"class CL{ void Method ([$$]int i) {} }"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_TopLevel() { var source = @"namespace $$ { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_EmptyNameSpan_Nested() { var source = @"; namespace System { namespace $$ { } }"; await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers() { var source = @"using System; namespace $$"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace() { var source = @"using System; namespace $$;"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_TopLevelWithPeer() { var source = @" namespace A { } namespace $$"; await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithNoPeers() { var source = @" namespace A { namespace $$ }"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_NestedWithPeer() { var source = @" namespace A { namespace B { } namespace $$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration() { var source = @"namespace N$$S"; await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNested() { var source = @" namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A { namespace $$ { namespace B { } } }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Unqualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace $$ namespace C1 { } } namespace B.C2 { } } namespace A.B.C3 { }"; // Ideally, all the C* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // C1 => A.B.?.C1 // C2 => A.B.B.C2 // C3 => A.A.B.C3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); // Because of the above, B does end up in the completion list // since A.B.B appears to be a peer of the new declaration await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NoPeers() { var source = @"namespace A.$$"; await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer() { var source = @" namespace A.B { } namespace A.$$"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace() { var source = @" namespace A.B { } namespace A.$$;"; await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_NestedWithPeer() { var source = @" namespace A { namespace B.C { } namespace B.$$ }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNested() { var source = @" namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer() { var source = @" namespace A.B { } namespace A.$$ { namespace B { } } "; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_InnerCompletionPosition() { var source = @"namespace Sys$$tem.Runtime { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnKeyword() { var source = @"name$$space System { }"; await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_OnNestedKeyword() { var source = @" namespace System { name$$space Runtime { } }"; await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceName_Qualified_IncompleteDeclaration() { var source = @" namespace A { namespace B { namespace C.$$ namespace C.D1 { } } namespace B.C.D2 { } } namespace A.B.C.D3 { }"; await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular); // Ideally, all the D* namespaces would be recommended but, because of how the parser // recovers from the missing braces, they end up with the following qualified names... // // D1 => A.B.C.C.?.D1 // D2 => A.B.B.C.D2 // D3 => A.A.B.C.D3 // // ...none of which are found by the current algorithm. await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnderNamespace() { await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType1() { await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"String"); await VerifyItemIsAbsentAsync(@"namespace NS { class CL {} $$", @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutsideOfType2() { var content = @"namespace NS { class CL {} $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideProperty() { var content = @"class C { private string name; public string Name { set { name = $$"; await VerifyItemExistsAsync(content, @"value"); await VerifyItemExistsAsync(content, @"C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDot() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingAlias() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMember() { var content = @"class CL { $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteMemberAccessibility() { var content = @"class CL { public $$ "; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BadStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameter() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeTypeParameterList() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionTypePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObjectCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StackAllocArrayCreationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseTypeOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DeclarationStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VariableDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementNoToken() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchDeclaration() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldDeclaration() { var content = @"class CL { $$ i"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventFieldDeclaration() { var content = @"class CL { event $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclaration() { var content = @"class CL { explicit operator $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConversionOperatorDeclarationNoToken() { var content = @"class CL { explicit $$"; await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PropertyDeclaration() { var content = @"class CL { $$ Prop {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EventDeclaration() { var content = @"class CL { event $$ Event {"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IndexerDeclaration() { var content = @"class CL { $$ this"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameter() { var content = @"class CL { void Method($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayType() { var content = @"class CL { $$ ["; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PointerType() { var content = @"class CL { $$ *"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableType() { var content = @"class CL { $$ ?"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DelegateDeclaration() { var content = @"class CL { delegate $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodDeclaration() { var content = @"class CL { $$ M("; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OperatorDeclaration() { var content = @"class CL { $$ operator"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParenthesizedExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Argument() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CastExpressionExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FromClauseInPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LetClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OrderingExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SelectClauseExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThrowStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System"); } [WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task YieldReturnStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStatementExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LockStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EqualsValueClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementInitializersPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementConditionOptPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForStatementIncrementorsPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhileStatementConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ArrayRankSpecifierSizesPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrefixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PostfixUnaryExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BinaryExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionLeftPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AssignmentExpressionRightPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenTruePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalExpressionWhenFalsePart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseInExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseLeftExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task JoinClauseRightExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WhereClauseConditionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseGroupExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GroupClauseByExpressionPart() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IfStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchStatement() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchLabelCase() { var content = @"switch(i) { case $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchPatternLabelCase() { var content = @"switch(i) { case $$ when"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionFirstBranch() { var content = @"i switch { $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task SwitchExpressionSecondBranch() { var content = @"i switch { 1 => true, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternFirstPosition() { var content = @"i is ($$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PositionalPatternSecondPosition() { var content = @"i is (1, $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternFirstPosition() { var content = @"i is { P: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")] public async Task PropertyPatternSecondPosition() { var content = @"i is { P1: 1, P2: $$"; await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InitializerExpression() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClause() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseList() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParameterConstraintClauseAnotherWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause1() { await VerifyItemExistsAsync(@"class CL<T> where $$", @"T"); await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T"); await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause2() { await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeSymbolOfTypeParameterConstraintClause3() { await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1"); await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseList2() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task BaseListWhere() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedName() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedNamespace() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AliasedType() => await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstructorInitializer() { await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String"); await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Typeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Sizeof2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default1() { await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String"); await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Default2() => await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Checked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x"); [WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Unchecked() => await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Locals() => await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Parameters() => await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args"); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55969")] [Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(55969, "https://github.com/dotnet/roslyn/issues/55969")] public async Task Parameters_TopLevelStatement_1() => await VerifyItemExistsAsync(@"$$", "args", sourceCodeKind: SourceCodeKind.Regular); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55969")] [Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(55969, "https://github.com/dotnet/roslyn/issues/55969")] public async Task Parameters_TopLevelStatement_2() => await VerifyItemExistsAsync( @"using System; Console.WriteLine(); $$", "args", sourceCodeKind: SourceCodeKind.Regular); [Fact(Skip = "https://github.com/dotnet/roslyn/issues/55969")] [Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(55969, "https://github.com/dotnet/roslyn/issues/55969")] public async Task Parameters_TopLevelStatement_3() => await VerifyItemExistsAsync( @"using System; $$", "args", sourceCodeKind: SourceCodeKind.Regular); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(55969, "https://github.com/dotnet/roslyn/issues/55969")] public async Task Parameters_TopLevelStatement_4() => await VerifyItemExistsAsync(@"string first = $$", "args", sourceCodeKind: SourceCodeKind.Regular); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LambdaDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AnonymousMethodDiscardParameters() => await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommonTypesInNewExpressionContext() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionForUnboundTypes() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInTypeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInDefault() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInSizeOf() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoParametersInGenericParameterList() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterNumericLiteral() { // NOTE: the Completion command handler will suppress this case if the user types '.', // but we still need to show members if the user specifically invokes statement completion here. await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersAfterParenthesizedNullLiteral() => await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedTrueLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedFalseLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedCharLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedVerbatimStringLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterParenthesizedNumericLiteral() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals"); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MembersAfterArithmeticExpression() => await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals"); [WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceTypesAvailableInUsingAlias() => await VerifyItemExistsAsync(@"using S = System.$$", "String"); [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember1() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember2() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { this.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedMember3() { var markup = @" class A { private void Hidden() { } protected void Goo() { } } class B : A { void Bar() { base.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember1() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember2() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { B.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedStaticMember3() { var markup = @" class A { private static void Hidden() { } protected static void Goo() { } } class B : A { void Bar() { A.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Hidden"); await VerifyItemExistsAsync(markup, "Goo"); } [WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedInstanceAndStaticMembers() { var markup = @" class A { private static void HiddenStatic() { } protected static void GooStatic() { } private void HiddenInstance() { } protected void GooInstance() { } } class B : A { void Bar() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "HiddenStatic"); await VerifyItemExistsAsync(markup, "GooStatic"); await VerifyItemIsAbsentAsync(markup, "HiddenInstance"); await VerifyItemExistsAsync(markup, "GooInstance"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer1() { var markup = @" class C { void M() { for (int i = 0; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForLoopIndexer2() { var markup = @" class C { void M() { for (int i = 0; i < 10; $$ "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "Dispose"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType1() { var markup = @" class C { void M() { System.IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType2() { var markup = @" class C { void M() { (System.IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType3() { var markup = @" using System; class C { void M() { IDisposable.$$ "; await VerifyItemExistsAsync(markup, "ReferenceEquals"); } [WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersAfterType4() { var markup = @" using System; class C { void M() { (IDisposable).$$ "; await VerifyItemIsAbsentAsync(markup, "ReferenceEquals"); } [WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersInClass() { var markup = @" class C<T, R> { $$ } "; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInLambda_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { Func<int, int> f = (in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(ref $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(out $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInMethodDeclaration_TypeOnly() { var markup = @" using System; class C { String field; void M(in $$) { } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(ref String parameter) { M(ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterOutInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(out String parameter) { M(out $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")] public async Task AfterInInInvocation_TypeAndVariable() { var markup = @" using System; class C { void M(in String parameter) { M(in $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefExpression_TypeAndVariable() { var markup = @" using System; class C { void M(String parameter) { ref var x = ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemExistsAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInStatementContext_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalDeclaration_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int local; } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterRefReadonlyLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { ref readonly $$ int Function(); } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task AfterStaticLocalFunction_TypeOnly() { var markup = @" using System; class C { void M(String parameter) { static $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("extern")] [InlineData("static extern")] [InlineData("extern static")] [InlineData("async")] [InlineData("static async")] [InlineData("async static")] [InlineData("unsafe")] [InlineData("static unsafe")] [InlineData("unsafe static")] [InlineData("async unsafe")] [InlineData("unsafe async")] [InlineData("unsafe extern")] [InlineData("extern unsafe")] [InlineData("extern unsafe async static")] public async Task AfterLocalFunction_TypeOnly(string keyword) { var markup = $@" using System; class C {{ void M(String parameter) {{ {keyword} $$ }} }} "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] public async Task AfterAsyncLocalFunctionWithTwoAsyncs() { var markup = @" using System; class C { void M(String parameter) { async async $$ } } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("void")] [InlineData("string")] [InlineData("String")] [InlineData("(int, int)")] [InlineData("async void")] [InlineData("async System.Threading.Tasks.Task")] [InlineData("int Function")] public async Task NotAfterReturnTypeInLocalFunction(string returnType) { var markup = @$" using System; class C {{ void M(String parameter) {{ static {returnType} $$ }} }} "; await VerifyItemIsAbsentAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "parameter"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")] public async Task AfterRefReadonlyInMemberContext_TypeOnly() { var markup = @" using System; class C { String field; ref readonly $$ } "; await VerifyItemExistsAsync(markup, "String"); await VerifyItemIsAbsentAsync(markup, "field"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType1() { var markup = @" class Q { $$ class R { } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType2() { var markup = @" class Q { class R { $$ } } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType3() { var markup = @" class Q { class R { } $$ } "; await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Regular() { var markup = @" class Q { class R { } } $$"; // At EOF // Top-level statements are not allowed to follow classes, but we still offer it in completion for a few // reasons: // // 1. The code is simpler // 2. It's a relatively rare coding practice to define types outside of namespaces // 3. It allows the compiler to produce a better error message when users type things in the wrong order await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType4_Script() { var markup = @" class Q { class R { } } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType5() { var markup = @" class Q { class R { } $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedType6() { var markup = @" class Q { class R { $$"; // At EOF await VerifyItemExistsAsync(markup, "Q"); await VerifyItemExistsAsync(markup, "R"); } [WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenTypeAndLocal() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Program { public void goo() { int i = 5; i.$$ List<string> ml = new List<string>(); } }"; await VerifyItemExistsAsync(markup, "CompareTo"); } [WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType() { var markup = @" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main(string[] args) { AwaitTest test = new AwaitTest(); test.Test1().Wait(); } } class AwaitTest { List<string> stringList = new List<string>(); public async Task<bool> Test1() { stringList.$$ await Test2(); return true; } public async Task<bool> Test2() { return true; } }"; await VerifyItemExistsAsync(markup, "Add"); } [WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterNewInScript() { var markup = @" using System; new $$"; await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodsInScript() { var markup = @" using System.Linq; var a = new int[] { 1, 2 }; a.$$"; await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionsInForLoopInitializer() { var markup = @" public class C { public void M() { int count = 0; for ($$ "; await VerifyItemExistsAsync(markup, "count"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression1() { var markup = @" public class C { public void M() { System.Func<int, int> f = arg => { arg = 2; return arg; }.$$ } } "; await VerifyItemIsAbsentAsync(markup, "ToString"); } [WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaExpression2() { var markup = @" public class C { public void M() { ((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$ } } "; await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemExistsAsync(markup, "Invoke"); } [WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InMultiLineCommentAtEndOfFile() { var markup = @" using System; /*$$"; await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeParametersAtEndOfFile() { var markup = @" using System; using System.Collections.Generic; using System.Linq; class Outer<T> { class Inner<U> { static void F(T t, U u) { return; } public static void F(T t) { Outer<$$"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForCase() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "case 0:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent() { var markup = @" class Program { static void Main() { int x; switch (x) { case 0: goto $$"; await VerifyItemIsAbsentAsync(markup, "default:"); } [WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelInCaseSwitchPresentForDefault() { var markup = @" class Program { static void Main() { int x; switch (x) { default: goto $$"; await VerifyItemExistsAsync(markup, "default"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto1() { var markup = @" class Program { static void Main() { Goo: int Goo; goto $$"; await VerifyItemExistsAsync(markup, "Goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelAfterGoto2() { var markup = @" class Program { static void Main() { Goo: int Goo; goto Goo $$"; await VerifyItemIsAbsentAsync(markup, "Goo"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeName() { var markup = @" using System; [$$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifier() { var markup = @" using System; [assembly:$$ "; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeList() { var markup = @" using System; [CLSCompliant, $$"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameBeforeClass() { var markup = @" using System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterSpecifierBeforeClass() { var markup = @" using System; [assembly:$$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliant"); await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInAttributeArgumentList() { var markup = @" using System; [CLSCompliant($$ class C { }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameInsideClass() { var markup = @" using System; class C { $$ }"; await VerifyItemExistsAsync(markup, "CLSCompliantAttribute"); await VerifyItemIsAbsentAsync(markup, "CLSCompliant"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName1() { var markup = @" using Alias = System; [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName2() { var markup = @" using Alias = Goo; namespace Goo { } [$$ class C { }"; await VerifyItemIsAbsentAsync(markup, "Alias"); } [WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NamespaceAliasInAttributeName3() { var markup = @" using Alias = Goo; namespace Goo { class A : System.Attribute { } } [$$ class C { }"; await VerifyItemExistsAsync(markup, "Alias"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace() { var markup = @" namespace Test { class MyAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespace2() { var markup = @" namespace Test { namespace Two { class MyAttribute : System.Attribute { } [Test.Two.$$ class Program { } } }"; await VerifyItemExistsAsync(markup, "My"); await VerifyItemIsAbsentAsync(markup, "MyAttribute"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword() { var markup = @" namespace Test { class namespaceAttribute : System.Attribute { } [Test.$$ class Program { } }"; await VerifyItemExistsAsync(markup, "namespaceAttribute"); await VerifyItemIsAbsentAsync(markup, "namespace"); await VerifyItemIsAbsentAsync(markup, "@namespace"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task KeywordsUsedAsLocals() { var markup = @" class C { void M() { var error = 0; var method = 0; var @int = 0; Console.Write($$ } }"; // preprocessor keyword await VerifyItemExistsAsync(markup, "error"); await VerifyItemIsAbsentAsync(markup, "@error"); // contextual keyword await VerifyItemExistsAsync(markup, "method"); await VerifyItemIsAbsentAsync(markup, "@method"); // full keyword await VerifyItemExistsAsync(markup, "@int"); await VerifyItemIsAbsentAsync(markup, "int"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords1() { var markup = @" class C { void M() { var from = new[]{1,2,3}; var r = from x in $$ } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords2() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where $$ == @where.Length select @from; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task QueryContextualKeywords3() { var markup = @" class C { void M() { var where = new[] { 1, 2, 3 }; var x = from @from in @where where @from == @where.Length select $$; } }"; await VerifyItemExistsAsync(markup, "@from"); await VerifyItemIsAbsentAsync(markup, "from"); await VerifyItemExistsAsync(markup, "@where"); await VerifyItemIsAbsentAsync(markup, "where"); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAlias() { var markup = @" class MyAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular); } [Fact] [WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword() { var markup = @" class namespaceAttribute : System.Attribute { } [global::$$ class Program { }"; await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular); await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute1() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute2() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace2"); await VerifyItemExistsAsync(markup, "Namespace3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute3() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.$$]"; await VerifyItemExistsAsync(markup, "Namespace4"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute4() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [Namespace1.Namespace3.Namespace4.$$]"; await VerifyItemExistsAsync(markup, "Custom"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias() { var markup = @" using Namespace1Alias = Namespace1; using Namespace2Alias = Namespace1.Namespace2; using Namespace3Alias = Namespace1.Namespace3; using Namespace4Alias = Namespace1.Namespace3.Namespace4; namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } } } [$$]"; await VerifyItemExistsAsync(markup, "Namespace1Alias"); await VerifyItemIsAbsentAsync(markup, "Namespace2Alias"); await VerifyItemExistsAsync(markup, "Namespace3Alias"); await VerifyItemExistsAsync(markup, "Namespace4Alias"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AttributeSearch_NamespaceWithoutNestedAttribute() { var markup = @" namespace Namespace1 { namespace Namespace2 { class NonAttribute { } } namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } } } [$$]"; await VerifyItemIsAbsentAsync(markup, "Namespace1"); } [WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariableInQuerySelect() { var markup = @" using System.Linq; class P { void M() { var src = new string[] { ""Goo"", ""Bar"" }; var q = from x in src select x.$$"; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInIsPatternExpression() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; if (i is $$ 1"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchPatternCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case $$ when"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInSwitchGotoCase() { var markup = @" class C { public const int MAX_SIZE = 10; void M() { int i = 10; switch (i) { case MAX_SIZE: break; case GOO: goto case $$"; await VerifyItemExistsAsync(markup, "MAX_SIZE"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInEnumMember() { var markup = @" class C { public const int GOO = 0; enum E { A = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute1() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage($$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute2() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(GOO, $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute3() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(validOn: $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInAttribute4() { var markup = @" class C { public const int GOO = 0; [System.AttributeUsage(AllowMultiple = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInParameterDefaultValue() { var markup = @" class C { public const int GOO = 0; void M(int x = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstField() { var markup = @" class C { public const int GOO = 0; const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConstantsInConstLocal() { var markup = @" class C { public const int GOO = 0; void M() { const int BAR = $$"; await VerifyItemExistsAsync(markup, "GOO"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1Overload() { var markup = @" class C { void M(int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2Overloads() { var markup = @" class C { void M(int i) { } void M(out int i) { } void M() { $$"; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 2 {FeaturesResources.overloads_})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith1GenericOverload() { var markup = @" class C { void M<T>(T i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ 1 {FeaturesResources.generic_overload})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionWith2GenericOverloads() { var markup = @" class C { void M<T>(int i) { } void M<T>(out int i) { } void M<T>() { $$"; await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ 2 {FeaturesResources.generic_overloads})"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionNamedGenericType() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionParameter() { var markup = @" class C<T> { void M(T goo) { $$"; await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionGenericTypeParameter() { var markup = @" class C<T> { void M() { $$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionAnonymousType() { var markup = @" class C { void M() { var a = new { }; $$ "; var expectedDescription = $@"({FeaturesResources.local_variable}) 'a a {FeaturesResources.Types_colon} 'a {FeaturesResources.is_} new {{ }}"; await VerifyItemExistsAsync(markup, "a", expectedDescription); } [WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterNewInAnonymousType() { var markup = @" class Program { string field = 0; static void Main() { var an = new { new $$ }; } } "; await VerifyItemExistsAsync(markup, "Program"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticMethod() { var markup = @" class C { int x = 0; static void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsInStaticFieldInitializer() { var markup = @" class C { int x = 0; static int y = $$ } "; await VerifyItemIsAbsentAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticMethod() { var markup = @" class C { static int x = 0; static void M() { $$ } } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsInStaticFieldInitializer() { var markup = @" class C { static int x = 0; static int y = $$ } "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { int i; class inner { void M() { $$ } } } "; await VerifyItemIsAbsentAsync(markup, "i"); } [WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticFieldsFromOuterClassInInstanceMethod() { var markup = @" class outer { static int i; class inner { void M() { $$ } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OnlyEnumMembersInEnumMemberAccess() { var markup = @" class C { enum x {a,b,c} void M() { x.$$ } } "; await VerifyItemExistsAsync(markup, "a"); await VerifyItemExistsAsync(markup, "b"); await VerifyItemExistsAsync(markup, "c"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoEnumMembersInEnumLocalAccess() { var markup = @" class C { enum x {a,b,c} void M() { var y = x.a; y.$$ } } "; await VerifyItemIsAbsentAsync(markup, "a"); await VerifyItemIsAbsentAsync(markup, "b"); await VerifyItemIsAbsentAsync(markup, "c"); await VerifyItemExistsAsync(markup, "Equals"); } [WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterLambdaParameterDot() { var markup = @" using System; using System.Linq; class A { public event Func<String, String> E; } class Program { static void Main(string[] args) { new A().E += ss => ss.$$ } } "; await VerifyItemExistsAsync(markup, "Substring"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAtRoot_Interactive() { await VerifyItemIsAbsentAsync( @"$$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterClass_Interactive() { await VerifyItemIsAbsentAsync( @"class C { } $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalStatement_Interactive() { await VerifyItemIsAbsentAsync( @"System.Console.WriteLine(); $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterGlobalVariableDeclaration_Interactive() { await VerifyItemIsAbsentAsync( @"int i = 0; $$", "value", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInUsingAlias() { await VerifyItemIsAbsentAsync( @"using Goo = $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInEmptyStatement() { await VerifyItemIsAbsentAsync(AddInsideMethod( @"$$"), "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideSetter() { await VerifyItemExistsAsync( @"class C { int Goo { set { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideAdder() { await VerifyItemExistsAsync( @"class C { event int Goo { add { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueInsideRemover() { await VerifyItemExistsAsync( @"class C { event int Goo { remove { $$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterDot() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { this.$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterArrow() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a->$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotAfterColonColon() { await VerifyItemIsAbsentAsync( @"class C { int Goo { set { a::$$", "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ValueNotInGetter() { await VerifyItemIsAbsentAsync( @"class C { int Goo { get { $$", "value"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterNullableTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterNullableTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterQuestionMarkAndPartialIdentifierInConditional() { await VerifyItemExistsAsync( @"class C { void M() { bool b = false; int goo = 0; b? f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerType() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAlias() { await VerifyItemIsAbsentAsync( @"using A = System.Int32; class C { void M() { int goo = 0; A* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterPointerTypeAndPartialIdentifier() { await VerifyItemIsAbsentAsync( @"class C { void M() { int goo = 0; C* f$$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* $$", "goo"); } [WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsteriskAndPartialIdentifierInMultiplication() { await VerifyItemExistsAsync( @"class C { void M() { int i = 0; int goo = 0; i* f$$", "goo"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterEventFieldDeclaredInSameType() { await VerifyItemExistsAsync( @"class C { public event System.EventHandler E; void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterFullEventDeclaredInSameType() { await VerifyItemIsAbsentAsync( @"class C { public event System.EventHandler E { add { } remove { } } void M() { E.$$", "Invoke"); } [WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterEventDeclaredInDifferentType() { await VerifyItemIsAbsentAsync( @"class C { void M() { System.Console.CancelKeyPress.$$", "Invoke"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotInObjectInitializerMemberContext() { await VerifyItemIsAbsentAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$", "x"); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task AfterPointerMemberAccess() { await VerifyItemExistsAsync(@" struct MyStruct { public int MyField; } class Program { static unsafe void Main(string[] args) { MyStruct s = new MyStruct(); MyStruct* ptr = &s; ptr->$$ }}", "MyField"); } // After @ both X and XAttribute are legal. We think this is an edge case in the language and // are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed. [WorkItem(11931, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task VerbatimAttributes() { var code = @" using System; public class X : Attribute { } public class XAttribute : Attribute { } [@X$$] class Class3 { } "; await VerifyItemExistsAsync(code, "X"); await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute")); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; $$ } } ", "Console"); } [WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopIncrementor2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (; ; Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer1() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for ($$ } } ", "Console"); } [WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task InForLoopInitializer2() { await VerifyItemExistsAsync(@" using System; class Program { static void Main() { for (Console.WriteLine(), $$ } } ", "Console"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclaration() { // "int goo = goo = 1" is a legal declaration await VerifyItemExistsAsync(@" class Program { void M() { int goo = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableInItsDeclarator() { // "int bar = bar = 1" is legal in a declarator await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$, int baz = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclaration() { await VerifyItemIsAbsentAsync(@" class Program { void M() { $$ int goo = 0; } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableNotBeforeDeclarator() { await VerifyItemIsAbsentAsync(@" class Program { void M() { int goo = $$, bar = 0; } }", "bar"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAfterDeclarator() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = 0, int bar = $$ } }", "goo"); } [WorkItem(10572, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalVariableAsOutArgumentInInitializerExpression() { await VerifyItemExistsAsync(@" class Program { void M() { int goo = Bar(out $$ } int Bar(out int x) { x = 3; return 5; } }", "goo"); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_BrowsableStateAdvanced() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever() { var markup = @" class Program { void M() { Goo.$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x, int y) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Bar(int x) { } } public static class GooExtensions { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public static void Bar(this Goo goo, int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OverriddenSymbolsFilteredFromCompletionList() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" public class B { public virtual void Goo(int original) { } } public class D : B { public override void Goo(int derived) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass() { var markup = @" class Program { void M() { C c = new C(); c.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class C { public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass() { var markup = @" class Program { void M() { D d = new D(); d.$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public class B { public void Goo() { } } public class D : B { public void Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass() { var markup = @" class Program : B { void M() { $$ } }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var ci = new C<int>(); ci.$$ } }"; var referencedCode = @" public class C<T> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(int i) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 2, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever() { var markup = @" class Program { void M() { var cii = new C<int, int>(); cii.$$ } }"; var referencedCode = @" public class C<T, U> { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(T t) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public void Goo(U u) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 2, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Field_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")] [WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")] [WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateNever() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { public int Bar { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] get { return 5; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] set { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAlways() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Property_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public int Bar {get; set;} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateNever() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAlways() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public Goo() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads1() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Constructor_MixedOverloads2() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" public class Goo { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo() { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public Goo(int x) { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateNever() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAlways() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Event_BrowsableStateAdvanced() { var markup = @" class Program { void M() { new C().$$ } }"; var referencedCode = @" public delegate void Handler(); public class C { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public event Handler Changed; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Changed", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateNever() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAlways() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced() { var markup = @" class Program { public event $$ }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public delegate void Handler();"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Handler", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing() { var markup = @" class Program { void M() { using (var x = new NS.$$ } }"; var referencedCode = @" namespace NS { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class Goo : System.IDisposable { public void Dispose() { } } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" public class Goo : Bar { } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class Bar { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public struct Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateNever() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAlways() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Enum_BrowsableStateAdvanced() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public enum Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal() { var markup = @" class Program { public void M() { $$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom() { var markup = @" class Program : $$ { }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public interface Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Always() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_CrossLanguage_CStoVB_Never() { var markup = @" class Program { void M() { $$ } }"; var referencedCode = @" <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Class Goo End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 0, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic, hideAdvancedMembers: false); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new $$ } }"; var referencedCode = @" [System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))] public class Goo { }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))] public void Bar() { } }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor() { var markup = @" class Program { void M() { new Goo().$$ } }"; var referencedCode = @" public class Goo { [System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))] public int bar; }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "bar", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 0, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestColorColor1() { var markup = @" class A { static void Goo() { } void Bar() { } static void Main() { A A = new A(); A.$$ } }"; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType1() { var markup = @" using System; class C { public static void Main() { $$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestLaterLocalHidesType2() { var markup = @" using System; class C { public static void Main() { C$$ Console.WriteLine(); } }"; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestIndexedProperty() { var markup = @"class Program { void M() { CCC c = new CCC(); c.$$ } }"; // Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types. var referencedCode = @"Imports System.Runtime.InteropServices <ComImport()> <GuidAttribute(CCC.ClassId)> Public Class CCC #Region ""COM GUIDs"" Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0"" Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6"" Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb"" # End Region ''' <summary> ''' An index property from VB ''' </summary> ''' <param name=""p1"">p1 is an integer index</param> ''' <returns>A string</returns> Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "IndexProp", expectedSymbolsSameSolution: 1, expectedSymbolsMetadataReference: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.VisualBasic); } [WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestDeclarationAmbiguity() { var markup = @" using System; class Program { void Main() { Environment.$$ var v; } }"; await VerifyItemExistsAsync(markup, "CommandLine"); } [WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldDeclarationAmbiguity() { var markup = @" using System; Environment.$$ var v; }"; await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestCursorOnClassCloseBrace() { var markup = @" using System; class Outer { class Inner { } $$}"; await VerifyItemExistsAsync(markup, "Inner"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync1() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsync2() { var markup = @" using System.Threading.Tasks; class Program { public async T$$ }"; await VerifyItemExistsAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterAsyncInMethodBody() { var markup = @" using System.Threading.Tasks; class Program { void goo() { var x = async $$ } }"; await VerifyItemIsAbsentAsync(markup, "Task"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable1() { var markup = @" class Program { void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAwaitable2() { var markup = @" class Program { async void goo() { $$ } }"; await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable1() { var markup = @" using System.Threading; using System.Threading.Tasks; class Program { async Task goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task Awaitable2() { var markup = @" using System.Threading.Tasks; class Program { async Task<int> goo() { $$ } }"; var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()"; await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpression() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = await request.$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Request(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; // Nothing should be found: no awaiter for request. await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses() { var markup = @" using System.IO; using System.Threading.Tasks; namespace N { class C { async Task M() { var request = new Task<Request>(); var m = (await request).$$.ReadAsStreamAsync(); } } class Request { public Task<Stream> ReadAsStreamAsync() => null; } }"; await VerifyItemIsAbsentAsync(markup, "Result"); await VerifyItemExistsAsync(markup, "ReadAsStreamAsync"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteItem() { var markup = @" using System; class Program { [Obsolete] public void goo() { $$ } }"; await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()"); } [WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoMembersOnDottingIntoUnboundType() { var markup = @" class Program { RegistryKey goo; static void Main(string[] args) { goo.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TypeArgumentsInConstraintAfterBaselist() { var markup = @" public class Goo<T> : System.Object where $$ { }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoDestructor() { var markup = @" class C { ~C() { $$ "; await VerifyItemIsAbsentAsync(markup, "Finalize"); } [WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodOnCovariantInterface() { var markup = @" class Schema<T> { } interface ISet<out T> { } static class SetMethods { public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { } } class Context { public ISet<T> Set<T>() { return null; } } class CustomSchema : Schema<int> { } class Program { static void Main(string[] args) { var set = new Context().Set<CustomSchema>(); set.$$ "; await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ForEachInsideParentheses() { var markup = @" using System; class C { void M() { foreach($$) "; await VerifyItemExistsAsync(markup, "String"); } [WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestFieldInitializerInP2P() { var markup = @" class Class { int i = Consts.$$; }"; var referencedCode = @" public static class Consts { public const int C = 1; }"; await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false); } [WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowWithEqualsSign() { var markup = @" class c { public int value {set; get; }} class d { void goo() { c goo = new c { value$$= } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterThisDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { this.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInStaticContext() { var markup = @" class C { void M1() { } static void M2() { base.$$ } }"; await VerifyNoItemsExistAsync(markup); } [WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NothingAfterBaseDotInScriptContext() => await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script); [WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoNestedTypeWhenDisplayingInstance() { var markup = @" class C { class D { } void M2() { new C().$$ } }"; await VerifyItemIsAbsentAsync(markup, "D"); } [WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CatchVariableInExceptionFilter() { var markup = @" class C { void M() { try { } catch (System.Exception myExn) when ($$"; await VerifyItemExistsAsync(markup, "myExn"); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterExternAlias() { var markup = @" class C { void goo() { global::$$ } }"; await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true); } [WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExternAliasSuggested() { var markup = @" extern alias Bar; class C { void goo() { $$ } }"; await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ClassDestructor() { var markup = @" class C { class N { ~$$ } }"; await VerifyItemExistsAsync(markup, "N"); await VerifyItemIsAbsentAsync(markup, "C"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")] public async Task TildeOutsideClass() { var markup = @" class C { class N { } } ~$$"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "N"); } [WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StructDestructor() { var markup = @" struct C { ~$$ }"; await VerifyItemIsAbsentAsync(markup, "C"); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData("record")] [InlineData("record class")] public async Task RecordDestructor(string record) { var markup = $@" {record} C {{ ~$$ }}"; await VerifyItemExistsAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RecordStructDestructor() { var markup = $@" record struct C {{ ~$$ }}"; await VerifyItemIsAbsentAsync(markup, "C"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldAvailableInBothLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { int x; void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FieldUnavailableInTwoLinkedFiles() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif void goo() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR void goo() { $$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO int x; #endif #if BAR class G { public void DoGStuff() {} } #endif void goo() { new G().$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { int xyz; $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LocalWarningInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { #if PROJ1 int xyz; #endif $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}"; await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LabelsValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void M() { LABEL: int xyz; goto $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.label}) LABEL"; await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription); } [WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RangeVariablesValidInLinkedDocuments() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ using System.Linq; class C { void M() { var x = from y in new[] { 1, 2, 3 } select $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({FeaturesResources.range_variable}) ? y"; await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription); } [WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif #if TWO void Do(string x){} #endif void Shared() { $$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void C.Do(int x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE void Do(int x){} #endif void Shared() { this.$$ } } public static class Extensions { #if TWO public static void Do (this C c, string x) { } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloadDifferencesIgnored_ContainingType() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { void Shared() { var x = GetThing(); x.$$ } #if ONE private Methods1 GetThing() { return new Methods1(); } #endif #if TWO private Methods2 GetThing() { return new Methods2(); } #endif } #if ONE public class Methods1 { public void Do(string x) { } } #endif #if TWO public class Methods2 { public void Do(string x) { } } #endif ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"void Methods1.Do(string x)"; await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if ONE public int x; #endif #if TWO public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = $"({ FeaturesResources.field }) int C.x"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if TWO public int x; #endif #if ONE public int x {get; set;} #endif void goo() { x$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; var expectedDescription = "int C.x { get; set; }"; await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessWalkUp() { var markup = @" public class B { public A BA; public B BB; } class A { public A AA; public A AB; public int? x; public void goo() { A a = null; var q = a?.$$AB.BA.AB.BA; } }"; await VerifyItemExistsAsync(markup, "AA"); await VerifyItemExistsAsync(markup, "AB"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { A a = null; var q = a?.s?.$$; } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrapped2() { var markup = @" public struct S { public int? i; } class A { public S? s; public void goo() { var q = s?.$$i?.ToString(); } }"; await VerifyItemExistsAsync(markup, "i"); await VerifyItemIsAbsentAsync(markup, "value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ConditionalAccessNullableIsUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt?.$$ } } "; await VerifyItemExistsAsync(markup, "Day"); await VerifyItemIsAbsentAsync(markup, "Value"); } [WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableIsNotUnwrappedOnParameter() { var markup = @" class A { void M(System.DateTime? dt) { dt.$$ } } "; await VerifyItemExistsAsync(markup, "Value"); await VerifyItemIsAbsentAsync(markup, "Day"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionAfterConditionalIndexing() { var markup = @" public struct S { public int? i; } class A { public S[] s; public void goo() { A a = null; var q = a?.s?[$$; } }"; await VerifyItemExistsAsync(markup, "System"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses1() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.$$b?.c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses2() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.$$c?.d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "c"); } [WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinChainOfConditionalAccesses3() { var markup = @" class Program { static void Main(string[] args) { A a; var x = a?.b?.c?.$$d.e; } } class A { public B b; } class B { public C c; } class C { public D d; } class D { public int e; }"; await VerifyItemExistsAsync(markup, "d"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnSelf() { var markup = @"using System; [My] class X { [My$$] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NestedAttributeAccessibleOnOuterType() { var markup = @"using System; [My] class Y { } [$$] class X { [My] class MyAttribute : Attribute { } }"; await VerifyItemExistsAsync(markup, "My"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType() { var markup = @"abstract class Test { private int _field; public sealed class InnerTest : Test { public void SomeTest() { $$ } } }"; await VerifyItemExistsAsync(markup, "_field"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType2() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { $$ // M recommended and accessible } class NN { void Test2() { // M inaccessible and not recommended } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType3() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN { void Test2() { $$ // M inaccessible and not recommended } } } }"; await VerifyItemIsAbsentAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType4() { var markup = @"class C<T> { void M() { } class N : C<int> { void Test() { M(); // M recommended and accessible } class NN : N { void Test2() { $$ // M accessible and recommended. } } } }"; await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType5() { var markup = @" class D { public void Q() { } } class C<T> : D { class N { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "Q"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersFromBaseOuterType6() { var markup = @" class Base<T> { public int X; } class Derived : Base<int> { class Nested { void Test() { $$ } } }"; await VerifyItemIsAbsentAsync(markup, "X"); } [WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoTypeParametersDefinedInCrefs() { var markup = @"using System; /// <see cref=""Program{T$$}""/> class Program<T> { }"; await VerifyItemIsAbsentAsync(markup, "T"); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList1() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowTypesInGenericMethodTypeParameterList2() { var markup = @" class Class1<T, D> { public static Class1<T, D> Create() { return null; } } static class Class2 { public static void Test<T,D>(this Class1<T, D> arg) { } } class Program { static void Main(string[] args) { Class1<string, int>.Create().Test<string,$$ } } "; await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular); } [WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionInAliasedType() { var markup = @" using IAlias = IGoo; ///<summary>summary for interface IGoo</summary> interface IGoo { } class C { I$$ } "; await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task WithinNameOf() { var markup = @" class C { void goo() { var x = nameof($$) } } "; await VerifyAnyItemExistsAsync(markup); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y1"); } [WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMemberInNameOfInStaticContext() { var markup = @" class C { int y1 = 15; static int y2 = 1; static string x = nameof($$ "; await VerifyItemExistsAsync(markup, "y2"); } [WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IncompleteDeclarationExpressionType() { var markup = @" using System; class C { void goo() { var x = Console.$$ var y = 3; } } "; await VerifyItemExistsAsync(markup, "WriteLine"); } [WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticAndInstanceInNameOf() { var markup = @" using System; class C { class D { public int x; public static int y; } void goo() { var z = nameof(C.D.$$ } } "; await VerifyItemExistsAsync(markup, "x"); await VerifyItemExistsAsync(markup, "y"); } [WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForLocals() { var markup = @"class C { void M() { var x = nameof(T.z.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes2() { var markup = @"class C { void M() { var x = nameof(U.$$) } } public class T { public U z; } public class U { public int nope; } "; await VerifyItemExistsAsync(markup, "nope"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes3() { var markup = @"class C { void M() { var x = nameof(N.$$) } } namespace N { public class U { public int nope; } } "; await VerifyItemExistsAsync(markup, "U"); } [WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NameOfMembersListedForNamespacesAndTypes4() { var markup = @" using z = System; class C { void M() { var x = nameof(z.$$) } } "; await VerifyItemExistsAsync(markup, "Console"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings1() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$ "; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings2() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{$$}""; } }"; await VerifyItemExistsAsync(markup, "a"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings3() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings4() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings5() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$ "; await VerifyItemExistsAsync(markup, "b"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InterpolatedStrings6() { var markup = @" class C { void M() { var a = ""Hello""; var b = ""World""; var c = $@""{a}, {$$}""; } }"; await VerifyItemExistsAsync(markup, "b"); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBeforeFirstStringHole() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}$$\{1}\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotBetweenStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}$$\{2}""")); } [WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotAfterStringHoles() { await VerifyNoItemsExistAsync(AddInsideMethod( @"var x = ""\{0}\{1}\{2}$$""")); } [WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task CompletionAfterTypeOfGetType() { await VerifyItemExistsAsync(AddInsideMethod( "typeof(int).GetType().$$"), "GUID"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives1() { var markup = @" using $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives2() { var markup = @" using N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemIsAbsentAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives3() { var markup = @" using G = $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives4() { var markup = @" using G = N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives5() { var markup = @" using static $$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingDirectives6() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemExistsAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates1() { var markup = @" using static $$ class A { } delegate void B(); namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "B"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowDelegates2() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } delegate void D(); namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "D"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces1() { var markup = @" using static N.$$ class A { } static class B { } namespace N { class C { } interface I { } namespace M { } }"; await VerifyItemExistsAsync(markup, "C"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "M"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticDoesNotShowInterfaces2() { var markup = @" using static $$ class A { } interface I { } namespace N { class C { } static class D { } namespace M { } }"; await VerifyItemExistsAsync(markup, "A"); await VerifyItemIsAbsentAsync(markup, "I"); await VerifyItemExistsAsync(markup, "N"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods1() { var markup = @" using static A; using static B; static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods2() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { $$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods3() { var markup = @" using N; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods4() { var markup = @" using static N.A; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods5() { var markup = @" using static N.A; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemIsAbsentAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods6() { var markup = @" using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$ } } "; await VerifyItemIsAbsentAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task UsingStaticAndExtensionMethods7() { var markup = @" using N; using static N.B; namespace N { static class A { public static void Goo(this string s) { } } static class B { public static void Bar(this string s) { } } } class C { void M() { string s; s.$$; } } "; await VerifyItemExistsAsync(markup, "Goo"); await VerifyItemExistsAsync(markup, "Bar"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinSameClassOfferedForCompletion() { var markup = @" public static class Test { static void TestB() { $$ } static void TestA(this string s) { } } "; await VerifyItemExistsAsync(markup, "TestA"); } [WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExtensionMethodWithinParentClassOfferedForCompletion() { var markup = @" public static class Parent { static void TestA(this string s) { } static void TestC(string s) { } public static class Test { static void TestB() { $$ } } } "; await VerifyItemExistsAsync(markup, "TestA"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1() { var markup = @" using System; class C { void M(bool x) { try { } catch when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter1_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch when $$ "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when ($$ "; await VerifyItemExistsAsync(markup, "x"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExceptionFilter2_NotBeforeOpenParen() { var markup = @" using System; class C { void M(bool x) { try { } catch (Exception ex) when $$ "; await VerifyNoItemsExistAsync(markup); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause1() { var markup = @" class C { void M(bool x) { switch (1) { case 1 when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SwitchCaseWhenClause2() { var markup = @" class C { void M(bool x) { switch (1) { case int i when $$ "; await VerifyItemExistsAsync(markup, "x"); } [WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExpressionContextCompletionWithinCast() { var markup = @" class Program { void M() { for (int i = 0; i < 5; i++) { var x = ($$) var y = 1; } } } "; await VerifyItemExistsAsync(markup, "i"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInPropertyInitializer() { var markup = @" class A { int abc; int B { get; } = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInPropertyInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoInstanceMembersInFieldLikeEventInitializer() { var markup = @" class A { Action abc; event Action B = $$ } "; await VerifyItemIsAbsentAsync(markup, "abc"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task StaticMembersInFieldLikeEventInitializer() { var markup = @" class A { static Action s_abc; event Action B = $$ } "; await VerifyItemExistsAsync(markup, "s_abc"); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldInitializer() { var markup = @" int aaa = 1; int bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InstanceMembersInTopLevelFieldLikeEventInitializer() { var markup = @" Action aaa = null; event Action bbb = $$ "; await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes1() { var markup = @" using A = System class C { A?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes2() { var markup = @" class C { System?.$$ } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoConditionalAccessCompletionOnTypes3() { var markup = @" class C { System.Console?.$$ } "; await VerifyNoItemsExistAsync(markup); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInIncompletePropertyDeclaration() { var markup = @" class Class1 { public string Property1 { get; set; } } class Class2 { public string Property { get { return this.Source.$$ public Class1 Source { get; set; } }"; await VerifyItemExistsAsync(markup, "Property1"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoCompletionInShebangComments() { await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script); await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompoundNameTargetTypePreselection() { var markup = @" class Class1 { void goo() { int x = 3; string y = x.$$ } }"; await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer1() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargetTypeInCollectionInitializer2() { var markup = @" using System.Collections.Generic; class Program { static void Main(string[] args) { int z; string q; List<int> x = new List<int>() { 1, $$ } } }"; await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer1() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TargeTypeInObjectInitializer2() { var markup = @" class C { public int X { get; set; } public int Y { get; set; } void goo() { int i; var c = new C() { X = 1, Y = $$ } } }"; await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElements() { var markup = @" class C { void goo() { var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9); t.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; await VerifyItemExistsAsync(markup, "Alice"); await VerifyItemExistsAsync(markup, "Bob"); await VerifyItemExistsAsync(markup, "CompareTo"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "GetType"); await VerifyItemExistsAsync(markup, "Item2"); await VerifyItemExistsAsync(markup, "ITEM3"); for (var i = 4; i <= 8; i++) { await VerifyItemExistsAsync(markup, "Item" + i); } await VerifyItemExistsAsync(markup, "ToString"); await VerifyItemIsAbsentAsync(markup, "Item1"); await VerifyItemIsAbsentAsync(markup, "Item9"); await VerifyItemIsAbsentAsync(markup, "Rest"); await VerifyItemIsAbsentAsync(markup, "Item3"); } [WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleElementsCompletionOffMethodGroup() { var markup = @" class C { void goo() { new object().ToString.$$ } }" + TestResources.NetFX.ValueTuple.tuplelib_cs; // should not crash await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task NoCompletionInLocalFuncGenericParamList() { var markup = @" class C { void M() { int Local<$$"; await VerifyNoItemsExistAsync(markup); } [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] public async Task CompletionForAwaitWithoutAsync() { var markup = @" class C { void M() { await Local<$$"; await VerifyAnyItemExistsAsync(markup); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel1() { await VerifyItemExistsAsync(@" class C { ($$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel2() { await VerifyItemExistsAsync(@" class C { ($$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel3() { await VerifyItemExistsAsync(@" class C { (C, $$ }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeAtMemberLevel4() { await VerifyItemExistsAsync(@" class C { (C, $$) }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInForeach() { await VerifyItemExistsAsync(@" class C { void M() { foreach ((C, $$ } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInParameterList() { await VerifyItemExistsAsync(@" class C { void M((C, $$) { } }", "C"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TupleTypeInNameOf() { await VerifyItemExistsAsync(@" class C { void M() { var x = nameof((C, $$ } }", "C"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription() { await VerifyItemExistsAsync(@" class C { void M() { void Local() { } $$ } }", "Local", "void Local()"); } [WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionDescription2() { await VerifyItemExistsAsync(@" using System; class C { class var { } void M() { Action<int> Local(string x, ref var @class, params Func<int, string> f) { return () => 0; } $$ } }", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)"); } [WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterDot() { var markup = @"namespace ConsoleApplication253 { class Program { static void Main(string[] args) { M(E.$$) } static void M(E e) { } } enum E { A, B, } } "; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup1() { var markup = @"namespace ConsoleApp { class Program { static void Main(string[] args) { Main.$$ } } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup2() { var markup = @"class C { void M<T>() {M<C>.$$ } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task NotOnMethodGroup3() { var markup = @"class C { void M() {M.$$} } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember() { var markup = @"public static class Extensions { public static T Get<T>(this object o) => $$} "; await VerifyItemExistsAsync(markup, "o"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task EnumConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Enum"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task DelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "Delegate"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task MulticastDelegateConstraint() { var markup = @"public class X<T> where T : System.$$ "; await VerifyItemExistsAsync(markup, "MulticastDelegate"); } private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString) { var template = @" using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ThenIncludeIntellisenseBug { class Program { static void Main(string[] args) { var registrations = new List<Registration>().AsQueryable(); var reg = registrations.Include(r => r.Activities).ThenInclude([1]); } } internal class Registration { public ICollection<Activity> Activities { get; set; } } public class Activity { public Task Task { get; set; } } public class Task { public string Name { get; set; } } public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity> { } public static class EntityFrameworkQuerybleExtensions { public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>( this IQueryable<TEntity> source, Expression<Func<TEntity, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } [2] } }"; return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenInclude() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoExpression() { var markup = CreateThenIncludeTestCode("b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgument() { var markup = CreateThenIncludeTestCode("0, b => b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); }"); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentNoOverlap() { var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath, Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap() { var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$", @" public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source, int a, Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, int a, Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemIsAbsentAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeGenericAndNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>( this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class { return default(IIncludableQueryable<TEntity, TProperty>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ThenIncludeNoGenericOverloads() { var markup = CreateThenIncludeTestCode("c => c.$$", @" public static IIncludableQueryable<Registration, Task> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<Activity, Task> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Task>); } public static IIncludableQueryable<Registration, Activity> ThenInclude( this IIncludableQueryable<Registration, ICollection<Activity>> source, Func<ICollection<Activity>, Activity> navigationPropertyPath) { return default(IIncludableQueryable<Registration, Activity>); } "); await VerifyItemExistsAsync(markup, "Task"); await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaWithOverloads() { var markup = @" using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace ClassLibrary1 { class SomeItem { public string A; public int B; } class SomeCollection<T> : List<T> { public virtual SomeCollection<T> Include(string path) => null; } static class Extensions { public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path) => null; public static IList Include(this IList source, string path) => null; public static IList<T> Include<T>(this IList<T> source, string path) => null; } class Program { void M(SomeCollection<SomeItem> c) { var a = from m in c.Include(t => t.$$); } } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "A"); await VerifyItemExistsAsync(markup, "B"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads2() { var markup = @" using System; class C { void M(Action<int> a) { } void M(string s) { } void Test() { M(p => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads3() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M((int p) => p.$$); } }"; await VerifyItemIsAbsentAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")] public async Task CompletionForLambdaWithOverloads4() { var markup = @" using System; class C { void M(Action<int> a) { } void M(Action<string> a) { } void Test() { M(p => p.$$); } }"; await VerifyItemExistsAsync(markup, "Substring"); await VerifyItemExistsAsync(markup, "GetTypeCode"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParameters() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new List<Product>(), arg => arg.$$); } static void Create<T>(List<T> list, Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1, Product2>(), arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersAndOverloads2() { var markup = @" using System; using System.Collections.Generic; class Program { static void M() { Create(new Dictionary<Product1,Product2>(),arg => arg.$$); } static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { } static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { } static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { } } class Product1 { public void MyProperty1() { } } class Product2 { public void MyProperty2() { } } class Product3 { public void MyProperty3() { } }"; await VerifyItemExistsAsync(markup, "MyProperty1"); await VerifyItemExistsAsync(markup, "MyProperty2"); await VerifyItemExistsAsync(markup, "MyProperty3"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClass() { var markup = @" using System; class Program<T> { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemIsAbsentAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType() { var markup = @" using System; class Program<T> where T : Product { static void M() { Create(arg => arg.$$); } static void Create(Action<T> expression) { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")] public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod() { var markup = @" using System; class Program { static void M() { Create(arg => arg.$$); } static void Create<T>(Action<T> expression) where T : Product { } } class Product { public void MyProperty() { } }"; await VerifyItemExistsAsync(markup, "GetHashCode"); await VerifyItemExistsAsync(markup, "MyProperty"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x = 7, Action<string> y = null) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")] public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2() { var markup = @" using System; class C { void Test() { X(y: t => Console.WriteLine(t.$$)); } void X(int x, int z, Action<string> y) { } } "; await VerifyItemExistsAsync(markup, "Length"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive() { var markup = @" using System; static class CExtensions { public static void X(this C x, Action<string> y) { } } class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive() { var markup = @" using System; public static void X(this C x, Action<string> y) { } public class C { void Test() { new C().X(t => Console.WriteLine(t.$$)); } } "; await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithNonFunctionsAsArguments() { var markup = @" using System; class c { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> configure) { var builder = new Builder(); configure(builder); } } class Builder { public int Something { get; set; } }"; await VerifyItemExistsAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAsArguments() { var markup = @" using System; class Program { public delegate void Delegate1(Uri u); public delegate void Delegate2(Guid g); public void M(Delegate1 d) { } public void M(Delegate2 d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Uri await VerifyItemExistsAsync(markup, "AbsoluteUri"); await VerifyItemExistsAsync(markup, "Fragment"); await VerifyItemExistsAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments() { var markup = @" using System; class Program { public delegate void Delegate1<T1,T2>(T2 t2, T1 t1); public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1); public void M(Delegate1<Uri,Guid> d) { } public void M(Delegate2<Uri,Guid> d) { } public void Test() { M(d => d.$$) } }"; // Guid await VerifyItemExistsAsync(markup, "ToByteArray"); // Should not appear for Uri await VerifyItemIsAbsentAsync(markup, "AbsoluteUri"); await VerifyItemIsAbsentAsync(markup, "Fragment"); await VerifyItemIsAbsentAsync(markup, "Query"); // Should not appear for Delegate await VerifyItemIsAbsentAsync(markup, "BeginInvoke"); await VerifyItemIsAbsentAsync(markup, "Clone"); await VerifyItemIsAbsentAsync(markup, "Method"); await VerifyItemIsAbsentAsync(markup, "Target"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsBeforeParams() { var markup = @" using System; class C { void M() { Goo(builder => { builder.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "AnotherSomething"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "Something"); } [WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionInsideMethodWithParamsInParams() { var markup = @" using System; class C { void M() { Goo(b0 => { }, b1 => {}, b2 => { b2.$$ }); } void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions) { } } class Builder { public int Something { get; set; } }; class AnotherBuilder { public int AnotherSomething { get; set; } }"; await VerifyItemIsAbsentAsync(markup, "Something"); await VerifyItemIsAbsentAsync(markup, "FirstOrDefault"); await VerifyItemExistsAsync(markup, "AnotherSomething"); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilterWithExperimentEnabled() { TargetTypedCompletionFilterFeatureFlag = true; var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestNoTargetTypeFilterWithExperimentDisabled() { TargetTypedCompletionFilterFeatureFlag = false; var markup = @"public class C { int intField; void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "intField", matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotOnObjectMembers() { TargetTypedCompletionFilterFeatureFlag = true; var markup = @"public class C { void M(int x) { M($$); } }"; await VerifyItemExistsAsync( markup, "GetHashCode", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeFilter_NotNamedTypes() { TargetTypedCompletionFilterFeatureFlag = true; var markup = @"public class C { void M(C c) { M($$); } }"; await VerifyItemExistsAsync( markup, "c", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter }); await VerifyItemExistsAsync( markup, "C", matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch() { var markup = @" public static class Ext { public static void DoSomething<T>(this T thing, string s) where T : class, I { } } public interface I { } public class C { public void M(string s) { this.$$ } }"; await VerifyItemExistsAsync(markup, "M"); await VerifyItemExistsAsync(markup, "Equals"); await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>"); } [WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")] [Fact] [Trait(Traits.Feature, Traits.Features.Completion)] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionInStaticMethod() { await VerifyItemExistsAsync(@" class C { static void M() { void Local() { } $$ } }", "Local"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")] public async Task NoItemWithEmptyDisplayName() { var markup = @" class C { static void M() { int$$ } } "; await VerifyItemIsAbsentAsync( markup, "", matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter }); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar) { var markup = @" class Program { private void Bar() { F$$ } private void Foo(int i) { } private void Foo(int i, int c) { } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(){commitChar} }} private void Foo(int i) {{ }} private void Foo(int i, int c) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithSemicolonInNestedMethod(char commitChar) { var markup = @" class Program { private void Bar() { Foo(F$$); } private int Foo(int i) { return 1; } }"; var expected = $@" class Program {{ private void Bar() {{ Foo(Foo(){commitChar}); }} private int Foo(int i) {{ return 1; }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar) { var markup = @" using System; class Program { private void Bar() { Bar2(F$$); } private void Foo() { } void Bar2(Action t) { } }"; var expected = $@" using System; class Program {{ private void Bar() {{ Bar2(Foo{commitChar}); }} private void Foo() {{ }} void Bar2(Action t) {{ }} }}"; await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar) { var markup = @" class Program { private static void Bar() { var o = new P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = new Program(){commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar) { var markup = @" class Program { private static void Bar() { var o = P$$ } }"; var expected = $@" class Program {{ private static void Bar() {{ var o = Program{commitChar} }} }}"; await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar); } [Theory, Trait(Traits.Feature, Traits.Features.Completion)] [InlineData('.')] [InlineData(';')] public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar) { var markup = @" using String2 = System.String; namespace Bar1 { class Program { private static void Bar() { var o = new S$$ } } }"; var expected = $@" using String2 = System.String; namespace Bar1 {{ class Program {{ private static void Bar() {{ var o = new String2(){commitChar} }} }} }}"; await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CompletionWithSemicolonUnderNameofContext() { var markup = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(B$$) } } }"; var expected = @" namespace Bar1 { class Program { private static void Bar() { var o = nameof(Bar;) } } }"; await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';'); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPatternMatchWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m is RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterPropertyPatternMatch() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { public RankedMusicians R; void M(C m) { if (m is { R: RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ChildClassAfterPatternMatch() { var markup = @"namespace N { public class D { public class E { } } class C { void M(object m) { if (m is D.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "E"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpression() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EnumMemberAfterBinaryExpressionWithDeclaration() { var markup = @"namespace N { enum RankedMusicians { BillyJoel, EveryoneElse } class C { void M(RankedMusicians m) { if (m == RankedMusicians.$$ r) { } } } }"; // VerifyItemExistsAsync also tests with the item typed. await VerifyItemExistsAsync(markup, "BillyJoel"); await VerifyItemExistsAsync(markup, "EveryoneElse"); await VerifyItemIsAbsentAsync(markup, "Equals"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable() { var markup = @" public class C { [System.Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete() { var markup = @" public class C { [System.Obsolete] public void M() { } [System.Obsolete] public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ 1 {FeaturesResources.overload})"); } [WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreCustomObsoleteAttribute() { var markup = @" public class ObsoleteAttribute: System.Attribute { } public class C { [Obsolete] public void M() { } public void M(int i) { } public void Test() { this.$$ } } "; await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ 1 {FeaturesResources.overload})"); } [InlineData("int", "")] [InlineData("int[]", "int a")] [Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)] public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList) { // Check the description displayed is based on symbol matches targeted type TargetTypedCompletionFilterFeatureFlag = true; var markup = $@"public class C {{ bool Bar(int a, int b) => false; int Bar() => 0; int[] Bar(int a) => null; bool N({targetType} x) => true; void M(C c) {{ N(c.$$); }} }}"; await VerifyItemExistsAsync( markup, "Bar", expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})", matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter }); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesNotSuggestedInDeclarationDeconstruction() { await VerifyItemIsAbsentAsync(@" class C { int M() { var (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { (x, $$) = (0, 0); } }", "C"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction() { await VerifyItemExistsAsync(@" class C { int M() { int y; (var x, $$) = (0, 0); } }", "y"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")] public async Task TestTypeParameterConstraintedToInterfaceWithStatics() { var source = @" interface I1 { static void M0(); static abstract void M1(); abstract static int P1 { get; set; } abstract static event System.Action E1; } interface I2 { static abstract void M2(); } class Test { void M<T>(T x) where T : I1, I2 { T.$$ } } "; await VerifyItemIsAbsentAsync(source, "M0"); await VerifyItemExistsAsync(source, "M1"); await VerifyItemExistsAsync(source, "M2"); await VerifyItemExistsAsync(source, "P1"); await VerifyItemExistsAsync(source, "E1"); } } }
1