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
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
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
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CoreTest/SyntaxPathTests.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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxPathTests { [Fact] public void RecoverSingle() { var node = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("Hi")); var path = new SyntaxPath(node); Assert.True(path.TryResolve(node, out SyntaxNode recovered)); Assert.Equal(node, recovered); } [Fact] public void FailFirstType() { var node = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("Hi")); var path = new SyntaxPath(node); Assert.False(path.TryResolve(SyntaxFactory.ParseExpression("Goo()"), out SyntaxNode _)); } [Fact] public void RecoverChild() { var node = SyntaxFactory.ParseExpression("Goo()"); var child = ((InvocationExpressionSyntax)node).ArgumentList; var path = new SyntaxPath(child); Assert.True(path.TryResolve(node, out SyntaxNode recovered)); Assert.Equal(child, recovered); } [Fact] public void FailChildCount() { var root = SyntaxFactory.ParseExpression("Goo(a, b)"); var path = new SyntaxPath(((InvocationExpressionSyntax)root).ArgumentList.Arguments.Last()); var root2 = SyntaxFactory.ParseExpression("Goo(a)"); Assert.False(path.TryResolve(root2, out SyntaxNode _)); } [Fact] public void FailChildType() { var root = SyntaxFactory.ParseExpression("Goo(a)"); var path = new SyntaxPath(((InvocationExpressionSyntax)root).ArgumentList.Arguments.First().Expression); var root2 = SyntaxFactory.ParseExpression("Goo(3)"); Assert.False(path.TryResolve(root2, out SyntaxNode _)); } [Fact] public void RecoverGeneric() { var root = SyntaxFactory.ParseExpression("Goo()"); var node = ((InvocationExpressionSyntax)root).ArgumentList; var path = new SyntaxPath(node); Assert.True(path.TryResolve(root, out ArgumentListSyntax recovered)); Assert.Equal(node, recovered); } [Fact] public void TestRoot1() { var tree = SyntaxFactory.ParseSyntaxTree(string.Empty); var root = tree.GetRoot(); var path = new SyntaxPath(root); Assert.True(path.TryResolve(tree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(root, node); } [Fact] public void TestRoot2() { var text = SourceText.From(string.Empty); var tree = SyntaxFactory.ParseSyntaxTree(string.Empty); var root = tree.GetCompilationUnitRoot(); var path = new SyntaxPath(root); var newText = text.WithChanges(new TextChange(new TextSpan(0, 0), "class C {}")); var newTree = tree.WithChangedText(newText); Assert.True(path.TryResolve(newTree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.CompilationUnit, node.Kind()); } [Fact] public void TestRoot3() { var text = SourceText.From("class C {}"); var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); var path = new SyntaxPath(root); var newText = text.WithChanges(new TextChange(new TextSpan(0, text.Length), "")); var newTree = tree.WithChangedText(newText); Assert.True(path.TryResolve(newTree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.CompilationUnit, node.Kind()); } [Fact] public void TestRoot4() { var text = "class C {}"; var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); var path = new SyntaxPath(root); tree = WithReplaceFirst(tree, "C", "D"); Assert.True(path.TryResolve(tree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.CompilationUnit, node.Kind()); } [Fact] public void TestMethodBodyChange() { var text = @"namespace N { class C { void M1() { int i1; } void M2() { int i2; } void M3() { int i3; } } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)(tree.GetRoot() as CompilationUnitSyntax).Members[0]; var classDecl = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var member1 = classDecl.Members[0]; var member2 = classDecl.Members[1]; var member3 = classDecl.Members[2]; var path1 = new SyntaxPath(member1); var path2 = new SyntaxPath(member2); var path3 = new SyntaxPath(member3); tree = WithReplaceFirst(WithReplaceFirst(WithReplaceFirst(tree, "i1", "j1"), "i2", "j2"), "i3", "j3"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.True(path3.TryResolve(tree, CancellationToken.None, out SyntaxNode n3)); Assert.Equal(SyntaxKind.MethodDeclaration, n1.Kind()); Assert.Equal("M1", ((MethodDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.MethodDeclaration, n2.Kind()); Assert.Equal("M2", ((MethodDeclarationSyntax)n2).Identifier.ValueText); Assert.Equal(SyntaxKind.MethodDeclaration, n3.Kind()); Assert.Equal("M3", ((MethodDeclarationSyntax)n3).Identifier.ValueText); } [Fact] public void TestAddBase() { var text = @"namespace N { class C { } class D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)(tree.GetRoot() as CompilationUnitSyntax).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplaceFirst(tree, "C {", "C : Goo {"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.ClassDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestAddFieldBefore() { var text = @"namespace N { class C { void M1() { int i1; } bool M2() { int i2; } } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var classDecl = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var member1 = classDecl.Members[0]; var member2 = classDecl.Members[1]; var path1 = new SyntaxPath(member1); var path2 = new SyntaxPath(member2); tree = WithReplaceFirst(tree, "bool", "int field; bool"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.MethodDeclaration, n1.Kind()); Assert.Equal("M1", ((MethodDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.MethodDeclaration, n2.Kind()); Assert.Equal("M2", ((MethodDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestChangeType() { var text = @"namespace N { class C { } class D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplaceFirst(tree, "class", "struct"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.False(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode _)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n1).Identifier.ValueText); } [Fact] public void TestChangeType1() { var text = @"namespace N { class C { void Goo(); } class D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var method1 = class1.Members[0]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); var path3 = new SyntaxPath(method1); tree = WithReplaceFirst(tree, "class", "struct"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.False(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode _)); Assert.False(path3.TryResolve(tree, CancellationToken.None, out SyntaxNode _)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n1).Identifier.ValueText); } [Fact] public void TestWhitespace1() { var text = @"namespace N { class C { } class D { } }"; var text2 = text.Replace(" ", " "); var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplace(tree, 0, text.Length, text2); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.ClassDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestComment() { var text = @"namespace N { class C { } struct D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplaceFirst(WithReplaceFirst(tree, "class", "/* goo */ class"), "struct", "/* bar */ struct"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.StructDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestPP1() { var text = @"namespace N { class C { } struct D { } }"; var text2 = @"namespace N { #if true class C { } struct D { } #endif }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplace(tree, 0, text.Length, text2); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.StructDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestRemoveUsing() { var text = SourceText.From("using X; class C {}"); var tree = SyntaxFactory.ParseSyntaxTree(text); var root = (CompilationUnitSyntax)tree.GetRoot(); var path = new SyntaxPath(root.Members[0]); var newText = WithReplaceFirst(text, "using X;", ""); var newTree = tree.WithChangedText(newText); Assert.True(path.TryResolve(newTree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.ClassDeclaration, node.Kind()); } internal static SourceText WithReplaceFirst(SourceText text, string oldText, string newText) { var oldFullText = text.ToString(); var offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal); var length = oldText.Length; var span = new TextSpan(offset, length); var newFullText = oldFullText.Substring(0, offset) + newText + oldFullText.Substring(span.End); return SourceText.From(newFullText); } public static SyntaxTree WithReplaceFirst(SyntaxTree syntaxTree, string oldText, string newText) { return WithReplace(syntaxTree, startIndex: 0, oldText: oldText, newText: newText); } public static SyntaxTree WithReplace(SyntaxTree syntaxTree, int offset, int length, string newText) { var oldFullText = syntaxTree.GetText(); var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText)); return syntaxTree.WithChangedText(newFullText); } public static SyntaxTree WithReplace(SyntaxTree syntaxTree, int startIndex, string oldText, string newText) { // Use the offset to find the first element to replace at return WithReplace(syntaxTree, offset: syntaxTree.GetText().ToString().IndexOf(oldText, startIndex, StringComparison.Ordinal), length: oldText.Length, newText: newText); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxPathTests { [Fact] public void RecoverSingle() { var node = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("Hi")); var path = new SyntaxPath(node); Assert.True(path.TryResolve(node, out SyntaxNode recovered)); Assert.Equal(node, recovered); } [Fact] public void FailFirstType() { var node = SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("Hi")); var path = new SyntaxPath(node); Assert.False(path.TryResolve(SyntaxFactory.ParseExpression("Goo()"), out SyntaxNode _)); } [Fact] public void RecoverChild() { var node = SyntaxFactory.ParseExpression("Goo()"); var child = ((InvocationExpressionSyntax)node).ArgumentList; var path = new SyntaxPath(child); Assert.True(path.TryResolve(node, out SyntaxNode recovered)); Assert.Equal(child, recovered); } [Fact] public void FailChildCount() { var root = SyntaxFactory.ParseExpression("Goo(a, b)"); var path = new SyntaxPath(((InvocationExpressionSyntax)root).ArgumentList.Arguments.Last()); var root2 = SyntaxFactory.ParseExpression("Goo(a)"); Assert.False(path.TryResolve(root2, out SyntaxNode _)); } [Fact] public void FailChildType() { var root = SyntaxFactory.ParseExpression("Goo(a)"); var path = new SyntaxPath(((InvocationExpressionSyntax)root).ArgumentList.Arguments.First().Expression); var root2 = SyntaxFactory.ParseExpression("Goo(3)"); Assert.False(path.TryResolve(root2, out SyntaxNode _)); } [Fact] public void RecoverGeneric() { var root = SyntaxFactory.ParseExpression("Goo()"); var node = ((InvocationExpressionSyntax)root).ArgumentList; var path = new SyntaxPath(node); Assert.True(path.TryResolve(root, out ArgumentListSyntax recovered)); Assert.Equal(node, recovered); } [Fact] public void TestRoot1() { var tree = SyntaxFactory.ParseSyntaxTree(string.Empty); var root = tree.GetRoot(); var path = new SyntaxPath(root); Assert.True(path.TryResolve(tree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(root, node); } [Fact] public void TestRoot2() { var text = SourceText.From(string.Empty); var tree = SyntaxFactory.ParseSyntaxTree(string.Empty); var root = tree.GetCompilationUnitRoot(); var path = new SyntaxPath(root); var newText = text.WithChanges(new TextChange(new TextSpan(0, 0), "class C {}")); var newTree = tree.WithChangedText(newText); Assert.True(path.TryResolve(newTree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.CompilationUnit, node.Kind()); } [Fact] public void TestRoot3() { var text = SourceText.From("class C {}"); var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); var path = new SyntaxPath(root); var newText = text.WithChanges(new TextChange(new TextSpan(0, text.Length), "")); var newTree = tree.WithChangedText(newText); Assert.True(path.TryResolve(newTree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.CompilationUnit, node.Kind()); } [Fact] public void TestRoot4() { var text = "class C {}"; var tree = SyntaxFactory.ParseSyntaxTree(text); var root = tree.GetRoot(); var path = new SyntaxPath(root); tree = WithReplaceFirst(tree, "C", "D"); Assert.True(path.TryResolve(tree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.CompilationUnit, node.Kind()); } [Fact] public void TestMethodBodyChange() { var text = @"namespace N { class C { void M1() { int i1; } void M2() { int i2; } void M3() { int i3; } } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)(tree.GetRoot() as CompilationUnitSyntax).Members[0]; var classDecl = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var member1 = classDecl.Members[0]; var member2 = classDecl.Members[1]; var member3 = classDecl.Members[2]; var path1 = new SyntaxPath(member1); var path2 = new SyntaxPath(member2); var path3 = new SyntaxPath(member3); tree = WithReplaceFirst(WithReplaceFirst(WithReplaceFirst(tree, "i1", "j1"), "i2", "j2"), "i3", "j3"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.True(path3.TryResolve(tree, CancellationToken.None, out SyntaxNode n3)); Assert.Equal(SyntaxKind.MethodDeclaration, n1.Kind()); Assert.Equal("M1", ((MethodDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.MethodDeclaration, n2.Kind()); Assert.Equal("M2", ((MethodDeclarationSyntax)n2).Identifier.ValueText); Assert.Equal(SyntaxKind.MethodDeclaration, n3.Kind()); Assert.Equal("M3", ((MethodDeclarationSyntax)n3).Identifier.ValueText); } [Fact] public void TestAddBase() { var text = @"namespace N { class C { } class D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)(tree.GetRoot() as CompilationUnitSyntax).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplaceFirst(tree, "C {", "C : Goo {"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.ClassDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestAddFieldBefore() { var text = @"namespace N { class C { void M1() { int i1; } bool M2() { int i2; } } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var classDecl = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var member1 = classDecl.Members[0]; var member2 = classDecl.Members[1]; var path1 = new SyntaxPath(member1); var path2 = new SyntaxPath(member2); tree = WithReplaceFirst(tree, "bool", "int field; bool"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.MethodDeclaration, n1.Kind()); Assert.Equal("M1", ((MethodDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.MethodDeclaration, n2.Kind()); Assert.Equal("M2", ((MethodDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestChangeType() { var text = @"namespace N { class C { } class D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplaceFirst(tree, "class", "struct"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.False(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode _)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n1).Identifier.ValueText); } [Fact] public void TestChangeType1() { var text = @"namespace N { class C { void Goo(); } class D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var method1 = class1.Members[0]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); var path3 = new SyntaxPath(method1); tree = WithReplaceFirst(tree, "class", "struct"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.False(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode _)); Assert.False(path3.TryResolve(tree, CancellationToken.None, out SyntaxNode _)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n1).Identifier.ValueText); } [Fact] public void TestWhitespace1() { var text = @"namespace N { class C { } class D { } }"; var text2 = text.Replace(" ", " "); var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplace(tree, 0, text.Length, text2); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.ClassDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestComment() { var text = @"namespace N { class C { } struct D { } }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplaceFirst(WithReplaceFirst(tree, "class", "/* goo */ class"), "struct", "/* bar */ struct"); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.StructDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestPP1() { var text = @"namespace N { class C { } struct D { } }"; var text2 = @"namespace N { #if true class C { } struct D { } #endif }"; var tree = SyntaxFactory.ParseSyntaxTree(text); var namespaceDecl = (NamespaceDeclarationSyntax)((CompilationUnitSyntax)tree.GetRoot()).Members[0]; var class1 = (TypeDeclarationSyntax)namespaceDecl.Members[0]; var class2 = (TypeDeclarationSyntax)namespaceDecl.Members[1]; var path1 = new SyntaxPath(class1); var path2 = new SyntaxPath(class2); tree = WithReplace(tree, 0, text.Length, text2); Assert.True(path1.TryResolve(tree, CancellationToken.None, out SyntaxNode n1)); Assert.True(path2.TryResolve(tree, CancellationToken.None, out SyntaxNode n2)); Assert.Equal(SyntaxKind.ClassDeclaration, n1.Kind()); Assert.Equal("C", ((TypeDeclarationSyntax)n1).Identifier.ValueText); Assert.Equal(SyntaxKind.StructDeclaration, n2.Kind()); Assert.Equal("D", ((TypeDeclarationSyntax)n2).Identifier.ValueText); } [Fact] public void TestRemoveUsing() { var text = SourceText.From("using X; class C {}"); var tree = SyntaxFactory.ParseSyntaxTree(text); var root = (CompilationUnitSyntax)tree.GetRoot(); var path = new SyntaxPath(root.Members[0]); var newText = WithReplaceFirst(text, "using X;", ""); var newTree = tree.WithChangedText(newText); Assert.True(path.TryResolve(newTree, CancellationToken.None, out SyntaxNode node)); Assert.Equal(SyntaxKind.ClassDeclaration, node.Kind()); } internal static SourceText WithReplaceFirst(SourceText text, string oldText, string newText) { var oldFullText = text.ToString(); var offset = oldFullText.IndexOf(oldText, StringComparison.Ordinal); var length = oldText.Length; var span = new TextSpan(offset, length); var newFullText = oldFullText.Substring(0, offset) + newText + oldFullText.Substring(span.End); return SourceText.From(newFullText); } public static SyntaxTree WithReplaceFirst(SyntaxTree syntaxTree, string oldText, string newText) { return WithReplace(syntaxTree, startIndex: 0, oldText: oldText, newText: newText); } public static SyntaxTree WithReplace(SyntaxTree syntaxTree, int offset, int length, string newText) { var oldFullText = syntaxTree.GetText(); var newFullText = oldFullText.WithChanges(new TextChange(new TextSpan(offset, length), newText)); return syntaxTree.WithChangedText(newFullText); } public static SyntaxTree WithReplace(SyntaxTree syntaxTree, int startIndex, string oldText, string newText) { // Use the offset to find the first element to replace at return WithReplace(syntaxTree, offset: syntaxTree.GetText().ToString().IndexOf(oldText, startIndex, StringComparison.Ordinal), length: oldText.Length, newText: newText); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Collections/TopologicalSort.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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { /// <summary> /// A helper class that contains a topological sort algorithm. /// </summary> internal static class TopologicalSort { /// <summary> /// Produce a topological sort of a given directed acyclic graph, given a set of nodes which include all nodes /// that have no predecessors. Any nodes not in the given set, but reachable through successors, will be added /// to the result. This is an iterative rather than recursive implementation, so it is unlikely to cause a stack /// overflow. /// </summary> /// <typeparam name="TNode">The type of the node</typeparam> /// <param name="nodes">Any subset of the nodes that includes all nodes with no predecessors</param> /// <param name="successors">A function mapping a node to its set of successors</param> /// <param name="result">A list of all reachable nodes, in which each node always precedes its successors</param> /// <returns>true if successful; false if not successful due to cycles in the graph</returns> public static bool TryIterativeSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, ImmutableArray<TNode>> successors, out ImmutableArray<TNode> result) where TNode : notnull { // First, count the predecessors of each node PooledDictionary<TNode, int> predecessorCounts = PredecessorCounts(nodes, successors, out ImmutableArray<TNode> allNodes); // Initialize the ready set with those nodes that have no predecessors var ready = ArrayBuilder<TNode>.GetInstance(); foreach (TNode node in allNodes) { if (predecessorCounts[node] == 0) { ready.Push(node); } } // Process the ready set. Output a node, and decrement the predecessor count of its successors. var resultBuilder = ArrayBuilder<TNode>.GetInstance(); while (ready.Count != 0) { var node = ready.Pop(); resultBuilder.Add(node); foreach (var succ in successors(node)) { var count = predecessorCounts[succ]; Debug.Assert(count != 0); predecessorCounts[succ] = count - 1; if (count == 1) { ready.Push(succ); } } } // At this point all the nodes should have been output, otherwise there was a cycle bool hadCycle = predecessorCounts.Count != resultBuilder.Count; result = hadCycle ? ImmutableArray<TNode>.Empty : resultBuilder.ToImmutable(); predecessorCounts.Free(); ready.Free(); resultBuilder.Free(); return !hadCycle; } private static PooledDictionary<TNode, int> PredecessorCounts<TNode>( IEnumerable<TNode> nodes, Func<TNode, ImmutableArray<TNode>> successors, out ImmutableArray<TNode> allNodes) where TNode : notnull { var predecessorCounts = PooledDictionary<TNode, int>.GetInstance(); var counted = PooledHashSet<TNode>.GetInstance(); var toCount = ArrayBuilder<TNode>.GetInstance(); var allNodesBuilder = ArrayBuilder<TNode>.GetInstance(); toCount.AddRange(nodes); while (toCount.Count != 0) { var n = toCount.Pop(); if (!counted.Add(n)) { continue; } allNodesBuilder.Add(n); if (!predecessorCounts.ContainsKey(n)) { predecessorCounts.Add(n, 0); } foreach (var succ in successors(n)) { toCount.Push(succ); if (predecessorCounts.TryGetValue(succ, out int succPredecessorCount)) { predecessorCounts[succ] = succPredecessorCount + 1; } else { predecessorCounts.Add(succ, 1); } } } counted.Free(); toCount.Free(); allNodes = allNodesBuilder.ToImmutableAndFree(); return predecessorCounts; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { /// <summary> /// A helper class that contains a topological sort algorithm. /// </summary> internal static class TopologicalSort { /// <summary> /// Produce a topological sort of a given directed acyclic graph, given a set of nodes which include all nodes /// that have no predecessors. Any nodes not in the given set, but reachable through successors, will be added /// to the result. This is an iterative rather than recursive implementation, so it is unlikely to cause a stack /// overflow. /// </summary> /// <typeparam name="TNode">The type of the node</typeparam> /// <param name="nodes">Any subset of the nodes that includes all nodes with no predecessors</param> /// <param name="successors">A function mapping a node to its set of successors</param> /// <param name="result">A list of all reachable nodes, in which each node always precedes its successors</param> /// <returns>true if successful; false if not successful due to cycles in the graph</returns> public static bool TryIterativeSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, ImmutableArray<TNode>> successors, out ImmutableArray<TNode> result) where TNode : notnull { // First, count the predecessors of each node PooledDictionary<TNode, int> predecessorCounts = PredecessorCounts(nodes, successors, out ImmutableArray<TNode> allNodes); // Initialize the ready set with those nodes that have no predecessors var ready = ArrayBuilder<TNode>.GetInstance(); foreach (TNode node in allNodes) { if (predecessorCounts[node] == 0) { ready.Push(node); } } // Process the ready set. Output a node, and decrement the predecessor count of its successors. var resultBuilder = ArrayBuilder<TNode>.GetInstance(); while (ready.Count != 0) { var node = ready.Pop(); resultBuilder.Add(node); foreach (var succ in successors(node)) { var count = predecessorCounts[succ]; Debug.Assert(count != 0); predecessorCounts[succ] = count - 1; if (count == 1) { ready.Push(succ); } } } // At this point all the nodes should have been output, otherwise there was a cycle bool hadCycle = predecessorCounts.Count != resultBuilder.Count; result = hadCycle ? ImmutableArray<TNode>.Empty : resultBuilder.ToImmutable(); predecessorCounts.Free(); ready.Free(); resultBuilder.Free(); return !hadCycle; } private static PooledDictionary<TNode, int> PredecessorCounts<TNode>( IEnumerable<TNode> nodes, Func<TNode, ImmutableArray<TNode>> successors, out ImmutableArray<TNode> allNodes) where TNode : notnull { var predecessorCounts = PooledDictionary<TNode, int>.GetInstance(); var counted = PooledHashSet<TNode>.GetInstance(); var toCount = ArrayBuilder<TNode>.GetInstance(); var allNodesBuilder = ArrayBuilder<TNode>.GetInstance(); toCount.AddRange(nodes); while (toCount.Count != 0) { var n = toCount.Pop(); if (!counted.Add(n)) { continue; } allNodesBuilder.Add(n); if (!predecessorCounts.ContainsKey(n)) { predecessorCounts.Add(n, 0); } foreach (var succ in successors(n)) { toCount.Push(succ); if (predecessorCounts.TryGetValue(succ, out int succPredecessorCount)) { predecessorCounts[succ] = succPredecessorCount + 1; } else { predecessorCounts.Add(succ, 1); } } } counted.Free(); toCount.Free(); allNodes = allNodesBuilder.ToImmutableAndFree(); return predecessorCounts; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/RQName/Nodes/RQArrayType.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQArrayType : RQArrayOrPointerType { public readonly int Rank; public RQArrayType(int rank, RQType elementType) : base(elementType) { Rank = rank; } public override SimpleTreeNode ToSimpleTree() { var rankNode = new SimpleLeafNode(Rank.ToString()); return new SimpleGroupNode(RQNameStrings.Array, rankNode, ElementType.ToSimpleTree()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Features.RQName.SimpleTree; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQArrayType : RQArrayOrPointerType { public readonly int Rank; public RQArrayType(int rank, RQType elementType) : base(elementType) { Rank = rank; } public override SimpleTreeNode ToSimpleTree() { var rankNode = new SimpleLeafNode(Rank.ToString()); return new SimpleGroupNode(RQNameStrings.Array, rankNode, ElementType.ToSimpleTree()); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/EndConstructGeneration/XmlLiteralTests.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.EndConstructGeneration <[UseExportProvider]> Public Class XmlLiteralTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElement() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementSplitAcrossLines() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml > End Sub End Class", beforeCaret:={3, -1}, after:="Class C1 Sub M1() Dim x = <xml ></xml> End Sub End Class", afterCaret:={3, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWithNamespace() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a:b> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a:b></a:b> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration1() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(<xml>) End Sub End Class", caret:={1, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration2() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(i As Integer, <xml>) End Sub End Class", caret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlStartElementWithEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", caret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = </xml> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterSingleXmlTag() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml/> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterProcessingInstruction() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <?xml version=""1.0""?> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter1() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<xml></xml> End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter2() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml>) End Sub End Class", beforeCaret:={2, 16}, after:="Class C1 Sub M1() M2(<xml></xml>) End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlComment() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() Dim x = <!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <!----> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter1() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<!----> End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter2() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!--) End Sub End Class", beforeCaret:={2, 15}, after:="Class C1 Sub M1() M2(<!---->) End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <![CDATA[ End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <![CDATA[]]> End Sub End Class", afterCaret:={2, 25}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData2() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <Code><![CDATA[</Code> End Sub End Class", beforeCaret:={2, 31}, after:="Class C1 Sub M1() Dim x = <Code><![CDATA[]]></Code> End Sub End Class", afterCaret:={2, 31}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression1() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <%= %> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression2() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a><%= %> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression3() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%=</a> End Sub End Class", beforeCaret:={2, 22}, after:="Class C1 Sub M1() Dim x = <a><%= %></a> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstruction() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <??> End Sub End Class", afterCaret:={2, 18}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter1() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<??> End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter2() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<?) End Sub End Class", beforeCaret:={2, 13}, after:="Class C1 Sub M1() M2(<??>) End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestInsertBlankLineWhenPressingEnterInEmptyXmlTag() VerifyStatementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <goo></goo> End Sub End Class", beforeCaret:={2, 21}, after:="Class C1 Sub M1() Dim x = <goo> </goo> End Sub End Class", afterCaret:={3, -1}) 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.EndConstructGeneration <[UseExportProvider]> Public Class XmlLiteralTests <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElement() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementSplitAcrossLines() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <xml > End Sub End Class", beforeCaret:={3, -1}, after:="Class C1 Sub M1() Dim x = <xml ></xml> End Sub End Class", afterCaret:={3, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWithNamespace() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a:b> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a:b></a:b> End Sub End Class", afterCaret:={2, 21}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration1() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(<xml>) End Sub End Class", caret:={1, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyInParameterDeclaration2() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1(i As Integer, <xml>) End Sub End Class", caret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlStartElementWithEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml></xml> End Sub End Class", caret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterXmlEndElement() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = </xml> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterSingleXmlTag() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <xml/> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub DontApplyAfterProcessingInstruction() VerifyXmlElementEndConstructNotApplied( text:="Class C1 Sub M1() Dim x = <?xml version=""1.0""?> End Sub End Class", caret:={2, -1}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter1() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml> End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<xml></xml> End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlStartElementWhenPassedAsParameter2() VerifyXmlElementEndConstructApplied( before:="Class C1 Sub M1() M2(<xml>) End Sub End Class", beforeCaret:={2, 16}, after:="Class C1 Sub M1() M2(<xml></xml>) End Sub End Class", afterCaret:={2, 16}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlComment() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() Dim x = <!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <!----> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter1() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!-- End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<!----> End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCommentWhenPassedAsParameter2() VerifyXmlCommentEndConstructApplied( before:="Class C1 Sub M1() M2(<!--) End Sub End Class", beforeCaret:={2, 15}, after:="Class C1 Sub M1() M2(<!---->) End Sub End Class", afterCaret:={2, 15}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <![CDATA[ End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <![CDATA[]]> End Sub End Class", afterCaret:={2, 25}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlCData2() VerifyXmlCDataEndConstructApplied( before:="Class C1 Sub M1() Dim x = <Code><![CDATA[</Code> End Sub End Class", beforeCaret:={2, 31}, after:="Class C1 Sub M1() Dim x = <Code><![CDATA[]]></Code> End Sub End Class", afterCaret:={2, 31}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression1() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <%= %> End Sub End Class", afterCaret:={2, 20}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression2() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%= End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <a><%= %> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlEmbeddedExpression3() VerifyXmlEmbeddedExpressionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <a><%=</a> End Sub End Class", beforeCaret:={2, 22}, after:="Class C1 Sub M1() Dim x = <a><%= %></a> End Sub End Class", afterCaret:={2, 23}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstruction() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() Dim x = <? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() Dim x = <??> End Sub End Class", afterCaret:={2, 18}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter1() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<? End Sub End Class", beforeCaret:={2, -1}, after:="Class C1 Sub M1() M2(<??> End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestApplyAfterXmlProcessingInstructionWhenPassedAsParameter2() VerifyXmlProcessingInstructionEndConstructApplied( before:="Class C1 Sub M1() M2(<?) End Sub End Class", beforeCaret:={2, 13}, after:="Class C1 Sub M1() M2(<??>) End Sub End Class", afterCaret:={2, 13}) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.EndConstructGeneration)> Public Sub TestInsertBlankLineWhenPressingEnterInEmptyXmlTag() VerifyStatementEndConstructApplied( before:="Class C1 Sub M1() Dim x = <goo></goo> End Sub End Class", beforeCaret:={2, 21}, after:="Class C1 Sub M1() Dim x = <goo> </goo> End Sub End Class", afterCaret:={3, -1}) End Sub End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticAnalyzerAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract class AnalyzerAction { internal DiagnosticAnalyzer Analyzer { get; } internal AnalyzerAction(DiagnosticAnalyzer analyzer) { Analyzer = analyzer; } } internal sealed class SymbolAnalyzerAction : AnalyzerAction { public Action<SymbolAnalysisContext> Action { get; } public ImmutableArray<SymbolKind> Kinds { get; } public SymbolAnalyzerAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> kinds, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kinds = kinds; } } internal sealed class SymbolStartAnalyzerAction : AnalyzerAction { public Action<SymbolStartAnalysisContext> Action { get; } public SymbolKind Kind { get; } public SymbolStartAnalyzerAction(Action<SymbolStartAnalysisContext> action, SymbolKind kind, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kind = kind; } } internal sealed class SymbolEndAnalyzerAction : AnalyzerAction { public Action<SymbolAnalysisContext> Action { get; } public SymbolEndAnalyzerAction(Action<SymbolAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class SyntaxNodeAnalyzerAction<TLanguageKindEnum> : AnalyzerAction where TLanguageKindEnum : struct { public Action<SyntaxNodeAnalysisContext> Action { get; } public ImmutableArray<TLanguageKindEnum> Kinds { get; } public SyntaxNodeAnalyzerAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> kinds, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kinds = kinds; } } internal sealed class OperationBlockStartAnalyzerAction : AnalyzerAction { public Action<OperationBlockStartAnalysisContext> Action { get; } public OperationBlockStartAnalyzerAction(Action<OperationBlockStartAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class OperationBlockAnalyzerAction : AnalyzerAction { public Action<OperationBlockAnalysisContext> Action { get; } public OperationBlockAnalyzerAction(Action<OperationBlockAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class OperationAnalyzerAction : AnalyzerAction { public Action<OperationAnalysisContext> Action { get; } public ImmutableArray<OperationKind> Kinds { get; } public OperationAnalyzerAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> kinds, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kinds = kinds; } } internal sealed class CompilationStartAnalyzerAction : AnalyzerAction { public Action<CompilationStartAnalysisContext> Action { get; } public CompilationStartAnalyzerAction(Action<CompilationStartAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class CompilationAnalyzerAction : AnalyzerAction { public Action<CompilationAnalysisContext> Action { get; } public CompilationAnalyzerAction(Action<CompilationAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class SemanticModelAnalyzerAction : AnalyzerAction { public Action<SemanticModelAnalysisContext> Action { get; } public SemanticModelAnalyzerAction(Action<SemanticModelAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class SyntaxTreeAnalyzerAction : AnalyzerAction { public Action<SyntaxTreeAnalysisContext> Action { get; } public SyntaxTreeAnalyzerAction(Action<SyntaxTreeAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class AdditionalFileAnalyzerAction : AnalyzerAction { public Action<AdditionalFileAnalysisContext> Action { get; } public AdditionalFileAnalyzerAction(Action<AdditionalFileAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class CodeBlockStartAnalyzerAction<TLanguageKindEnum> : AnalyzerAction where TLanguageKindEnum : struct { public Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> Action { get; } public CodeBlockStartAnalyzerAction(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class CodeBlockAnalyzerAction : AnalyzerAction { public Action<CodeBlockAnalysisContext> Action { get; } public CodeBlockAnalyzerAction(Action<CodeBlockAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.Diagnostics { internal abstract class AnalyzerAction { internal DiagnosticAnalyzer Analyzer { get; } internal AnalyzerAction(DiagnosticAnalyzer analyzer) { Analyzer = analyzer; } } internal sealed class SymbolAnalyzerAction : AnalyzerAction { public Action<SymbolAnalysisContext> Action { get; } public ImmutableArray<SymbolKind> Kinds { get; } public SymbolAnalyzerAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> kinds, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kinds = kinds; } } internal sealed class SymbolStartAnalyzerAction : AnalyzerAction { public Action<SymbolStartAnalysisContext> Action { get; } public SymbolKind Kind { get; } public SymbolStartAnalyzerAction(Action<SymbolStartAnalysisContext> action, SymbolKind kind, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kind = kind; } } internal sealed class SymbolEndAnalyzerAction : AnalyzerAction { public Action<SymbolAnalysisContext> Action { get; } public SymbolEndAnalyzerAction(Action<SymbolAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class SyntaxNodeAnalyzerAction<TLanguageKindEnum> : AnalyzerAction where TLanguageKindEnum : struct { public Action<SyntaxNodeAnalysisContext> Action { get; } public ImmutableArray<TLanguageKindEnum> Kinds { get; } public SyntaxNodeAnalyzerAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> kinds, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kinds = kinds; } } internal sealed class OperationBlockStartAnalyzerAction : AnalyzerAction { public Action<OperationBlockStartAnalysisContext> Action { get; } public OperationBlockStartAnalyzerAction(Action<OperationBlockStartAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class OperationBlockAnalyzerAction : AnalyzerAction { public Action<OperationBlockAnalysisContext> Action { get; } public OperationBlockAnalyzerAction(Action<OperationBlockAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class OperationAnalyzerAction : AnalyzerAction { public Action<OperationAnalysisContext> Action { get; } public ImmutableArray<OperationKind> Kinds { get; } public OperationAnalyzerAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> kinds, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; Kinds = kinds; } } internal sealed class CompilationStartAnalyzerAction : AnalyzerAction { public Action<CompilationStartAnalysisContext> Action { get; } public CompilationStartAnalyzerAction(Action<CompilationStartAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class CompilationAnalyzerAction : AnalyzerAction { public Action<CompilationAnalysisContext> Action { get; } public CompilationAnalyzerAction(Action<CompilationAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class SemanticModelAnalyzerAction : AnalyzerAction { public Action<SemanticModelAnalysisContext> Action { get; } public SemanticModelAnalyzerAction(Action<SemanticModelAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class SyntaxTreeAnalyzerAction : AnalyzerAction { public Action<SyntaxTreeAnalysisContext> Action { get; } public SyntaxTreeAnalyzerAction(Action<SyntaxTreeAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class AdditionalFileAnalyzerAction : AnalyzerAction { public Action<AdditionalFileAnalysisContext> Action { get; } public AdditionalFileAnalyzerAction(Action<AdditionalFileAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class CodeBlockStartAnalyzerAction<TLanguageKindEnum> : AnalyzerAction where TLanguageKindEnum : struct { public Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> Action { get; } public CodeBlockStartAnalyzerAction(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } internal sealed class CodeBlockAnalyzerAction : AnalyzerAction { public Action<CodeBlockAnalysisContext> Action { get; } public CodeBlockAnalyzerAction(Action<CodeBlockAnalysisContext> action, DiagnosticAnalyzer analyzer) : base(analyzer) { Action = action; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/SignatureHelp/ObjectCreationExpressionSignatureHelpProviderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class ObjectCreationExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(ObjectCreationExpressionSignatureHelpProvider) End Function #Region "Regular tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickString() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:="Hello"$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickInteger() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:=1$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParametersMethodXmlComments() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo. See <see cref="System.Object"/> ''' </summary> Sub New() End Sub Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", "Summary for Goo. See Object", Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlCommentsOn1() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b</param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param a", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(545931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545931")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestUnsupportedParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new String($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char())", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(c As Char, count As Integer)", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char(), startIndex As Integer, length As Integer)", currentParameterIndex:=0)) ' All the unsafe pointer overloads should be missing in VB Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlComentsOn2() As Task Dim markup = <a><![CDATA[ Imports System Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b. See <see cref="System.IAsyncResult"/></param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param b. See IAsyncResult", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParen() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParameters() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnLambda() As Task Dim markup = <a><![CDATA[ Imports System Class C Sub Goo() Dim obj = [|new Action(Of Integer, Integer)($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("Action(Of Integer, Integer)(Sub (Integer, Integer))", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Current Parameter Name" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCurrentParameterName() As Task Dim markup = <a><![CDATA[ Class C Sub New(int a, string b) End Sub Sub Goo() Dim obj = [|new C(b:=String.Empty, $$a:=2|]) End Sub End Class ]]></a>.Value Await VerifyCurrentParameterNameAsync(markup, "a") End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerParens() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2,$$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNoInvocationOnSpace() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedCharacters() As Char = {","c, "("c} Dim unexpectedCharacters() As Char = {" "c, "["c, "<"c} VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer, y As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer, y As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) 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 Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.SignatureHelp Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SignatureHelp Public Class ObjectCreationExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(ObjectCreationExpressionSignatureHelpProvider) End Function #Region "Regular tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickString() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:="Hello"$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.Completion)> <WorkItem(25830, "https://github.com/dotnet/roslyn/issues/25830")> Public Async Function PickCorrectOverload_PickInteger() As Task Dim markup = <Text><![CDATA[ Public Class C Sub M() Dim obj = [|new C(i:=1$$|]) End Sub Public Sub New(i As String) End Sub Public Sub New(i As Integer) End Sub Public Sub New(filtered As Byte) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As Integer)", String.Empty, Nothing, currentParameterIndex:=0, isSelected:=True)) expectedOrderedItems.Add(New SignatureHelpTestItem("C(i As String)", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutParametersMethodXmlComments() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo. See <see cref="System.Object"/> ''' </summary> Sub New() End Sub Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", "Summary for Goo. See Object", Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn1() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlCommentsOn1() As Task Dim markup = <a><![CDATA[ Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b</param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param a", currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <WorkItem(545931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545931")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestUnsupportedParameters() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new String($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char())", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(c As Char, count As Integer)", currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem("String(value As Char(), startIndex As Integer, length As Integer)", currentParameterIndex:=0)) ' All the unsafe pointer overloads should be missing in VB Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithParametersXmlComentsOn2() As Task Dim markup = <a><![CDATA[ Imports System Class C ''' <summary> ''' Summary for Goo ''' </summary> ''' <param name="a">Param a</param> ''' <param name="b">Param b. See <see cref="System.IAsyncResult"/></param> Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4|]) End Sub End Class]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", "Summary for Goo", "Param b. See IAsyncResult", currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParen() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$ |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParameters() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C($$2, 4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationWithoutClosingParenWithParametersOn2() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$4 |]End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnLambda() As Task Dim markup = <a><![CDATA[ Imports System Class C Sub Goo() Dim obj = [|new Action(Of Integer, Integer)($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("Action(Of Integer, Integer)(Sub (Integer, Integer))", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function #End Region #Region "Current Parameter Name" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestCurrentParameterName() As Task Dim markup = <a><![CDATA[ Class C Sub New(int a, string b) End Sub Sub Goo() Dim obj = [|new C(b:=String.Empty, $$a:=2|]) End Sub End Class ]]></a>.Value Await VerifyCurrentParameterNameAsync(markup, "a") End Function #End Region #Region "Trigger tests" <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerParens() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim obj = [|new C($$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C()", String.Empty, Nothing, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationOnTriggerComma() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2,$$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(a As Integer, b As Integer)", String.Empty, String.Empty, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestNoInvocationOnSpace() As Task Dim markup = <a><![CDATA[ Class C Sub New(a As Integer, b As Integer) End Sub Sub Goo() Dim obj = [|new C(2, $$|]) End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() Await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger:=True) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Sub TestTriggerCharacters() Dim expectedCharacters() As Char = {","c, "("c} Dim unexpectedCharacters() As Char = {" "c, "["c, "<"c} VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters) End Sub #End Region #Region "EditorBrowsable tests" <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAlways() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableNever() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableAdvanced() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)> Public Sub New(x As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=New List(Of SignatureHelpTestItem)(), expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=True) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItems, expectedOrderedItemsSameSolution:=expectedOrderedItems, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic, hideAdvancedMembers:=False) End Function <WorkItem(7336, "DevDiv_Projects/Roslyn")> <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestEditorBrowsable_ObjectCreation_BrowsableMixed() As Task Dim markup = <Text><![CDATA[ Class Program Sub Main(args As String()) Dim x = New C($$ End Sub End Class ]]></Text>.Value Dim referencedCode = <Text><![CDATA[ Public Class C <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)> Public Sub New(x As Integer) End Sub <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> Public Sub New(x As Integer, y As Integer) End Sub End Class ]]></Text>.Value Dim expectedOrderedItemsMetadataReference = New List(Of SignatureHelpTestItem)() expectedOrderedItemsMetadataReference.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Dim expectedOrderedItemsSameSolution = New List(Of SignatureHelpTestItem)() expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) expectedOrderedItemsSameSolution.Add(New SignatureHelpTestItem("C(x As Integer, y As Integer)", String.Empty, String.Empty, currentParameterIndex:=0)) Await TestSignatureHelpInEditorBrowsableContextsAsync(markup:=markup, referencedCode:=referencedCode, expectedOrderedItemsMetadataReference:=expectedOrderedItemsMetadataReference, expectedOrderedItemsSameSolution:=expectedOrderedItemsSameSolution, sourceLanguage:=LanguageNames.VisualBasic, referencedLanguage:=LanguageNames.VisualBasic) End Function #End Region End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/Collections/CodeElementSnapshot.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.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class CodeElementSnapshot : Snapshot { private readonly ImmutableArray<EnvDTE.CodeElement> _elements; public CodeElementSnapshot(ICodeElements codeElements) { var count = codeElements.Count; var elementsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance(count); for (var i = 0; i < count; i++) { // We use "i + 1" since CodeModel indices are 1-based if (ErrorHandler.Succeeded(codeElements.Item(i + 1, out var element))) { elementsBuilder.Add(element); } } _elements = elementsBuilder.ToImmutableAndFree(); } public CodeElementSnapshot(ImmutableArray<EnvDTE.CodeElement> elements) => _elements = elements; public override int Count { get { return _elements.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _elements.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return _elements[index]; } } } }
// Licensed to the .NET Foundation under one or more 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.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { internal class CodeElementSnapshot : Snapshot { private readonly ImmutableArray<EnvDTE.CodeElement> _elements; public CodeElementSnapshot(ICodeElements codeElements) { var count = codeElements.Count; var elementsBuilder = ArrayBuilder<EnvDTE.CodeElement>.GetInstance(count); for (var i = 0; i < count; i++) { // We use "i + 1" since CodeModel indices are 1-based if (ErrorHandler.Succeeded(codeElements.Item(i + 1, out var element))) { elementsBuilder.Add(element); } } _elements = elementsBuilder.ToImmutableAndFree(); } public CodeElementSnapshot(ImmutableArray<EnvDTE.CodeElement> elements) => _elements = elements; public override int Count { get { return _elements.Length; } } public override EnvDTE.CodeElement this[int index] { get { if (index < 0 || index >= _elements.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return _elements[index]; } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxTreeTests.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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxTreeTests : ParsingTests { public SyntaxTreeTests(ITestOutputHelper output) : base(output) { } protected SyntaxTree UsingTree(string text, CSharpParseOptions options, params DiagnosticDescription[] expectedErrors) { var tree = base.UsingTree(text, options); var actualErrors = tree.GetDiagnostics(); actualErrors.Verify(expectedErrors); return tree; } // Diagnostic options on syntax trees are now obsolete #pragma warning disable CS0618 [Fact] public void CreateTreeWithDiagnostics() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), options: null, path: "", encoding: null, diagnosticOptions: options); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void ParseTreeWithChangesPreservesDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); var newTree = tree.WithChangedText(SourceText.From("class C { }")); Assert.Same(options, newTree.DiagnosticOptions); } [Fact] public void ParseTreeNullDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: null, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); // The default options are case insensitive but the default empty ImmutableDictionary is not Assert.NotSame(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeEmptyDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: ImmutableDictionary<string, ReportDiagnostic>.Empty, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); Assert.Same(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeCustomDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void DefaultTreeDiagnosticOptions() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); } [Fact] public void WithDiagnosticOptionsNull() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(null); Assert.NotNull(newTree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); Assert.Same(tree, newTree); } [Fact] public void WithDiagnosticOptionsEmpty() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic>.Empty); Assert.NotNull(tree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); // Default empty immutable dictionary is case sensitive Assert.NotSame(tree.DiagnosticOptions, newTree.DiagnosticOptions); } [Fact] public void PerTreeDiagnosticOptionsNewDict() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var map = ImmutableDictionary.CreateRange( new[] { KeyValuePair.Create("CS00778", ReportDiagnostic.Suppress) }); var newTree = tree.WithDiagnosticOptions(map); Assert.NotNull(newTree.DiagnosticOptions); Assert.Same(map, newTree.DiagnosticOptions); Assert.NotEqual(tree, newTree); } #pragma warning restore CS0618 [Fact] public void WithRootAndOptions_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}"); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_DummyTree() { var dummy = new CSharpSyntaxTree.DummySyntaxTree(); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = dummy.WithRootAndOptions(newRoot, newOptions); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); } [Fact] public void WithFilePath_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}", path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_DummyTree() { var oldTree = new CSharpSyntaxTree.DummySyntaxTree(); var newTree = oldTree.WithFilePath("new.cs"); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); } [Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")] public void WithFilePath_Null() { SyntaxTree oldTree = new CSharpSyntaxTree.DummySyntaxTree(); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); oldTree = SyntaxFactory.ParseSyntaxTree("", path: "old.cs"); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); Assert.Equal(string.Empty, SyntaxFactory.ParseSyntaxTree("", path: null).FilePath); Assert.Equal(string.Empty, CSharpSyntaxTree.Create((CSharpSyntaxNode)oldTree.GetRoot(), path: null).FilePath); } [Fact] public void GlobalUsingDirective_01() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_02() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_03() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_04() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_05() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_06() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using static ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_07() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_08() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using static ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_09() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_10() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using alias = ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_11() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_12() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using alias = ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_13() { var test = @" namespace ns {} global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_14() { var test = @" global using ns1; extern alias a; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias a; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_15() { var test = @" namespace ns2 { namespace ns {} global using ns1; } "; UsingTree(test, TestOptions.RegularPreview, // (5,5): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(5, 5) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_16() { var test = @" global using ns1; namespace ns {} "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_01() { var test = "d using ns1;"; UsingTree(test, TestOptions.Regular, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_17() { var test = "d global using ns1;"; UsingTree(test, TestOptions.RegularPreview, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d global using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_02() { var test = "using ns1; p using ns2;"; UsingTree(test, TestOptions.Regular, // (1,12): error CS0116: A namespace cannot directly contain members such as fields or methods // using ns1; p using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 12) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_18() { var test = "global using ns1; p global using ns2;"; UsingTree(test, TestOptions.RegularPreview, // (1,19): error CS0116: A namespace cannot directly contain members such as fields or methods // global using ns1; p global using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 19) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_19() { var test = @" M(); global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_20() { var test = @" global using ns1; using ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_21() { var test = @" global using alias1 = ns1; using alias2 = ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias1"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias2"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_22() { var test = @" global using static ns1; using static ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using static Roslyn.Test.Utilities.TestHelpers; using KeyValuePair = Roslyn.Utilities.KeyValuePairUtil; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class SyntaxTreeTests : ParsingTests { public SyntaxTreeTests(ITestOutputHelper output) : base(output) { } protected SyntaxTree UsingTree(string text, CSharpParseOptions options, params DiagnosticDescription[] expectedErrors) { var tree = base.UsingTree(text, options); var actualErrors = tree.GetDiagnostics(); actualErrors.Verify(expectedErrors); return tree; } // Diagnostic options on syntax trees are now obsolete #pragma warning disable CS0618 [Fact] public void CreateTreeWithDiagnostics() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.Create(SyntaxFactory.ParseCompilationUnit(""), options: null, path: "", encoding: null, diagnosticOptions: options); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void ParseTreeWithChangesPreservesDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); var newTree = tree.WithChangedText(SourceText.From("class C { }")); Assert.Same(options, newTree.DiagnosticOptions); } [Fact] public void ParseTreeNullDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: null, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); // The default options are case insensitive but the default empty ImmutableDictionary is not Assert.NotSame(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeEmptyDiagnosticOptions() { var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: ImmutableDictionary<string, ReportDiagnostic>.Empty, isGeneratedCode: null, cancellationToken: default); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); Assert.Same(ImmutableDictionary<string, ReportDiagnostic>.Empty, tree.DiagnosticOptions); } [Fact] public void ParseTreeCustomDiagnosticOptions() { var options = CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)); var tree = CSharpSyntaxTree.ParseText( SourceText.From(""), options: null, path: "", diagnosticOptions: options, isGeneratedCode: null, cancellationToken: default); Assert.Same(options, tree.DiagnosticOptions); } [Fact] public void DefaultTreeDiagnosticOptions() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); Assert.NotNull(tree.DiagnosticOptions); Assert.True(tree.DiagnosticOptions.IsEmpty); } [Fact] public void WithDiagnosticOptionsNull() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(null); Assert.NotNull(newTree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); Assert.Same(tree, newTree); } [Fact] public void WithDiagnosticOptionsEmpty() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var newTree = tree.WithDiagnosticOptions(ImmutableDictionary<string, ReportDiagnostic>.Empty); Assert.NotNull(tree.DiagnosticOptions); Assert.True(newTree.DiagnosticOptions.IsEmpty); // Default empty immutable dictionary is case sensitive Assert.NotSame(tree.DiagnosticOptions, newTree.DiagnosticOptions); } [Fact] public void PerTreeDiagnosticOptionsNewDict() { var tree = SyntaxFactory.SyntaxTree(SyntaxFactory.CompilationUnit()); var map = ImmutableDictionary.CreateRange( new[] { KeyValuePair.Create("CS00778", ReportDiagnostic.Suppress) }); var newTree = tree.WithDiagnosticOptions(map); Assert.NotNull(newTree.DiagnosticOptions); Assert.Same(map, newTree.DiagnosticOptions); Assert.NotEqual(tree, newTree); } #pragma warning restore CS0618 [Fact] public void WithRootAndOptions_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}"); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = oldTree.WithRootAndOptions(newRoot, newOptions); var newText = newTree.GetText(); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithRootAndOptions_DummyTree() { var dummy = new CSharpSyntaxTree.DummySyntaxTree(); var newRoot = SyntaxFactory.ParseCompilationUnit("class C {}"); var newOptions = new CSharpParseOptions(); var newTree = dummy.WithRootAndOptions(newRoot, newOptions); Assert.Equal(newRoot.ToString(), newTree.GetRoot().ToString()); Assert.Same(newOptions, newTree.Options); } [Fact] public void WithFilePath_ParsedTree() { var oldTree = SyntaxFactory.ParseSyntaxTree("class B {}", path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Null(newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha1, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_ParsedTreeWithText() { var oldText = SourceText.From("class B {}", Encoding.Unicode, SourceHashAlgorithm.Sha256); var oldTree = SyntaxFactory.ParseSyntaxTree(oldText, path: "old.cs"); var newTree = oldTree.WithFilePath("new.cs"); var newText = newTree.GetText(); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); Assert.Same(Encoding.Unicode, newText.Encoding); Assert.Equal(SourceHashAlgorithm.Sha256, newText.ChecksumAlgorithm); } [Fact] public void WithFilePath_DummyTree() { var oldTree = new CSharpSyntaxTree.DummySyntaxTree(); var newTree = oldTree.WithFilePath("new.cs"); Assert.Equal("new.cs", newTree.FilePath); Assert.Equal(oldTree.ToString(), newTree.ToString()); } [Fact, WorkItem(12638, "https://github.com/dotnet/roslyn/issues/12638")] public void WithFilePath_Null() { SyntaxTree oldTree = new CSharpSyntaxTree.DummySyntaxTree(); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); oldTree = SyntaxFactory.ParseSyntaxTree("", path: "old.cs"); Assert.Equal(string.Empty, oldTree.WithFilePath(null).FilePath); Assert.Equal(string.Empty, SyntaxFactory.ParseSyntaxTree("", path: null).FilePath); Assert.Equal(string.Empty, CSharpSyntaxTree.Create((CSharpSyntaxNode)oldTree.GetRoot(), path: null).FilePath); } [Fact] public void GlobalUsingDirective_01() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_02() { var test = "global using ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_03() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_04() { var test = "namespace ns { global using ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_05() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_06() { var test = "global using static ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using static ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_07() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular10); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_08() { var test = "namespace ns { global using static ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using static ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using static ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_09() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_10() { var test = "global using alias = ns1;"; UsingTree(test, TestOptions.Regular9, // (1,1): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // global using alias = ns1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_11() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_12() { var test = "namespace ns { global using alias = ns1; }"; UsingTree(test, TestOptions.Regular9, // (1,16): error CS8773: Feature 'global using directive' is not available in C# 9.0. Please use language version 10.0 or greater. // namespace ns { global using alias = ns1; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "global using alias = ns1;").WithArguments("global using directive", "10.0").WithLocation(1, 16) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_13() { var test = @" namespace ns {} global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_14() { var test = @" global using ns1; extern alias a; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS0439: An extern alias declaration must precede all other elements defined in the namespace // extern alias a; Diagnostic(ErrorCode.ERR_ExternAfterElements, "extern").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_15() { var test = @" namespace ns2 { namespace ns {} global using ns1; } "; UsingTree(test, TestOptions.RegularPreview, // (5,5): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(5, 5) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_16() { var test = @" global using ns1; namespace ns {} "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns"); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_01() { var test = "d using ns1;"; UsingTree(test, TestOptions.Regular, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_17() { var test = "d global using ns1;"; UsingTree(test, TestOptions.RegularPreview, // (1,1): error CS0116: A namespace cannot directly contain members such as fields or methods // d global using ns1; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "d").WithLocation(1, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void UsingDirective_02() { var test = "using ns1; p using ns2;"; UsingTree(test, TestOptions.Regular, // (1,12): error CS0116: A namespace cannot directly contain members such as fields or methods // using ns1; p using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 12) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_18() { var test = "global using ns1; p global using ns2;"; UsingTree(test, TestOptions.RegularPreview, // (1,19): error CS0116: A namespace cannot directly contain members such as fields or methods // global using ns1; p global using ns2; Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "p").WithLocation(1, 19) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_19() { var test = @" M(); global using ns1; "; UsingTree(test, TestOptions.RegularPreview, // (3,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations // global using ns1; Diagnostic(ErrorCode.ERR_UsingAfterElements, "global using ns1;").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_20() { var test = @" global using ns1; using ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_21() { var test = @" global using alias1 = ns1; using alias2 = ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias1"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.NameEquals); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "alias2"); } N(SyntaxKind.EqualsToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void GlobalUsingDirective_22() { var test = @" global using static ns1; using static ns2; M(); "; UsingTree(test, TestOptions.RegularPreview); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.GlobalKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns1"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.StaticKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ns2"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Syntax/ICompilationUnitSyntax.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> /// Interface implemented by any node that is the root 'CompilationUnit' of a <see cref="SyntaxTree"/>. i.e. /// any node returned by <see cref="SyntaxTree.GetRoot"/> where <see cref="SyntaxTree.HasCompilationUnitRoot"/> /// is <see langword="true"/> will implement this interface. /// /// This interface provides a common way to both easily find the root of a <see cref="SyntaxTree"/> /// given any <see cref="SyntaxNode"/>, as well as a common way for handling the special /// <see cref="EndOfFileToken"/> that is needed to store all final trivia in a <see cref="SourceText"/> /// that is not owned by any other <see cref="SyntaxToken"/>. /// </summary> public interface ICompilationUnitSyntax { /// <summary> /// Represents the end of the source file. This <see cref="SyntaxToken"/> may have /// <see cref="SyntaxTrivia"/> (whitespace, comments, directives) attached to it. /// </summary> SyntaxToken EndOfFileToken { 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> /// Interface implemented by any node that is the root 'CompilationUnit' of a <see cref="SyntaxTree"/>. i.e. /// any node returned by <see cref="SyntaxTree.GetRoot"/> where <see cref="SyntaxTree.HasCompilationUnitRoot"/> /// is <see langword="true"/> will implement this interface. /// /// This interface provides a common way to both easily find the root of a <see cref="SyntaxTree"/> /// given any <see cref="SyntaxNode"/>, as well as a common way for handling the special /// <see cref="EndOfFileToken"/> that is needed to store all final trivia in a <see cref="SourceText"/> /// that is not owned by any other <see cref="SyntaxToken"/>. /// </summary> public interface ICompilationUnitSyntax { /// <summary> /// Represents the end of the source file. This <see cref="SyntaxToken"/> may have /// <see cref="SyntaxTrivia"/> (whitespace, comments, directives) attached to it. /// </summary> SyntaxToken EndOfFileToken { get; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/IntegrationTests/AbstractEditorTest.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.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Roslyn.Test.Utilities; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests { public abstract class AbstractEditorTest : AbstractIntegrationTest { private readonly string _solutionName; private readonly string _projectTemplate; protected AbstractEditorTest(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } protected AbstractEditorTest(VisualStudioInstanceFactory instanceFactory, string solutionName) : this(instanceFactory, solutionName, WellKnownProjectTemplates.ClassLibrary) { } protected AbstractEditorTest( VisualStudioInstanceFactory instanceFactory, string solutionName, string projectTemplate) : base(instanceFactory) { _solutionName = solutionName; _projectTemplate = projectTemplate; } protected abstract string LanguageName { get; } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); if (_solutionName != null) { VisualStudio.SolutionExplorer.CreateSolution(_solutionName); VisualStudio.SolutionExplorer.AddProject(new ProjectUtils.Project(ProjectName), _projectTemplate, LanguageName); VisualStudio.SolutionExplorer.RestoreNuGetPackages(new ProjectUtils.Project(ProjectName)); // Winforms and XAML do not open text files on creation // so these editor tasks will not work if that is the project template being used. if (_projectTemplate != WellKnownProjectTemplates.WinFormsApplication && _projectTemplate != WellKnownProjectTemplates.WpfApplication && _projectTemplate != WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { VisualStudio.Editor.SetUseSuggestionMode(false); ClearEditor(); } // Work around potential hangs in 16.10p2 caused by the roslyn LSP server not completing initialization before solution closed. // By waiting for the async operation tracking roslyn LSP server activation to complete we should never // encounter the scenario where the solution closes while activation is incomplete. VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LanguageServer); } } protected void ClearEditor() => SetUpEditor("$$"); protected void SetUpEditor(string markupCode) { MarkupTestFile.GetPosition(markupCode, out var code, out int caretPosition); VisualStudio.Editor.DismissCompletionSessions(); VisualStudio.Editor.DismissLightBulbSession(); var originalValue = VisualStudio.Workspace.IsPrettyListingOn(LanguageName); VisualStudio.Workspace.SetPrettyListing(LanguageName, false); try { VisualStudio.Editor.SetText(code); VisualStudio.Editor.MoveCaret(caretPosition); VisualStudio.Editor.Activate(); } finally { VisualStudio.Workspace.SetPrettyListing(LanguageName, originalValue); } } protected ClassifiedToken[] GetLightbulbPreviewClassification(string menuText) { return VisualStudio.Editor.GetLightbulbPreviewClassification(menuText); } } }
// Licensed to the .NET Foundation under one or more 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.Shared.TestHooks; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common; using Roslyn.Test.Utilities; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests { public abstract class AbstractEditorTest : AbstractIntegrationTest { private readonly string _solutionName; private readonly string _projectTemplate; protected AbstractEditorTest(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } protected AbstractEditorTest(VisualStudioInstanceFactory instanceFactory, string solutionName) : this(instanceFactory, solutionName, WellKnownProjectTemplates.ClassLibrary) { } protected AbstractEditorTest( VisualStudioInstanceFactory instanceFactory, string solutionName, string projectTemplate) : base(instanceFactory) { _solutionName = solutionName; _projectTemplate = projectTemplate; } protected abstract string LanguageName { get; } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); if (_solutionName != null) { VisualStudio.SolutionExplorer.CreateSolution(_solutionName); VisualStudio.SolutionExplorer.AddProject(new ProjectUtils.Project(ProjectName), _projectTemplate, LanguageName); VisualStudio.SolutionExplorer.RestoreNuGetPackages(new ProjectUtils.Project(ProjectName)); // Winforms and XAML do not open text files on creation // so these editor tasks will not work if that is the project template being used. if (_projectTemplate != WellKnownProjectTemplates.WinFormsApplication && _projectTemplate != WellKnownProjectTemplates.WpfApplication && _projectTemplate != WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { VisualStudio.Editor.SetUseSuggestionMode(false); ClearEditor(); } // Work around potential hangs in 16.10p2 caused by the roslyn LSP server not completing initialization before solution closed. // By waiting for the async operation tracking roslyn LSP server activation to complete we should never // encounter the scenario where the solution closes while activation is incomplete. VisualStudio.Workspace.WaitForAsyncOperations(Helper.HangMitigatingTimeout, FeatureAttribute.LanguageServer); } } protected void ClearEditor() => SetUpEditor("$$"); protected void SetUpEditor(string markupCode) { MarkupTestFile.GetPosition(markupCode, out var code, out int caretPosition); VisualStudio.Editor.DismissCompletionSessions(); VisualStudio.Editor.DismissLightBulbSession(); var originalValue = VisualStudio.Workspace.IsPrettyListingOn(LanguageName); VisualStudio.Workspace.SetPrettyListing(LanguageName, false); try { VisualStudio.Editor.SetText(code); VisualStudio.Editor.MoveCaret(caretPosition); VisualStudio.Editor.Activate(); } finally { VisualStudio.Workspace.SetPrettyListing(LanguageName, originalValue); } } protected ClassifiedToken[] GetLightbulbPreviewClassification(string menuText) { return VisualStudio.Editor.GetLightbulbPreviewClassification(menuText); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Emit/DebugDocumentsBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit { internal sealed class DebugDocumentsBuilder { // This is a map from the document "name" to the document. // Document "name" is typically a file path like "C:\Abc\Def.cs". However, that is not guaranteed. // For compatibility reasons the names are treated as case-sensitive in C# and case-insensitive in VB. // Neither language trims the names, so they are both sensitive to the leading and trailing whitespaces. // NOTE: We are not considering how filesystem or debuggers do the comparisons, but how native implementations did. // Deviating from that may result in unexpected warnings or different behavior (possibly without warnings). private readonly ConcurrentDictionary<string, Cci.DebugSourceDocument> _debugDocuments; private readonly ConcurrentCache<(string, string?), string> _normalizedPathsCache; private readonly SourceReferenceResolver? _resolver; public DebugDocumentsBuilder(SourceReferenceResolver? resolver, bool isDocumentNameCaseSensitive) { _resolver = resolver; _debugDocuments = new ConcurrentDictionary<string, Cci.DebugSourceDocument>( isDocumentNameCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); _normalizedPathsCache = new ConcurrentCache<(string, string?), string>(16); } internal int DebugDocumentCount => _debugDocuments.Count; internal void AddDebugDocument(Cci.DebugSourceDocument document) { _debugDocuments.Add(document.Location, document); } internal IReadOnlyDictionary<string, Cci.DebugSourceDocument> DebugDocuments => _debugDocuments; internal Cci.DebugSourceDocument? TryGetDebugDocument(string path, string basePath) { return TryGetDebugDocumentForNormalizedPath(NormalizeDebugDocumentPath(path, basePath)); } internal Cci.DebugSourceDocument? TryGetDebugDocumentForNormalizedPath(string normalizedPath) { Cci.DebugSourceDocument? document; _debugDocuments.TryGetValue(normalizedPath, out document); return document; } internal Cci.DebugSourceDocument GetOrAddDebugDocument(string path, string basePath, Func<string, Cci.DebugSourceDocument> factory) { return _debugDocuments.GetOrAdd(NormalizeDebugDocumentPath(path, basePath), factory); } internal string NormalizeDebugDocumentPath(string path, string? basePath) { if (_resolver == null) { return path; } var key = (path, basePath); string? normalizedPath; if (!_normalizedPathsCache.TryGetValue(key, out normalizedPath)) { normalizedPath = _resolver.NormalizePath(path, basePath) ?? path; _normalizedPathsCache.TryAdd(key, normalizedPath); } return normalizedPath; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Emit { internal sealed class DebugDocumentsBuilder { // This is a map from the document "name" to the document. // Document "name" is typically a file path like "C:\Abc\Def.cs". However, that is not guaranteed. // For compatibility reasons the names are treated as case-sensitive in C# and case-insensitive in VB. // Neither language trims the names, so they are both sensitive to the leading and trailing whitespaces. // NOTE: We are not considering how filesystem or debuggers do the comparisons, but how native implementations did. // Deviating from that may result in unexpected warnings or different behavior (possibly without warnings). private readonly ConcurrentDictionary<string, Cci.DebugSourceDocument> _debugDocuments; private readonly ConcurrentCache<(string, string?), string> _normalizedPathsCache; private readonly SourceReferenceResolver? _resolver; public DebugDocumentsBuilder(SourceReferenceResolver? resolver, bool isDocumentNameCaseSensitive) { _resolver = resolver; _debugDocuments = new ConcurrentDictionary<string, Cci.DebugSourceDocument>( isDocumentNameCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase); _normalizedPathsCache = new ConcurrentCache<(string, string?), string>(16); } internal int DebugDocumentCount => _debugDocuments.Count; internal void AddDebugDocument(Cci.DebugSourceDocument document) { _debugDocuments.Add(document.Location, document); } internal IReadOnlyDictionary<string, Cci.DebugSourceDocument> DebugDocuments => _debugDocuments; internal Cci.DebugSourceDocument? TryGetDebugDocument(string path, string basePath) { return TryGetDebugDocumentForNormalizedPath(NormalizeDebugDocumentPath(path, basePath)); } internal Cci.DebugSourceDocument? TryGetDebugDocumentForNormalizedPath(string normalizedPath) { Cci.DebugSourceDocument? document; _debugDocuments.TryGetValue(normalizedPath, out document); return document; } internal Cci.DebugSourceDocument GetOrAddDebugDocument(string path, string basePath, Func<string, Cci.DebugSourceDocument> factory) { return _debugDocuments.GetOrAdd(NormalizeDebugDocumentPath(path, basePath), factory); } internal string NormalizeDebugDocumentPath(string path, string? basePath) { if (_resolver == null) { return path; } var key = (path, basePath); string? normalizedPath; if (!_normalizedPathsCache.TryGetValue(key, out normalizedPath)) { normalizedPath = _resolver.NormalizePath(path, basePath) ?? path; _normalizedPathsCache.TryAdd(key, normalizedPath); } return normalizedPath; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/VisualBasicEntryPointFinderService.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.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim <ExportLanguageService(GetType(IEntryPointFinderService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEntryPointFinderService Implements IEntryPointFinderService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function FindEntryPoints(symbol As INamespaceSymbol, findFormsOnly As Boolean) As IEnumerable(Of INamedTypeSymbol) Implements IEntryPointFinderService.FindEntryPoints Return EntryPointFinder.FindEntryPoints(symbol, findFormsOnly) 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.Composition Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim <ExportLanguageService(GetType(IEntryPointFinderService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicEntryPointFinderService Implements IEntryPointFinderService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function FindEntryPoints(symbol As INamespaceSymbol, findFormsOnly As Boolean) As IEnumerable(Of INamedTypeSymbol) Implements IEntryPointFinderService.FindEntryPoints Return EntryPointFinder.FindEntryPoints(symbol, findFormsOnly) End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Tests/QualifyMemberAccess/QualifyMemberAccessTests.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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.QualifyMemberAccess; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QualifyMemberAccess { public partial class QualifyMemberAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public QualifyMemberAccessTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpQualifyMemberAccessDiagnosticAnalyzer(), new CSharpQualifyMemberAccessCodeFixProvider()); private Task TestAsyncWithOption(string code, string expected, PerLanguageOption2<CodeStyleOption2<bool>> option) => TestAsyncWithOptionAndNotificationOption(code, expected, option, NotificationOption2.Error); private Task TestAsyncWithOptionAndNotificationOption(string code, string expected, PerLanguageOption2<CodeStyleOption2<bool>> option, NotificationOption2 notification) => TestInRegularAndScriptAsync(code, expected, options: Option(option, true, notification)); private Task TestMissingAsyncWithOption(string code, PerLanguageOption2<CodeStyleOption2<bool>> option) => TestMissingAsyncWithOptionAndNotificationOption(code, option, NotificationOption2.Error); private Task TestMissingAsyncWithOptionAndNotificationOption(string code, PerLanguageOption2<CodeStyleOption2<bool>> option, NotificationOption2 notification) => TestMissingInRegularAndScriptAsync(code, new TestParameters(options: Option(option, true, notification))); [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_LHS() { await TestAsyncWithOption( @"class Class { int i; void M() { [|i|] = 1; } }", @"class Class { int i; void M() { this.i = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_RHS() { await TestAsyncWithOption( @"class Class { int i; void M() { var x = [|i|]; } }", @"class Class { int i; void M() { var x = this.i; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_MethodArgument() { await TestAsyncWithOption( @"class Class { int i; void M(int ii) { M([|i|]); } }", @"class Class { int i; void M(int ii) { M(this.i); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_ChainedAccess() { await TestAsyncWithOption( @"class Class { int i; void M() { var s = [|i|].ToString(); } }", @"class Class { int i; void M() { var s = this.i.ToString(); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_ConditionalAccess() { await TestAsyncWithOption( @"class Class { string s; void M() { var x = [|s|]?.ToString(); } }", @"class Class { string s; void M() { var x = this.s?.ToString(); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_OnBase() { await TestAsyncWithOption( @"class Base { protected int i; } class Derived : Base { void M() { [|i|] = 1; } }", @"class Base { protected int i; } class Derived : Base { void M() { this.i = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_InObjectInitializer() { await TestAsyncWithOption( @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { [|i|] }; } }", @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { this.i }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_InCollectionInitializer() { await TestAsyncWithOption( @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { [|i|] }; } }", @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { this.i }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"class Class { int i; void M() { Class c = new Class(); c.[|i|] = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"class C { static int i; void M() { [|i|] = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInObjectInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInCollectionInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28091, "https://github.com/dotnet/roslyn/issues/28091")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInDictionaryInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.Dictionary<int, int> { { 2, [|foo|] } }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_Subpattern1() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { if (c is { [|i|]: 1 }) { } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_Subpattern2() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { switch (t) { case Class { [|i|]: 1 }: return; } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_Subpattern3() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { var a = c switch { { [|i|]: 0 } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_LHS() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M() { [|i|] = 1; } }", @"class Class { int i { get; set; } void M() { this.i = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_RHS() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M() { var x = [|i|]; } }", @"class Class { int i { get; set; } void M() { var x = this.i; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern1() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { if (c is { [|i|]: 1 }) { } } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern2() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { switch (t) { case Class { [|i|]: 1 }: return; } } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern3() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { var a = c switch { { [|i|]: 0 } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern4() { // it's ok that we qualify here because it's not a legal pattern (because it is not const). await TestAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { var a = c switch { { i: [|i|] } => 1, _ => 0 }; } }", @"class Class { int i { get; set; } void M(Class c) { var a = c switch { { i: this.i } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern1() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { if (c is { [|i|]: 1 }) { } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern2() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { switch (t) { case Class { [|i|]: 1 }: return; } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern3() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { var a = c switch { { [|i|]: 0 } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern4() { // it's ok that we qualify here because it's not a legal pattern (because it is not const). await TestAsyncWithOption( @"class Class { int i; void M(Class c) { var a = c switch { { i: [|i|] } => 1, _ => 0 }; } }", @"class Class { int i; void M(Class c) { var a = c switch { { i: this.i } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_MethodArgument() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M(int ii) { M([|i|]); } }", @"class Class { int i { get; set; } void M(int ii) { M(this.i); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_ChainedAccess() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M() { var s = [|i|].ToString(); } }", @"class Class { int i { get; set; } void M() { var s = this.i.ToString(); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_ConditionalAccess() { await TestAsyncWithOption( @"class Class { string s { get; set; } void M() { var x = [|s|]?.ToString(); } }", @"class Class { string s { get; set; } void M() { var x = this.s?.ToString(); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_OnBase() { await TestAsyncWithOption( @"class Base { protected int i { get; set; } } class Derived : Base { void M() { [|i|] = 1; } }", @"class Base { protected int i { get; set; } } class Derived : Base { void M() { this.i = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { c.[|i|] = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"class C { static int i { get; set; } void M() { [|i|] = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_VoidCallWithArguments() { await TestAsyncWithOption( @"class Class { void M(int i) { [|M|](0); } }", @"class Class { void M(int i) { this.M(0); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_AsReturn() { await TestAsyncWithOption( @"class Class { int M() { return [|M|](); }", @"class Class { int M() { return this.M(); }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_ChainedAccess() { await TestAsyncWithOption( @"class Class { string M() { var s = [|M|]().ToString(); }", @"class Class { string M() { var s = this.M().ToString(); }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_ConditionalAccess() { await TestAsyncWithOption( @"class Class { string M() { return [|M|]()?.ToString(); }", @"class Class { string M() { return this.M()?.ToString(); }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_EventSubscription1() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += [|Handler|]; } }", @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += this.Handler; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_EventSubscription2() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += new EventHandler([|Handler|]); } }", @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += new EventHandler(this.Handler); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_OnBase() { await TestAsyncWithOption( @"class Base { protected void Method() { } } class Derived : Base { void M() { [|Method|](); } }", @"class Base { protected void Method() { } } class Derived : Base { void M() { this.Method(); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"class Class { void M(Class c) { c.[|M|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"class C { static void Method() { } void M() { [|Method|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnObjectInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedOnObjectInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { int Local() => 1; var test = new System.Collections.Generic.List<int> { [|Local()|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnCollectionInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedOnCollectionInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { int Local() => 1; var test = new System.Collections.Generic.List<int> { [|Local()|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInMethodCall() { await TestMissingAsyncWithOption( @"class C { void M() { int Local() => 1; [|Local|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInNestedMethodCall() { await TestMissingAsyncWithOption( @"using System; class C { void Method() { object LocalFunction() => new object(); this.Method2([|LocalFunction|]); } void Method2(Func<object> LocalFunction) { } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInCollectionInitializer() { await TestMissingAsyncWithOption( @"using System; using System.Collections.Generic; class C { void Method() { object LocalFunction() => new object(); var dict = new Dictionary<Func<object>, int>() { { [|LocalFunction|], 1 } }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInObjectMethodInvocation() { await TestMissingAsyncWithOption( @"using System; class C { void Method() { object LocalFunction() => new object(); [|LocalFunction|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_EventSubscription() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { this.e += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccessAsProperty_EventSubscription() { await TestAsyncWithOption( @"using System; class C { event EventHandler e { add { } remove { } } void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", @"using System; class C { event EventHandler e { add { } remove { } } void Handler(object sender, EventArgs args) { this.e += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_InvokeEvent1() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void OnSomeEvent() { [|e|](this, new EventArgs()); } }", @"using System; class C { event EventHandler e; void OnSomeEvent() { this.e(this, new EventArgs()); } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_InvokeEvent2() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void OnSomeEvent() { [|e|].Invoke(this, new EventArgs()); } }", @"using System; class C { event EventHandler e; void OnSomeEvent() { this.e.Invoke(this, new EventArgs()); } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_InvokeEvent3() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void OnSomeEvent() { [|e|]?.Invoke(this, new EventArgs()); } }", @"using System; class C { event EventHandler e; void OnSomeEvent() { this.e?.Invoke(this, new EventArgs()); } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_OnBase() { await TestAsyncWithOption( @"using System; class Base { protected event EventHandler e; } class Derived : Base { void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", @"using System; class Base { protected event EventHandler e; } class Derived : Base { void Handler(object sender, EventArgs args) { this.e += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"using System; class Class { event EventHandler e; void M(Class c) { c.[|e|] += Handler; } void Handler(object sender, EventArgs args) { } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"using System; class C { static event EventHandler e; } void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionSilent() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Silent); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionInfo() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Suggestion); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionWarning() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionError() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Error); } [WorkItem(15325, "https://github.com/dotnet/roslyn/issues/15325")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/18839"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyInstanceMethodInDelegateCreation() { await TestAsyncWithOption( @"using System; class A { int Function(int x) => x + x; void Error() { var func = new Func<int, int>([|Function|]); func(1); } }", @"using System; class A { int Function(int x) => x + x; void Error() { var func = new Func<int, int>(this.Function); func(1); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(15325, "https://github.com/dotnet/roslyn/issues/15325")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotQualifyStaticMethodInDelegateCreation() { await TestMissingAsyncWithOption( @"using System; class A { static int Function(int x) => x + x; void Error() { var func = new Func<int, int>([|Function|]); func(1); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnField() { await TestMissingAsyncWithOption( @"class Base { protected int field; } class Derived : Base { void M() { [|base.field|] = 0; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnProperty() { await TestMissingAsyncWithOption( @"class Base { protected virtual int Property { get; } } class Derived : Base { protected override int Property { get { return [|base.Property|]; } } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnMethod() { await TestMissingAsyncWithOption( @"class Base { protected virtual void M() { } } class Derived : Base { protected override void M() { [|base.M()|]; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnEvent() { await TestMissingAsyncWithOption( @"class Base { protected virtual event EventHandler Event; } class Derived : Base { protected override event EventHandler Event { add { [|base.Event|] += value; } remove { } } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext1() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } public static string Bar = nameof([|Foo|]); }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext2() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } public string Bar = nameof([|Foo|]); }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext3() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } static void Main(string[] args) { System.Console.WriteLine(nameof([|Foo|])); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext4() { await TestMissingAsyncWithOption( @"class Program { public int Foo; static void Main(string[] args) { System.Console.WriteLine(nameof([|Foo|])); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext5() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } static string Bar { get; set; } static Program() { Bar = nameof([|Foo|]); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext6() { await TestMissingAsyncWithOption( @"public class Foo { public event EventHandler Bar; private string Field = nameof([|Bar|]); }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(32093, "https://github.com/dotnet/roslyn/issues/32093")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInBaseConstructor() { await TestMissingAsyncWithOption( @"public class Base { public string Foo { get; } public Base(string foo){} } public class Derived : Base { public Derived() : base(nameof([|Foo|])) {} } ", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InAccessorExpressionBody() { await TestAsyncWithOption( @"public class C { public string Foo { get; set; } public string Bar { get => [|Foo|]; } }", @"public class C { public string Foo { get; set; } public string Bar { get => this.Foo; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody1() { await TestAsyncWithOption( @"public class C { public string Foo { get; set; } public string Bar { get { return [|Foo|]; } => Foo; } }", @"public class C { public string Foo { get; set; } public string Bar { get { return this.Foo; } => Foo; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody2() { await TestAsyncWithOption( @"public class C { public string Foo { get; set; } public string Bar { get { return Foo; } => [|Foo|]; } }", @"public class C { public string Foo { get; set; } public string Bar { get { return Foo; } => this.Foo; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InObjectInitializer() { await TestAsyncWithOption( @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { [|Foo|] }; } }", @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { this.Foo }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InCollectionInitializer() { await TestAsyncWithOption( @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { [|Foo|] }; } }", @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { this.Foo }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_InObjectInitializer1() { await TestMissingAsyncWithOption( @"public class C { public string Foo { get; set; } public void Bar() { var c = new C { [|Foo|] = string.Empty }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_InObjectInitializer2() { await TestMissingAsyncWithOption( @"public class C { public string Foo; public void Bar() { var c = new C { [|Foo|] = string.Empty }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute1() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } [My(nameof([|Goo|]))] class Program { int Goo { get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute2() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { [My(nameof([|Goo|]))] int Goo { get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute3() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { [My(nameof([|Goo|]))] public int Bar = 0 ; public int Goo { get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute4() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { int Goo { [My(nameof([|Goo|]))]get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute5() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { int Goo { get; set; } void M([My(nameof([|Goo|]))]int i) { } }", CodeStyleOptions2.QualifyPropertyAccess); } } }
// Licensed to the .NET Foundation under one or more 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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.QualifyMemberAccess; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QualifyMemberAccess { public partial class QualifyMemberAccessTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { public QualifyMemberAccessTests(ITestOutputHelper logger) : base(logger) { } internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpQualifyMemberAccessDiagnosticAnalyzer(), new CSharpQualifyMemberAccessCodeFixProvider()); private Task TestAsyncWithOption(string code, string expected, PerLanguageOption2<CodeStyleOption2<bool>> option) => TestAsyncWithOptionAndNotificationOption(code, expected, option, NotificationOption2.Error); private Task TestAsyncWithOptionAndNotificationOption(string code, string expected, PerLanguageOption2<CodeStyleOption2<bool>> option, NotificationOption2 notification) => TestInRegularAndScriptAsync(code, expected, options: Option(option, true, notification)); private Task TestMissingAsyncWithOption(string code, PerLanguageOption2<CodeStyleOption2<bool>> option) => TestMissingAsyncWithOptionAndNotificationOption(code, option, NotificationOption2.Error); private Task TestMissingAsyncWithOptionAndNotificationOption(string code, PerLanguageOption2<CodeStyleOption2<bool>> option, NotificationOption2 notification) => TestMissingInRegularAndScriptAsync(code, new TestParameters(options: Option(option, true, notification))); [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_LHS() { await TestAsyncWithOption( @"class Class { int i; void M() { [|i|] = 1; } }", @"class Class { int i; void M() { this.i = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_RHS() { await TestAsyncWithOption( @"class Class { int i; void M() { var x = [|i|]; } }", @"class Class { int i; void M() { var x = this.i; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_MethodArgument() { await TestAsyncWithOption( @"class Class { int i; void M(int ii) { M([|i|]); } }", @"class Class { int i; void M(int ii) { M(this.i); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_ChainedAccess() { await TestAsyncWithOption( @"class Class { int i; void M() { var s = [|i|].ToString(); } }", @"class Class { int i; void M() { var s = this.i.ToString(); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_ConditionalAccess() { await TestAsyncWithOption( @"class Class { string s; void M() { var x = [|s|]?.ToString(); } }", @"class Class { string s; void M() { var x = this.s?.ToString(); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_OnBase() { await TestAsyncWithOption( @"class Base { protected int i; } class Derived : Base { void M() { [|i|] = 1; } }", @"class Base { protected int i; } class Derived : Base { void M() { this.i = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_InObjectInitializer() { await TestAsyncWithOption( @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { [|i|] }; } }", @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { this.i }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_InCollectionInitializer() { await TestAsyncWithOption( @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { [|i|] }; } }", @"class C { int i = 1; void M() { var test = new System.Collections.Generic.List<int> { this.i }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"class Class { int i; void M() { Class c = new Class(); c.[|i|] = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"class C { static int i; void M() { [|i|] = 1; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInObjectInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInCollectionInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(28091, "https://github.com/dotnet/roslyn/issues/28091")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_NotSuggestedOnLocalVarInDictionaryInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.Dictionary<int, int> { { 2, [|foo|] } }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_Subpattern1() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { if (c is { [|i|]: 1 }) { } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_Subpattern2() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { switch (t) { case Class { [|i|]: 1 }: return; } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyFieldAccess_Subpattern3() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { var a = c switch { { [|i|]: 0 } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_LHS() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M() { [|i|] = 1; } }", @"class Class { int i { get; set; } void M() { this.i = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_RHS() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M() { var x = [|i|]; } }", @"class Class { int i { get; set; } void M() { var x = this.i; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern1() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { if (c is { [|i|]: 1 }) { } } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern2() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { switch (t) { case Class { [|i|]: 1 }: return; } } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern3() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { var a = c switch { { [|i|]: 0 } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_PropertySubpattern4() { // it's ok that we qualify here because it's not a legal pattern (because it is not const). await TestAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { var a = c switch { { i: [|i|] } => 1, _ => 0 }; } }", @"class Class { int i { get; set; } void M(Class c) { var a = c switch { { i: this.i } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern1() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { if (c is { [|i|]: 1 }) { } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern2() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { switch (t) { case Class { [|i|]: 1 }: return; } } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern3() { await TestMissingAsyncWithOption( @"class Class { int i; void M(Class c) { var a = c switch { { [|i|]: 0 } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(40242, "https://github.com/dotnet/roslyn/issues/40242")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_FieldSubpattern4() { // it's ok that we qualify here because it's not a legal pattern (because it is not const). await TestAsyncWithOption( @"class Class { int i; void M(Class c) { var a = c switch { { i: [|i|] } => 1, _ => 0 }; } }", @"class Class { int i; void M(Class c) { var a = c switch { { i: this.i } => 1, _ => 0 }; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_MethodArgument() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M(int ii) { M([|i|]); } }", @"class Class { int i { get; set; } void M(int ii) { M(this.i); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_ChainedAccess() { await TestAsyncWithOption( @"class Class { int i { get; set; } void M() { var s = [|i|].ToString(); } }", @"class Class { int i { get; set; } void M() { var s = this.i.ToString(); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_ConditionalAccess() { await TestAsyncWithOption( @"class Class { string s { get; set; } void M() { var x = [|s|]?.ToString(); } }", @"class Class { string s { get; set; } void M() { var x = this.s?.ToString(); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_OnBase() { await TestAsyncWithOption( @"class Base { protected int i { get; set; } } class Derived : Base { void M() { [|i|] = 1; } }", @"class Base { protected int i { get; set; } } class Derived : Base { void M() { this.i = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"class Class { int i { get; set; } void M(Class c) { c.[|i|] = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"class C { static int i { get; set; } void M() { [|i|] = 1; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_VoidCallWithArguments() { await TestAsyncWithOption( @"class Class { void M(int i) { [|M|](0); } }", @"class Class { void M(int i) { this.M(0); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_AsReturn() { await TestAsyncWithOption( @"class Class { int M() { return [|M|](); }", @"class Class { int M() { return this.M(); }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_ChainedAccess() { await TestAsyncWithOption( @"class Class { string M() { var s = [|M|]().ToString(); }", @"class Class { string M() { var s = this.M().ToString(); }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_ConditionalAccess() { await TestAsyncWithOption( @"class Class { string M() { return [|M|]()?.ToString(); }", @"class Class { string M() { return this.M()?.ToString(); }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_EventSubscription1() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += [|Handler|]; } }", @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += this.Handler; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_EventSubscription2() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += new EventHandler([|Handler|]); } }", @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { e += new EventHandler(this.Handler); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_OnBase() { await TestAsyncWithOption( @"class Base { protected void Method() { } } class Derived : Base { void M() { [|Method|](); } }", @"class Base { protected void Method() { } } class Derived : Base { void M() { this.Method(); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"class Class { void M(Class c) { c.[|M|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"class C { static void Method() { } void M() { [|Method|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnObjectInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedOnObjectInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { int Local() => 1; var test = new System.Collections.Generic.List<int> { [|Local()|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMethodAccess_NotSuggestedOnCollectionInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { var foo = 1; var test = new System.Collections.Generic.List<int> { [|foo|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedOnCollectionInitializer() { await TestMissingAsyncWithOption( @"class C { void M() { int Local() => 1; var test = new System.Collections.Generic.List<int> { [|Local()|] }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInMethodCall() { await TestMissingAsyncWithOption( @"class C { void M() { int Local() => 1; [|Local|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInNestedMethodCall() { await TestMissingAsyncWithOption( @"using System; class C { void Method() { object LocalFunction() => new object(); this.Method2([|LocalFunction|]); } void Method2(Func<object> LocalFunction) { } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInCollectionInitializer() { await TestMissingAsyncWithOption( @"using System; using System.Collections.Generic; class C { void Method() { object LocalFunction() => new object(); var dict = new Dictionary<Func<object>, int>() { { [|LocalFunction|], 1 } }; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(38043, "https://github.com/dotnet/roslyn/issues/38043")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyLocalMethodAccess_NotSuggestedInObjectMethodInvocation() { await TestMissingAsyncWithOption( @"using System; class C { void Method() { object LocalFunction() => new object(); [|LocalFunction|](); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_EventSubscription() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", @"using System; class C { event EventHandler e; void Handler(object sender, EventArgs args) { this.e += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccessAsProperty_EventSubscription() { await TestAsyncWithOption( @"using System; class C { event EventHandler e { add { } remove { } } void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", @"using System; class C { event EventHandler e { add { } remove { } } void Handler(object sender, EventArgs args) { this.e += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_InvokeEvent1() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void OnSomeEvent() { [|e|](this, new EventArgs()); } }", @"using System; class C { event EventHandler e; void OnSomeEvent() { this.e(this, new EventArgs()); } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_InvokeEvent2() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void OnSomeEvent() { [|e|].Invoke(this, new EventArgs()); } }", @"using System; class C { event EventHandler e; void OnSomeEvent() { this.e.Invoke(this, new EventArgs()); } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_InvokeEvent3() { await TestAsyncWithOption( @"using System; class C { event EventHandler e; void OnSomeEvent() { [|e|]?.Invoke(this, new EventArgs()); } }", @"using System; class C { event EventHandler e; void OnSomeEvent() { this.e?.Invoke(this, new EventArgs()); } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/7587"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_OnBase() { await TestAsyncWithOption( @"using System; class Base { protected event EventHandler e; } class Derived : Base { void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", @"using System; class Base { protected event EventHandler e; } class Derived : Base { void Handler(object sender, EventArgs args) { this.e += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_NotSuggestedOnInstance() { await TestMissingAsyncWithOption( @"using System; class Class { event EventHandler e; void M(Class c) { c.[|e|] += Handler; } void Handler(object sender, EventArgs args) { } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(7065, "https://github.com/dotnet/roslyn/issues/7065")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyEventAccess_NotSuggestedOnStatic() { await TestMissingAsyncWithOption( @"using System; class C { static event EventHandler e; } void Handler(object sender, EventArgs args) { [|e|] += Handler; } }", CodeStyleOptions2.QualifyEventAccess); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionSilent() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Silent); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionInfo() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Suggestion); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionWarning() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Warning); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyMemberAccessOnNotificationOptionError() { await TestAsyncWithOptionAndNotificationOption( @"class Class { int Property { get; set; }; void M() { [|Property|] = 1; } }", @"class Class { int Property { get; set; }; void M() { this.Property = 1; } }", CodeStyleOptions2.QualifyPropertyAccess, NotificationOption2.Error); } [WorkItem(15325, "https://github.com/dotnet/roslyn/issues/15325")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/18839"), Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyInstanceMethodInDelegateCreation() { await TestAsyncWithOption( @"using System; class A { int Function(int x) => x + x; void Error() { var func = new Func<int, int>([|Function|]); func(1); } }", @"using System; class A { int Function(int x) => x + x; void Error() { var func = new Func<int, int>(this.Function); func(1); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(15325, "https://github.com/dotnet/roslyn/issues/15325")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotQualifyStaticMethodInDelegateCreation() { await TestMissingAsyncWithOption( @"using System; class A { static int Function(int x) => x + x; void Error() { var func = new Func<int, int>([|Function|]); func(1); } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnField() { await TestMissingAsyncWithOption( @"class Base { protected int field; } class Derived : Base { void M() { [|base.field|] = 0; } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnProperty() { await TestMissingAsyncWithOption( @"class Base { protected virtual int Property { get; } } class Derived : Base { protected override int Property { get { return [|base.Property|]; } } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnMethod() { await TestMissingAsyncWithOption( @"class Base { protected virtual void M() { } } class Derived : Base { protected override void M() { [|base.M()|]; } }", CodeStyleOptions2.QualifyMethodAccess); } [WorkItem(17711, "https://github.com/dotnet/roslyn/issues/17711")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfBaseQualificationOnEvent() { await TestMissingAsyncWithOption( @"class Base { protected virtual event EventHandler Event; } class Derived : Base { protected override event EventHandler Event { add { [|base.Event|] += value; } remove { } } }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext1() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } public static string Bar = nameof([|Foo|]); }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext2() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } public string Bar = nameof([|Foo|]); }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext3() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } static void Main(string[] args) { System.Console.WriteLine(nameof([|Foo|])); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext4() { await TestMissingAsyncWithOption( @"class Program { public int Foo; static void Main(string[] args) { System.Console.WriteLine(nameof([|Foo|])); } }", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext5() { await TestMissingAsyncWithOption( @"class Program { public int Foo { get; set; } static string Bar { get; set; } static Program() { Bar = nameof([|Foo|]); } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInStaticContext6() { await TestMissingAsyncWithOption( @"public class Foo { public event EventHandler Bar; private string Field = nameof([|Bar|]); }", CodeStyleOptions2.QualifyEventAccess); } [WorkItem(32093, "https://github.com/dotnet/roslyn/issues/32093")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInBaseConstructor() { await TestMissingAsyncWithOption( @"public class Base { public string Foo { get; } public Base(string foo){} } public class Derived : Base { public Derived() : base(nameof([|Foo|])) {} } ", CodeStyleOptions2.QualifyFieldAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InAccessorExpressionBody() { await TestAsyncWithOption( @"public class C { public string Foo { get; set; } public string Bar { get => [|Foo|]; } }", @"public class C { public string Foo { get; set; } public string Bar { get => this.Foo; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody1() { await TestAsyncWithOption( @"public class C { public string Foo { get; set; } public string Bar { get { return [|Foo|]; } => Foo; } }", @"public class C { public string Foo { get; set; } public string Bar { get { return this.Foo; } => Foo; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(21519, "https://github.com/dotnet/roslyn/issues/21519")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InAccessorWithBodyAndExpressionBody2() { await TestAsyncWithOption( @"public class C { public string Foo { get; set; } public string Bar { get { return Foo; } => [|Foo|]; } }", @"public class C { public string Foo { get; set; } public string Bar { get { return Foo; } => this.Foo; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InObjectInitializer() { await TestAsyncWithOption( @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { [|Foo|] }; } }", @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { this.Foo }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(28509, "https://github.com/dotnet/roslyn/issues/28509")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task QualifyPropertyAccess_InCollectionInitializer() { await TestAsyncWithOption( @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { [|Foo|] }; } }", @"class C { public int Foo { get; set } void M() { var test = new System.Collections.Generic.List<int> { this.Foo }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_InObjectInitializer1() { await TestMissingAsyncWithOption( @"public class C { public string Foo { get; set; } public void Bar() { var c = new C { [|Foo|] = string.Empty }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(22776, "https://github.com/dotnet/roslyn/issues/22776")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_InObjectInitializer2() { await TestMissingAsyncWithOption( @"public class C { public string Foo; public void Bar() { var c = new C { [|Foo|] = string.Empty }; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute1() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } [My(nameof([|Goo|]))] class Program { int Goo { get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute2() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { [My(nameof([|Goo|]))] int Goo { get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute3() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { [My(nameof([|Goo|]))] public int Bar = 0 ; public int Goo { get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute4() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { int Goo { [My(nameof([|Goo|]))]get; set; } }", CodeStyleOptions2.QualifyPropertyAccess); } [WorkItem(26893, "https://github.com/dotnet/roslyn/issues/26893")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)] public async Task DoNotReportToQualify_IfInAttribute5() { await TestMissingAsyncWithOption( @" using System; class MyAttribute : Attribute { public MyAttribute(string name) { } } class Program { int Goo { get; set; } void M([My(nameof([|Goo|]))]int i) { } }", CodeStyleOptions2.QualifyPropertyAccess); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Interactive/AbstractResetInteractiveCommand.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 EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Roslyn.VisualStudio.Services.Interactive { internal abstract class AbstractResetInteractiveCommand : IResetInteractiveCommand { private readonly VisualStudioWorkspace _workspace; private readonly IComponentModel _componentModel; private readonly VsInteractiveWindowProvider _interactiveWindowProvider; private readonly IServiceProvider _serviceProvider; protected abstract string LanguageName { get; } protected abstract string CreateReference(string referenceName); protected abstract string CreateImport(string namespaceName); public AbstractResetInteractiveCommand( VisualStudioWorkspace workspace, VsInteractiveWindowProvider interactiveWindowProvider, IServiceProvider serviceProvider) { _workspace = workspace; _interactiveWindowProvider = interactiveWindowProvider; _serviceProvider = serviceProvider; _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } private object GetService(Type type) => _serviceProvider.GetService(type); public void ExecuteResetInteractive() { var resetInteractive = new VsResetInteractive( _workspace, (DTE)GetService(typeof(SDTE)), _componentModel, (IVsMonitorSelection)GetService(typeof(SVsShellMonitorSelection)), (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager)), CreateReference, CreateImport); var vsInteractiveWindow = _interactiveWindowProvider.Open(instanceId: 0, focus: true); void focusWindow(object s, EventArgs e) { // We have to set focus to the Interactive Window *after* the wait indicator is dismissed. vsInteractiveWindow.Show(focus: true); resetInteractive.ExecutionCompleted -= focusWindow; } resetInteractive.ExecuteAsync(vsInteractiveWindow.InteractiveWindow, LanguageName + " Interactive"); resetInteractive.ExecutionCompleted += focusWindow; } } }
// Licensed to the .NET Foundation under one or more 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 EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.LanguageServices.Interactive; using Microsoft.VisualStudio.Shell.Interop; using System; namespace Roslyn.VisualStudio.Services.Interactive { internal abstract class AbstractResetInteractiveCommand : IResetInteractiveCommand { private readonly VisualStudioWorkspace _workspace; private readonly IComponentModel _componentModel; private readonly VsInteractiveWindowProvider _interactiveWindowProvider; private readonly IServiceProvider _serviceProvider; protected abstract string LanguageName { get; } protected abstract string CreateReference(string referenceName); protected abstract string CreateImport(string namespaceName); public AbstractResetInteractiveCommand( VisualStudioWorkspace workspace, VsInteractiveWindowProvider interactiveWindowProvider, IServiceProvider serviceProvider) { _workspace = workspace; _interactiveWindowProvider = interactiveWindowProvider; _serviceProvider = serviceProvider; _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } private object GetService(Type type) => _serviceProvider.GetService(type); public void ExecuteResetInteractive() { var resetInteractive = new VsResetInteractive( _workspace, (DTE)GetService(typeof(SDTE)), _componentModel, (IVsMonitorSelection)GetService(typeof(SVsShellMonitorSelection)), (IVsSolutionBuildManager)GetService(typeof(SVsSolutionBuildManager)), CreateReference, CreateImport); var vsInteractiveWindow = _interactiveWindowProvider.Open(instanceId: 0, focus: true); void focusWindow(object s, EventArgs e) { // We have to set focus to the Interactive Window *after* the wait indicator is dismissed. vsInteractiveWindow.Show(focus: true); resetInteractive.ExecutionCompleted -= focusWindow; } resetInteractive.ExecuteAsync(vsInteractiveWindow.InteractiveWindow, LanguageName + " Interactive"); resetInteractive.ExecutionCompleted += focusWindow; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/InternalUtilities/KeyValuePairUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Roslyn.Utilities { internal static class KeyValuePairUtil { public static KeyValuePair<K, V> Create<K, V>(K key, V value) { return new KeyValuePair<K, V>(key, value); } public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> keyValuePair, out TKey key, out TValue value) { key = keyValuePair.Key; value = keyValuePair.Value; } public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this (TKey, TValue) tuple) => Create(tuple.Item1, tuple.Item2); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace Roslyn.Utilities { internal static class KeyValuePairUtil { public static KeyValuePair<K, V> Create<K, V>(K key, V value) { return new KeyValuePair<K, V>(key, value); } public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> keyValuePair, out TKey key, out TValue value) { key = keyValuePair.Key; value = keyValuePair.Value; } public static KeyValuePair<TKey, TValue> ToKeyValuePair<TKey, TValue>(this (TKey, TValue) tuple) => Create(tuple.Item1, tuple.Item2); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/CommandLine/VisualBasicCompiler.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.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicCompiler Inherits CommonCompiler Friend Const ResponseFileName As String = "vbc.rsp" Friend Const VbcCommandLinePrefix = "vbc : " 'Common prefix String For VB diagnostic output with no location. Private Shared ReadOnly s_responseFileName As String Private ReadOnly _responseFile As String Private ReadOnly _diagnosticFormatter As CommandLineDiagnosticFormatter Private ReadOnly _tempDirectory As String Private _additionalTextFiles As ImmutableArray(Of AdditionalTextFile) Protected Sub New(parser As VisualBasicCommandLineParser, responseFile As String, args As String(), buildPaths As BuildPaths, additionalReferenceDirectories As String, analyzerLoader As IAnalyzerAssemblyLoader) MyBase.New(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader) _diagnosticFormatter = New CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, AddressOf GetAdditionalTextFiles) _additionalTextFiles = Nothing _tempDirectory = buildPaths.TempDirectory Debug.Assert(Arguments.OutputFileName IsNot Nothing OrElse Arguments.Errors.Length > 0 OrElse parser.IsScriptCommandLineParser) End Sub Private Function GetAdditionalTextFiles() As ImmutableArray(Of AdditionalTextFile) Debug.Assert(Not _additionalTextFiles.IsDefault, "GetAdditionalTextFiles called before ResolveAdditionalFilesFromArguments") Return _additionalTextFiles End Function Protected Overrides Function ResolveAdditionalFilesFromArguments(diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, touchedFilesLogger As TouchedFileLogger) As ImmutableArray(Of AdditionalTextFile) _additionalTextFiles = MyBase.ResolveAdditionalFilesFromArguments(diagnostics, messageProvider, touchedFilesLogger) Return _additionalTextFiles End Function Friend Overloads ReadOnly Property Arguments As VisualBasicCommandLineArguments Get Return DirectCast(MyBase.Arguments, VisualBasicCommandLineArguments) End Get End Property Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return _diagnosticFormatter End Get End Property Private Function ParseFile(consoleOutput As TextWriter, parseOptions As VisualBasicParseOptions, scriptParseOptions As VisualBasicParseOptions, ByRef hadErrors As Boolean, file As CommandLineSourceFile, errorLogger As ErrorLogger) As SyntaxTree Dim fileReadDiagnostics As New List(Of DiagnosticInfo)() Dim content = TryReadFileContent(file, fileReadDiagnostics) If content Is Nothing Then ReportDiagnostics(fileReadDiagnostics, consoleOutput, errorLogger, compilation:=Nothing) fileReadDiagnostics.Clear() hadErrors = True Return Nothing End If Dim tree = VisualBasicSyntaxTree.ParseText( content, If(file.IsScript, scriptParseOptions, parseOptions), file.Path) ' prepopulate line tables. ' we will need line tables anyways and it is better to Not wait until we are in emit ' where things run sequentially. Dim isHiddenDummy As Boolean tree.GetMappedLineSpanAndVisibility(Nothing, isHiddenDummy) Return tree End Function Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, analyzerConfigOptions As ImmutableArray(Of AnalyzerConfigOptionsResult), globalAnalyzerConfigOptions As AnalyzerConfigOptionsResult) As Compilation Dim parseOptions = Arguments.ParseOptions ' We compute script parse options once so we don't have to do it repeatedly in ' case there are many script files. Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script) Dim hadErrors As Boolean = False Dim sourceFiles As ImmutableArray(Of CommandLineSourceFile) = Arguments.SourceFiles Dim trees(sourceFiles.Length - 1) As SyntaxTree If Arguments.CompilationOptions.ConcurrentBuild Then RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture(Of Integer)( Sub(i As Integer) ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) End Sub), CancellationToken.None) Else For i = 0 To sourceFiles.Length - 1 ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) Next End If If hadErrors Then Return Nothing End If If Arguments.TouchedFilesPath IsNot Nothing Then For Each file In sourceFiles touchedFilesLogger.AddRead(file.Path) Next End If Dim diagnostics = New List(Of DiagnosticInfo)() Dim assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default Dim referenceDirectiveResolver As MetadataReferenceResolver = Nothing Dim resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, referenceDirectiveResolver) If ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation:=Nothing) Then Return Nothing End If If Arguments.OutputLevel = OutputLevel.Verbose Then PrintReferences(resolvedReferences, consoleOutput) End If Dim xmlFileResolver = New LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger) ' TODO: support for #load search paths Dim sourceFileResolver = New LoggingSourceFileResolver(ImmutableArray(Of String).Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger) Dim loggingFileSystem = New LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory) Dim syntaxTreeOptions = New CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalAnalyzerConfigOptions) Return VisualBasicCompilation.Create( Arguments.CompilationName, trees, resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithXmlReferenceResolver(xmlFileResolver). WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)). WithSourceReferenceResolver(sourceFileResolver). WithSyntaxTreeOptionsProvider(syntaxTreeOptions)) End Function Protected Overrides Function GetOutputFileName(compilation As Compilation, cancellationToken As CancellationToken) As String ' The only case this is Nothing is when there are errors during parsing in which case this should never get called Debug.Assert(Arguments.OutputFileName IsNot Nothing) Return Arguments.OutputFileName End Function Private Sub PrintReferences(resolvedReferences As List(Of MetadataReference), consoleOutput As TextWriter) For Each reference In resolvedReferences If reference.Properties.Kind = MetadataImageKind.Module Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDMODULE, Culture), reference.Display) ElseIf reference.Properties.EmbedInteropTypes Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDLINKREFERENCE, Culture), reference.Display) Else consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDREFERENCE, Culture), reference.Display) End If Next consoleOutput.WriteLine() End Sub Friend Overrides Function SuppressDefaultResponseFile(args As IEnumerable(Of String)) As Boolean For Each arg In args Select Case arg.ToLowerInvariant Case "/noconfig", "-noconfig", "/nostdlib", "-nostdlib" Return True End Select Next Return False End Function ''' <summary> ''' Print compiler logo ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintLogo(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine2, Culture)) consoleOutput.WriteLine() End Sub Friend Overrides Function GetToolName() As String Return ErrorFactory.IdToString(ERRID.IDS_ToolName, Culture) End Function Friend Overrides ReadOnly Property Type As Type Get ' We do not use Me.GetType() so that we don't break mock subtypes Return GetType(VisualBasicCompiler) End Get End Property ''' <summary> ''' Print Commandline help message (up to 80 English characters per line) ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintHelp(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_VBCHelp, Culture)) End Sub Public Overrides Sub PrintLangVersions(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LangVersions, Culture)) Dim defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion() Dim latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion() For Each v As LanguageVersion In System.Enum.GetValues(GetType(LanguageVersion)) If v = defaultVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (default)") ElseIf v = latestVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)") Else consoleOutput.WriteLine(v.ToDisplayString()) End If Next consoleOutput.WriteLine() End Sub Protected Overrides Function TryGetCompilerDiagnosticCode(diagnosticId As String, ByRef code As UInteger) As Boolean Return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "BC", code) End Function Protected Overrides Sub ResolveAnalyzersFromArguments( diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, skipAnalyzers As Boolean, ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer), ByRef generators As ImmutableArray(Of ISourceGenerator)) Arguments.ResolveAnalyzersFromArguments(LanguageNames.VisualBasic, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, analyzers, generators) End Sub Protected Overrides Sub ResolveEmbeddedFilesFromExternalSourceDirectives( tree As SyntaxTree, resolver As SourceReferenceResolver, embeddedFiles As OrderedSet(Of String), diagnostics As DiagnosticBag) For Each directive As ExternalSourceDirectiveTriviaSyntax In tree.GetRoot().GetDirectives( Function(d) d.Kind() = SyntaxKind.ExternalSourceDirectiveTrivia) If directive.ExternalSource.IsMissing Then Continue For End If Dim path = CStr(directive.ExternalSource.Value) If path Is Nothing Then Continue For End If Dim resolvedPath = resolver.ResolveReference(path, tree.FilePath) If resolvedPath Is Nothing Then diagnostics.Add( MessageProvider.CreateDiagnostic( MessageProvider.ERR_FileNotFound, directive.ExternalSource.GetLocation(), path)) Continue For End If embeddedFiles.Add(resolvedPath) Next End Sub Private Protected Overrides Function RunGenerators(input As Compilation, parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), diagnostics As DiagnosticBag) As Compilation Dim driver = VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) Dim compilationOut As Compilation = Nothing, generatorDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(input, compilationOut, generatorDiagnostics) diagnostics.AddRange(generatorDiagnostics) Return compilationOut 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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicCompiler Inherits CommonCompiler Friend Const ResponseFileName As String = "vbc.rsp" Friend Const VbcCommandLinePrefix = "vbc : " 'Common prefix String For VB diagnostic output with no location. Private Shared ReadOnly s_responseFileName As String Private ReadOnly _responseFile As String Private ReadOnly _diagnosticFormatter As CommandLineDiagnosticFormatter Private ReadOnly _tempDirectory As String Private _additionalTextFiles As ImmutableArray(Of AdditionalTextFile) Protected Sub New(parser As VisualBasicCommandLineParser, responseFile As String, args As String(), buildPaths As BuildPaths, additionalReferenceDirectories As String, analyzerLoader As IAnalyzerAssemblyLoader) MyBase.New(parser, responseFile, args, buildPaths, additionalReferenceDirectories, analyzerLoader) _diagnosticFormatter = New CommandLineDiagnosticFormatter(buildPaths.WorkingDirectory, AddressOf GetAdditionalTextFiles) _additionalTextFiles = Nothing _tempDirectory = buildPaths.TempDirectory Debug.Assert(Arguments.OutputFileName IsNot Nothing OrElse Arguments.Errors.Length > 0 OrElse parser.IsScriptCommandLineParser) End Sub Private Function GetAdditionalTextFiles() As ImmutableArray(Of AdditionalTextFile) Debug.Assert(Not _additionalTextFiles.IsDefault, "GetAdditionalTextFiles called before ResolveAdditionalFilesFromArguments") Return _additionalTextFiles End Function Protected Overrides Function ResolveAdditionalFilesFromArguments(diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, touchedFilesLogger As TouchedFileLogger) As ImmutableArray(Of AdditionalTextFile) _additionalTextFiles = MyBase.ResolveAdditionalFilesFromArguments(diagnostics, messageProvider, touchedFilesLogger) Return _additionalTextFiles End Function Friend Overloads ReadOnly Property Arguments As VisualBasicCommandLineArguments Get Return DirectCast(MyBase.Arguments, VisualBasicCommandLineArguments) End Get End Property Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return _diagnosticFormatter End Get End Property Private Function ParseFile(consoleOutput As TextWriter, parseOptions As VisualBasicParseOptions, scriptParseOptions As VisualBasicParseOptions, ByRef hadErrors As Boolean, file As CommandLineSourceFile, errorLogger As ErrorLogger) As SyntaxTree Dim fileReadDiagnostics As New List(Of DiagnosticInfo)() Dim content = TryReadFileContent(file, fileReadDiagnostics) If content Is Nothing Then ReportDiagnostics(fileReadDiagnostics, consoleOutput, errorLogger, compilation:=Nothing) fileReadDiagnostics.Clear() hadErrors = True Return Nothing End If Dim tree = VisualBasicSyntaxTree.ParseText( content, If(file.IsScript, scriptParseOptions, parseOptions), file.Path) ' prepopulate line tables. ' we will need line tables anyways and it is better to Not wait until we are in emit ' where things run sequentially. Dim isHiddenDummy As Boolean tree.GetMappedLineSpanAndVisibility(Nothing, isHiddenDummy) Return tree End Function Public Overrides Function CreateCompilation(consoleOutput As TextWriter, touchedFilesLogger As TouchedFileLogger, errorLogger As ErrorLogger, analyzerConfigOptions As ImmutableArray(Of AnalyzerConfigOptionsResult), globalAnalyzerConfigOptions As AnalyzerConfigOptionsResult) As Compilation Dim parseOptions = Arguments.ParseOptions ' We compute script parse options once so we don't have to do it repeatedly in ' case there are many script files. Dim scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script) Dim hadErrors As Boolean = False Dim sourceFiles As ImmutableArray(Of CommandLineSourceFile) = Arguments.SourceFiles Dim trees(sourceFiles.Length - 1) As SyntaxTree If Arguments.CompilationOptions.ConcurrentBuild Then RoslynParallel.For( 0, sourceFiles.Length, UICultureUtilities.WithCurrentUICulture(Of Integer)( Sub(i As Integer) ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) End Sub), CancellationToken.None) Else For i = 0 To sourceFiles.Length - 1 ' NOTE: order of trees is important!! trees(i) = ParseFile( consoleOutput, parseOptions, scriptParseOptions, hadErrors, sourceFiles(i), errorLogger) Next End If If hadErrors Then Return Nothing End If If Arguments.TouchedFilesPath IsNot Nothing Then For Each file In sourceFiles touchedFilesLogger.AddRead(file.Path) Next End If Dim diagnostics = New List(Of DiagnosticInfo)() Dim assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default Dim referenceDirectiveResolver As MetadataReferenceResolver = Nothing Dim resolvedReferences = ResolveMetadataReferences(diagnostics, touchedFilesLogger, referenceDirectiveResolver) If ReportDiagnostics(diagnostics, consoleOutput, errorLogger, compilation:=Nothing) Then Return Nothing End If If Arguments.OutputLevel = OutputLevel.Verbose Then PrintReferences(resolvedReferences, consoleOutput) End If Dim xmlFileResolver = New LoggingXmlFileResolver(Arguments.BaseDirectory, touchedFilesLogger) ' TODO: support for #load search paths Dim sourceFileResolver = New LoggingSourceFileResolver(ImmutableArray(Of String).Empty, Arguments.BaseDirectory, Arguments.PathMap, touchedFilesLogger) Dim loggingFileSystem = New LoggingStrongNameFileSystem(touchedFilesLogger, _tempDirectory) Dim syntaxTreeOptions = New CompilerSyntaxTreeOptionsProvider(trees, analyzerConfigOptions, globalAnalyzerConfigOptions) Return VisualBasicCompilation.Create( Arguments.CompilationName, trees, resolvedReferences, Arguments.CompilationOptions. WithMetadataReferenceResolver(referenceDirectiveResolver). WithAssemblyIdentityComparer(assemblyIdentityComparer). WithXmlReferenceResolver(xmlFileResolver). WithStrongNameProvider(Arguments.GetStrongNameProvider(loggingFileSystem)). WithSourceReferenceResolver(sourceFileResolver). WithSyntaxTreeOptionsProvider(syntaxTreeOptions)) End Function Protected Overrides Function GetOutputFileName(compilation As Compilation, cancellationToken As CancellationToken) As String ' The only case this is Nothing is when there are errors during parsing in which case this should never get called Debug.Assert(Arguments.OutputFileName IsNot Nothing) Return Arguments.OutputFileName End Function Private Sub PrintReferences(resolvedReferences As List(Of MetadataReference), consoleOutput As TextWriter) For Each reference In resolvedReferences If reference.Properties.Kind = MetadataImageKind.Module Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDMODULE, Culture), reference.Display) ElseIf reference.Properties.EmbedInteropTypes Then consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDLINKREFERENCE, Culture), reference.Display) Else consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_MSG_ADDREFERENCE, Culture), reference.Display) End If Next consoleOutput.WriteLine() End Sub Friend Overrides Function SuppressDefaultResponseFile(args As IEnumerable(Of String)) As Boolean For Each arg In args Select Case arg.ToLowerInvariant Case "/noconfig", "-noconfig", "/nostdlib", "-nostdlib" Return True End Select Next Return False End Function ''' <summary> ''' Print compiler logo ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintLogo(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine1, Culture), GetToolName(), GetCompilerVersion()) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LogoLine2, Culture)) consoleOutput.WriteLine() End Sub Friend Overrides Function GetToolName() As String Return ErrorFactory.IdToString(ERRID.IDS_ToolName, Culture) End Function Friend Overrides ReadOnly Property Type As Type Get ' We do not use Me.GetType() so that we don't break mock subtypes Return GetType(VisualBasicCompiler) End Get End Property ''' <summary> ''' Print Commandline help message (up to 80 English characters per line) ''' </summary> ''' <param name="consoleOutput"></param> Public Overrides Sub PrintHelp(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_VBCHelp, Culture)) End Sub Public Overrides Sub PrintLangVersions(consoleOutput As TextWriter) consoleOutput.WriteLine(ErrorFactory.IdToString(ERRID.IDS_LangVersions, Culture)) Dim defaultVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion() Dim latestVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion() For Each v As LanguageVersion In System.Enum.GetValues(GetType(LanguageVersion)) If v = defaultVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (default)") ElseIf v = latestVersion Then consoleOutput.WriteLine($"{v.ToDisplayString()} (latest)") Else consoleOutput.WriteLine(v.ToDisplayString()) End If Next consoleOutput.WriteLine() End Sub Protected Overrides Function TryGetCompilerDiagnosticCode(diagnosticId As String, ByRef code As UInteger) As Boolean Return CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "BC", code) End Function Protected Overrides Sub ResolveAnalyzersFromArguments( diagnostics As List(Of DiagnosticInfo), messageProvider As CommonMessageProvider, skipAnalyzers As Boolean, ByRef analyzers As ImmutableArray(Of DiagnosticAnalyzer), ByRef generators As ImmutableArray(Of ISourceGenerator)) Arguments.ResolveAnalyzersFromArguments(LanguageNames.VisualBasic, diagnostics, messageProvider, AssemblyLoader, skipAnalyzers, analyzers, generators) End Sub Protected Overrides Sub ResolveEmbeddedFilesFromExternalSourceDirectives( tree As SyntaxTree, resolver As SourceReferenceResolver, embeddedFiles As OrderedSet(Of String), diagnostics As DiagnosticBag) For Each directive As ExternalSourceDirectiveTriviaSyntax In tree.GetRoot().GetDirectives( Function(d) d.Kind() = SyntaxKind.ExternalSourceDirectiveTrivia) If directive.ExternalSource.IsMissing Then Continue For End If Dim path = CStr(directive.ExternalSource.Value) If path Is Nothing Then Continue For End If Dim resolvedPath = resolver.ResolveReference(path, tree.FilePath) If resolvedPath Is Nothing Then diagnostics.Add( MessageProvider.CreateDiagnostic( MessageProvider.ERR_FileNotFound, directive.ExternalSource.GetLocation(), path)) Continue For End If embeddedFiles.Add(resolvedPath) Next End Sub Private Protected Overrides Function RunGenerators(input As Compilation, parseOptions As ParseOptions, generators As ImmutableArray(Of ISourceGenerator), analyzerConfigOptionsProvider As AnalyzerConfigOptionsProvider, additionalTexts As ImmutableArray(Of AdditionalText), diagnostics As DiagnosticBag) As Compilation Dim driver = VisualBasicGeneratorDriver.Create(generators, additionalTexts, DirectCast(parseOptions, VisualBasicParseOptions), analyzerConfigOptionsProvider) Dim compilationOut As Compilation = Nothing, generatorDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(input, compilationOut, generatorDiagnostics) diagnostics.AddRange(generatorDiagnostics) Return compilationOut End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicNameReducer.Rewriter.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.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicNameReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitGenericName(node As GenericNameSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitGenericName(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitIdentifierName(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitQualifiedName(node As QualifiedNameSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitQualifiedName(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitMemberAccessExpression(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitNullableType(node As NullableTypeSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitNullableType(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitArrayType(node As ArrayTypeSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitArrayType(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result 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 Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicNameReducer Private Class Rewriter Inherits AbstractReductionRewriter Public Sub New(pool As ObjectPool(Of IReductionRewriter)) MyBase.New(pool) End Sub Public Overrides Function VisitGenericName(node As GenericNameSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitGenericName(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitIdentifierName(node As IdentifierNameSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitIdentifierName(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitQualifiedName(node As QualifiedNameSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitQualifiedName(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitMemberAccessExpression(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitNullableType(node As NullableTypeSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitNullableType(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function Public Overrides Function VisitArrayType(node As ArrayTypeSyntax) As SyntaxNode Dim oldAlwaysSimplify = Me._alwaysSimplify If Not Me._alwaysSimplify Then Me._alwaysSimplify = node.HasAnnotation(Simplifier.Annotation) End If Dim result = SimplifyExpression( node, newNode:=MyBase.VisitArrayType(node), simplifier:=s_simplifyName) Me._alwaysSimplify = oldAlwaysSimplify Return result End Function End Class End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Shared/Extensions/ITextViewExtensions.AutoClosingViewProperty.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextViewExtensions { private class AutoClosingViewProperty<TProperty, TTextView> where TTextView : ITextView { private readonly TTextView _textView; private readonly Dictionary<object, TProperty> _map = new(); public static bool GetOrCreateValue( TTextView textView, object key, Func<TTextView, TProperty> valueCreator, out TProperty value) { Contract.ThrowIfTrue(textView.IsClosed); var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView)); if (!properties.TryGetValue(key, out var priorValue)) { // Need to create it. value = valueCreator(textView); properties.Add(key, value); return true; } // Already there. value = priorValue; return false; } public static bool TryGetValue( TTextView textView, object key, [MaybeNullWhen(false)] out TProperty value) { Contract.ThrowIfTrue(textView.IsClosed); var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView)); return properties.TryGetValue(key, out value); } public static void AddValue( TTextView textView, object key, TProperty value) { Contract.ThrowIfTrue(textView.IsClosed); var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView)); properties.Add(key, value); } public static void RemoveValue(TTextView textView, object key) { if (textView.Properties.TryGetProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>), out AutoClosingViewProperty<TProperty, TTextView> properties)) { properties.Remove(key); } } private AutoClosingViewProperty(TTextView textView) { _textView = textView; _textView.Closed += OnTextViewClosed; } private void OnTextViewClosed(object? sender, EventArgs e) { _textView.Closed -= OnTextViewClosed; _textView.Properties.RemoveProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>)); } public bool TryGetValue(object key, [MaybeNullWhen(false)] out TProperty value) => _map.TryGetValue(key, out value); public void Add(object key, TProperty value) => _map[key] = value; public void Remove(object key) => _map.Remove(key); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio.Text.Editor; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static partial class ITextViewExtensions { private class AutoClosingViewProperty<TProperty, TTextView> where TTextView : ITextView { private readonly TTextView _textView; private readonly Dictionary<object, TProperty> _map = new(); public static bool GetOrCreateValue( TTextView textView, object key, Func<TTextView, TProperty> valueCreator, out TProperty value) { Contract.ThrowIfTrue(textView.IsClosed); var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView)); if (!properties.TryGetValue(key, out var priorValue)) { // Need to create it. value = valueCreator(textView); properties.Add(key, value); return true; } // Already there. value = priorValue; return false; } public static bool TryGetValue( TTextView textView, object key, [MaybeNullWhen(false)] out TProperty value) { Contract.ThrowIfTrue(textView.IsClosed); var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView)); return properties.TryGetValue(key, out value); } public static void AddValue( TTextView textView, object key, TProperty value) { Contract.ThrowIfTrue(textView.IsClosed); var properties = textView.Properties.GetOrCreateSingletonProperty(() => new AutoClosingViewProperty<TProperty, TTextView>(textView)); properties.Add(key, value); } public static void RemoveValue(TTextView textView, object key) { if (textView.Properties.TryGetProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>), out AutoClosingViewProperty<TProperty, TTextView> properties)) { properties.Remove(key); } } private AutoClosingViewProperty(TTextView textView) { _textView = textView; _textView.Closed += OnTextViewClosed; } private void OnTextViewClosed(object? sender, EventArgs e) { _textView.Closed -= OnTextViewClosed; _textView.Properties.RemoveProperty(typeof(AutoClosingViewProperty<TProperty, TTextView>)); } public bool TryGetValue(object key, [MaybeNullWhen(false)] out TProperty value) => _map.TryGetValue(key, out value); public void Add(object key, TProperty value) => _map[key] = value; public void Remove(object key) => _map.Remove(key); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Compilation/TypeInfo.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic Friend Structure VisualBasicTypeInfo Implements IEquatable(Of VisualBasicTypeInfo) ' should be best guess if there is one, or error type if none. Private ReadOnly _type As TypeSymbol Private ReadOnly _convertedType As TypeSymbol Private ReadOnly _implicitConversion As Conversion Friend Shared None As New VisualBasicTypeInfo(Nothing, Nothing, New Conversion(Conversions.Identity)) ''' <summary> ''' The type of the expression represented by the syntax node. For expressions that do not ''' have a type, null is returned. If the type could not be determined due to an error, than ''' an object derived from ErrorTypeSymbol is returned. ''' </summary> Public ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property ''' <summary> ''' The type of the expression after it has undergone an implicit conversion. If the type ''' did not undergo an implicit conversion, returns the same as Type. ''' </summary> Public ReadOnly Property ConvertedType As TypeSymbol Get Return _convertedType End Get End Property ''' <summary> ''' If the expression underwent an implicit conversion, return information about that ''' conversion. Otherwise, returns an identity conversion. ''' </summary> Public ReadOnly Property ImplicitConversion As Conversion Get Return _implicitConversion End Get End Property Public Shared Widening Operator CType(info As VisualBasicTypeInfo) As TypeInfo Return New TypeInfo(info.Type, info.ConvertedType, nullability:=Nothing, convertedNullability:=Nothing) End Operator Friend Sub New(type As TypeSymbol, convertedType As TypeSymbol, implicitConversion As Conversion) Me._type = GetPossibleGuessForErrorType(type) Me._convertedType = GetPossibleGuessForErrorType(convertedType) Me._implicitConversion = implicitConversion End Sub Public Overloads Function Equals(other As VisualBasicTypeInfo) As Boolean Implements IEquatable(Of VisualBasicTypeInfo).Equals Return _implicitConversion.Equals(other._implicitConversion) AndAlso TypeSymbol.Equals(_type, other._type, TypeCompareKind.ConsiderEverything) AndAlso TypeSymbol.Equals(_convertedType, other._convertedType, TypeCompareKind.ConsiderEverything) End Function Public Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is VisualBasicTypeInfo AndAlso Equals(DirectCast(obj, VisualBasicTypeInfo)) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(_convertedType, Hash.Combine(_type, _implicitConversion.GetHashCode())) End Function ''' <summary> ''' Guess the non-error type that the given type was intended to represent, or return ''' the type itself. If a single, non-ambiguous type is a guess-type inside the type symbol, ''' return that; otherwise return the type itself (even if it is an error type). ''' </summary> Private Shared Function GetPossibleGuessForErrorType(type As TypeSymbol) As TypeSymbol Dim errorSymbol As ErrorTypeSymbol = TryCast(type, ErrorTypeSymbol) If errorSymbol Is Nothing Then Return type End If Dim nonErrorGuess = errorSymbol.NonErrorGuessType If nonErrorGuess Is Nothing Then Return type Else Return nonErrorGuess End If End Function End Structure End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic Friend Structure VisualBasicTypeInfo Implements IEquatable(Of VisualBasicTypeInfo) ' should be best guess if there is one, or error type if none. Private ReadOnly _type As TypeSymbol Private ReadOnly _convertedType As TypeSymbol Private ReadOnly _implicitConversion As Conversion Friend Shared None As New VisualBasicTypeInfo(Nothing, Nothing, New Conversion(Conversions.Identity)) ''' <summary> ''' The type of the expression represented by the syntax node. For expressions that do not ''' have a type, null is returned. If the type could not be determined due to an error, than ''' an object derived from ErrorTypeSymbol is returned. ''' </summary> Public ReadOnly Property Type As TypeSymbol Get Return _type End Get End Property ''' <summary> ''' The type of the expression after it has undergone an implicit conversion. If the type ''' did not undergo an implicit conversion, returns the same as Type. ''' </summary> Public ReadOnly Property ConvertedType As TypeSymbol Get Return _convertedType End Get End Property ''' <summary> ''' If the expression underwent an implicit conversion, return information about that ''' conversion. Otherwise, returns an identity conversion. ''' </summary> Public ReadOnly Property ImplicitConversion As Conversion Get Return _implicitConversion End Get End Property Public Shared Widening Operator CType(info As VisualBasicTypeInfo) As TypeInfo Return New TypeInfo(info.Type, info.ConvertedType, nullability:=Nothing, convertedNullability:=Nothing) End Operator Friend Sub New(type As TypeSymbol, convertedType As TypeSymbol, implicitConversion As Conversion) Me._type = GetPossibleGuessForErrorType(type) Me._convertedType = GetPossibleGuessForErrorType(convertedType) Me._implicitConversion = implicitConversion End Sub Public Overloads Function Equals(other As VisualBasicTypeInfo) As Boolean Implements IEquatable(Of VisualBasicTypeInfo).Equals Return _implicitConversion.Equals(other._implicitConversion) AndAlso TypeSymbol.Equals(_type, other._type, TypeCompareKind.ConsiderEverything) AndAlso TypeSymbol.Equals(_convertedType, other._convertedType, TypeCompareKind.ConsiderEverything) End Function Public Overrides Function Equals(obj As Object) As Boolean Return TypeOf obj Is VisualBasicTypeInfo AndAlso Equals(DirectCast(obj, VisualBasicTypeInfo)) End Function Public Overrides Function GetHashCode() As Integer Return Hash.Combine(_convertedType, Hash.Combine(_type, _implicitConversion.GetHashCode())) End Function ''' <summary> ''' Guess the non-error type that the given type was intended to represent, or return ''' the type itself. If a single, non-ambiguous type is a guess-type inside the type symbol, ''' return that; otherwise return the type itself (even if it is an error type). ''' </summary> Private Shared Function GetPossibleGuessForErrorType(type As TypeSymbol) As TypeSymbol Dim errorSymbol As ErrorTypeSymbol = TryCast(type, ErrorTypeSymbol) If errorSymbol Is Nothing Then Return type End If Dim nonErrorGuess = errorSymbol.NonErrorGuessType If nonErrorGuess Is Nothing Then Return type Else Return nonErrorGuess End If End Function End Structure End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/CSharpSyntaxNode.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.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class CSharpSyntaxNode : GreenNode { internal CSharpSyntaxNode(SyntaxKind kind) : base((ushort)kind) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, int fullWidth) : base((ushort)kind, fullWidth) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics) : base((ushort)kind, diagnostics) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, int fullWidth) : base((ushort)kind, diagnostics, fullWidth) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) : base((ushort)kind, diagnostics, annotations) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations, int fullWidth) : base((ushort)kind, diagnostics, annotations, fullWidth) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(ObjectReader reader) : base(reader) { } public override string Language { get { return LanguageNames.CSharp; } } public SyntaxKind Kind { get { return (SyntaxKind)this.RawKind; } } public override string KindText => this.Kind.ToString(); public override int RawContextualKind { get { return this.RawKind; } } public override bool IsStructuredTrivia { get { return this is StructuredTriviaSyntax; } } public override bool IsDirective { get { return this is DirectiveTriviaSyntax; } } public override bool IsSkippedTokensTrivia => this.Kind == SyntaxKind.SkippedTokensTrivia; public override bool IsDocumentationCommentTrivia => SyntaxFacts.IsDocumentationCommentTrivia(this.Kind); public override int GetSlotOffset(int index) { // This implementation should not support arbitrary // length lists since the implementation is O(n). System.Diagnostics.Debug.Assert(index < 11); // Max. slots 11 (TypeDeclarationSyntax) int offset = 0; for (int i = 0; i < index; i++) { var child = this.GetSlot(i); if (child != null) { offset += child.FullWidth; } } return offset; } public SyntaxToken GetFirstToken() { return (SyntaxToken)this.GetFirstTerminal(); } public SyntaxToken GetLastToken() { return (SyntaxToken)this.GetLastTerminal(); } public SyntaxToken GetLastNonmissingToken() { return (SyntaxToken)this.GetLastNonmissingTerminal(); } public virtual GreenNode GetLeadingTrivia() { return null; } public override GreenNode GetLeadingTriviaCore() { return this.GetLeadingTrivia(); } public virtual GreenNode GetTrailingTrivia() { return null; } public override GreenNode GetTrailingTriviaCore() { return this.GetTrailingTrivia(); } public abstract TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor); public abstract void Accept(CSharpSyntaxVisitor visitor); internal virtual DirectiveStack ApplyDirectives(DirectiveStack stack) { return ApplyDirectives(this, stack); } internal static DirectiveStack ApplyDirectives(GreenNode node, DirectiveStack stack) { if (node.ContainsDirectives) { for (int i = 0, n = node.SlotCount; i < n; i++) { var child = node.GetSlot(i); if (child != null) { stack = ApplyDirectivesToListOrNode(child, stack); } } } return stack; } internal static DirectiveStack ApplyDirectivesToListOrNode(GreenNode listOrNode, DirectiveStack stack) { // If we have a list of trivia, then that node is not actually a CSharpSyntaxNode. // Just defer to our standard ApplyDirectives helper as it will do the appropriate // walking of this list to ApplyDirectives to the children. if (listOrNode.RawKind == GreenNode.ListKind) { return ApplyDirectives(listOrNode, stack); } else { // Otherwise, we must have an actual piece of C# trivia. Just apply the stack // to that node directly. return ((CSharpSyntaxNode)listOrNode).ApplyDirectives(stack); } } internal virtual IList<DirectiveTriviaSyntax> GetDirectives() { if ((this.flags & NodeFlags.ContainsDirectives) != 0) { var list = new List<DirectiveTriviaSyntax>(32); GetDirectives(this, list); return list; } return SpecializedCollections.EmptyList<DirectiveTriviaSyntax>(); } private static void GetDirectives(GreenNode node, List<DirectiveTriviaSyntax> directives) { if (node != null && node.ContainsDirectives) { var d = node as DirectiveTriviaSyntax; if (d != null) { directives.Add(d); } else { var t = node as SyntaxToken; if (t != null) { GetDirectives(t.GetLeadingTrivia(), directives); GetDirectives(t.GetTrailingTrivia(), directives); } else { for (int i = 0, n = node.SlotCount; i < n; i++) { GetDirectives(node.GetSlot(i), directives); } } } } } /// <summary> /// Should only be called during construction. /// </summary> /// <remarks> /// This should probably be an extra constructor parameter, but we don't need more constructor overloads. /// </remarks> protected void SetFactoryContext(SyntaxFactoryContext context) { if (context.IsInAsync) { this.flags |= NodeFlags.FactoryContextIsInAsync; } if (context.IsInQuery) { this.flags |= NodeFlags.FactoryContextIsInQuery; } } internal static NodeFlags SetFactoryContext(NodeFlags flags, SyntaxFactoryContext context) { if (context.IsInAsync) { flags |= NodeFlags.FactoryContextIsInAsync; } if (context.IsInQuery) { flags |= NodeFlags.FactoryContextIsInQuery; } return flags; } public override CodeAnalysis.SyntaxToken CreateSeparator<TNode>(SyntaxNode element) { return CSharp.SyntaxFactory.Token(SyntaxKind.CommaToken); } public override bool IsTriviaWithEndOfLine() { return this.Kind == SyntaxKind.EndOfLineTrivia || this.Kind == SyntaxKind.SingleLineCommentTrivia; } // Use conditional weak table so we always return same identity for structured trivia private static readonly ConditionalWeakTable<SyntaxNode, Dictionary<CodeAnalysis.SyntaxTrivia, SyntaxNode>> s_structuresTable = new ConditionalWeakTable<SyntaxNode, Dictionary<CodeAnalysis.SyntaxTrivia, SyntaxNode>>(); /// <summary> /// Gets the syntax node represented the structure of this trivia, if any. The HasStructure property can be used to /// determine if this trivia has structure. /// </summary> /// <returns> /// A CSharpSyntaxNode derived from StructuredTriviaSyntax, with the structured view of this trivia node. /// If this trivia node does not have structure, returns null. /// </returns> /// <remarks> /// Some types of trivia have structure that can be accessed as additional syntax nodes. /// These forms of trivia include: /// directives, where the structure describes the structure of the directive. /// documentation comments, where the structure describes the XML structure of the comment. /// skipped tokens, where the structure describes the tokens that were skipped by the parser. /// </remarks> public override SyntaxNode GetStructure(Microsoft.CodeAnalysis.SyntaxTrivia trivia) { if (trivia.HasStructure) { var parent = trivia.Token.Parent; if (parent != null) { SyntaxNode structure; var structsInParent = s_structuresTable.GetOrCreateValue(parent); lock (structsInParent) { if (!structsInParent.TryGetValue(trivia, out structure)) { structure = CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); structsInParent.Add(trivia, structure); } } return structure; } else { return CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); } } 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.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class CSharpSyntaxNode : GreenNode { internal CSharpSyntaxNode(SyntaxKind kind) : base((ushort)kind) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, int fullWidth) : base((ushort)kind, fullWidth) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics) : base((ushort)kind, diagnostics) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, int fullWidth) : base((ushort)kind, diagnostics, fullWidth) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations) : base((ushort)kind, diagnostics, annotations) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(SyntaxKind kind, DiagnosticInfo[] diagnostics, SyntaxAnnotation[] annotations, int fullWidth) : base((ushort)kind, diagnostics, annotations, fullWidth) { GreenStats.NoteGreen(this); } internal CSharpSyntaxNode(ObjectReader reader) : base(reader) { } public override string Language { get { return LanguageNames.CSharp; } } public SyntaxKind Kind { get { return (SyntaxKind)this.RawKind; } } public override string KindText => this.Kind.ToString(); public override int RawContextualKind { get { return this.RawKind; } } public override bool IsStructuredTrivia { get { return this is StructuredTriviaSyntax; } } public override bool IsDirective { get { return this is DirectiveTriviaSyntax; } } public override bool IsSkippedTokensTrivia => this.Kind == SyntaxKind.SkippedTokensTrivia; public override bool IsDocumentationCommentTrivia => SyntaxFacts.IsDocumentationCommentTrivia(this.Kind); public override int GetSlotOffset(int index) { // This implementation should not support arbitrary // length lists since the implementation is O(n). System.Diagnostics.Debug.Assert(index < 11); // Max. slots 11 (TypeDeclarationSyntax) int offset = 0; for (int i = 0; i < index; i++) { var child = this.GetSlot(i); if (child != null) { offset += child.FullWidth; } } return offset; } public SyntaxToken GetFirstToken() { return (SyntaxToken)this.GetFirstTerminal(); } public SyntaxToken GetLastToken() { return (SyntaxToken)this.GetLastTerminal(); } public SyntaxToken GetLastNonmissingToken() { return (SyntaxToken)this.GetLastNonmissingTerminal(); } public virtual GreenNode GetLeadingTrivia() { return null; } public override GreenNode GetLeadingTriviaCore() { return this.GetLeadingTrivia(); } public virtual GreenNode GetTrailingTrivia() { return null; } public override GreenNode GetTrailingTriviaCore() { return this.GetTrailingTrivia(); } public abstract TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor); public abstract void Accept(CSharpSyntaxVisitor visitor); internal virtual DirectiveStack ApplyDirectives(DirectiveStack stack) { return ApplyDirectives(this, stack); } internal static DirectiveStack ApplyDirectives(GreenNode node, DirectiveStack stack) { if (node.ContainsDirectives) { for (int i = 0, n = node.SlotCount; i < n; i++) { var child = node.GetSlot(i); if (child != null) { stack = ApplyDirectivesToListOrNode(child, stack); } } } return stack; } internal static DirectiveStack ApplyDirectivesToListOrNode(GreenNode listOrNode, DirectiveStack stack) { // If we have a list of trivia, then that node is not actually a CSharpSyntaxNode. // Just defer to our standard ApplyDirectives helper as it will do the appropriate // walking of this list to ApplyDirectives to the children. if (listOrNode.RawKind == GreenNode.ListKind) { return ApplyDirectives(listOrNode, stack); } else { // Otherwise, we must have an actual piece of C# trivia. Just apply the stack // to that node directly. return ((CSharpSyntaxNode)listOrNode).ApplyDirectives(stack); } } internal virtual IList<DirectiveTriviaSyntax> GetDirectives() { if ((this.flags & NodeFlags.ContainsDirectives) != 0) { var list = new List<DirectiveTriviaSyntax>(32); GetDirectives(this, list); return list; } return SpecializedCollections.EmptyList<DirectiveTriviaSyntax>(); } private static void GetDirectives(GreenNode node, List<DirectiveTriviaSyntax> directives) { if (node != null && node.ContainsDirectives) { var d = node as DirectiveTriviaSyntax; if (d != null) { directives.Add(d); } else { var t = node as SyntaxToken; if (t != null) { GetDirectives(t.GetLeadingTrivia(), directives); GetDirectives(t.GetTrailingTrivia(), directives); } else { for (int i = 0, n = node.SlotCount; i < n; i++) { GetDirectives(node.GetSlot(i), directives); } } } } } /// <summary> /// Should only be called during construction. /// </summary> /// <remarks> /// This should probably be an extra constructor parameter, but we don't need more constructor overloads. /// </remarks> protected void SetFactoryContext(SyntaxFactoryContext context) { if (context.IsInAsync) { this.flags |= NodeFlags.FactoryContextIsInAsync; } if (context.IsInQuery) { this.flags |= NodeFlags.FactoryContextIsInQuery; } } internal static NodeFlags SetFactoryContext(NodeFlags flags, SyntaxFactoryContext context) { if (context.IsInAsync) { flags |= NodeFlags.FactoryContextIsInAsync; } if (context.IsInQuery) { flags |= NodeFlags.FactoryContextIsInQuery; } return flags; } public override CodeAnalysis.SyntaxToken CreateSeparator<TNode>(SyntaxNode element) { return CSharp.SyntaxFactory.Token(SyntaxKind.CommaToken); } public override bool IsTriviaWithEndOfLine() { return this.Kind == SyntaxKind.EndOfLineTrivia || this.Kind == SyntaxKind.SingleLineCommentTrivia; } // Use conditional weak table so we always return same identity for structured trivia private static readonly ConditionalWeakTable<SyntaxNode, Dictionary<CodeAnalysis.SyntaxTrivia, SyntaxNode>> s_structuresTable = new ConditionalWeakTable<SyntaxNode, Dictionary<CodeAnalysis.SyntaxTrivia, SyntaxNode>>(); /// <summary> /// Gets the syntax node represented the structure of this trivia, if any. The HasStructure property can be used to /// determine if this trivia has structure. /// </summary> /// <returns> /// A CSharpSyntaxNode derived from StructuredTriviaSyntax, with the structured view of this trivia node. /// If this trivia node does not have structure, returns null. /// </returns> /// <remarks> /// Some types of trivia have structure that can be accessed as additional syntax nodes. /// These forms of trivia include: /// directives, where the structure describes the structure of the directive. /// documentation comments, where the structure describes the XML structure of the comment. /// skipped tokens, where the structure describes the tokens that were skipped by the parser. /// </remarks> public override SyntaxNode GetStructure(Microsoft.CodeAnalysis.SyntaxTrivia trivia) { if (trivia.HasStructure) { var parent = trivia.Token.Parent; if (parent != null) { SyntaxNode structure; var structsInParent = s_structuresTable.GetOrCreateValue(parent); lock (structsInParent) { if (!structsInParent.TryGetValue(trivia, out structure)) { structure = CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); structsInParent.Add(trivia, structure); } } return structure; } else { return CSharp.Syntax.StructuredTriviaSyntax.Create(trivia); } } return null; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Diagnostics/DiagnosticAnalyzerCategory.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.Diagnostics { [Flags] internal enum DiagnosticAnalyzerCategory { /// <summary> /// Invalid value, analyzer must support at least one or more of the subsequent analysis categories. /// </summary> None = 0, /// <summary> /// Analyzer reports syntax diagnostics (i.e. registers a SyntaxTree action). /// Note: an <see cref="DiagnosticAnalyzer"/> that uses this will not work properly if /// it registers a <see cref="AnalysisContext.RegisterSyntaxNodeAction{TLanguageKindEnum}(Action{SyntaxNodeAnalysisContext}, TLanguageKindEnum[])"/> and then ends /// up needing to use the <see cref="SyntaxNodeAnalysisContext.SemanticModel"/>. If a /// <see cref="SemanticModel"/> is needed, use <see cref="SemanticSpanAnalysis"/> or /// <see cref="SemanticDocumentAnalysis"/>. /// </summary> SyntaxTreeWithoutSemanticsAnalysis = 0x0001, /// <summary> /// Analyzer reports semantic diagnostics and also supports incremental span based method body analysis. /// An analyzer can support incremental method body analysis if edits within a method body only affect the diagnostics reported by the analyzer on the edited method body. /// </summary> SemanticSpanAnalysis = 0x0010, /// <summary> /// Analyzer reports semantic diagnostics but doesn't support incremental span based method body analysis. /// It needs to re-analyze the whole document for reporting semantic diagnostics even for method body editing scenarios. /// </summary> SemanticDocumentAnalysis = 0x0100, /// <summary> /// Analyzer reports project diagnostics (i.e. registers a Compilation action and/or Compilation end action diagnostics). /// </summary> ProjectAnalysis = 0x1000 } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics { [Flags] internal enum DiagnosticAnalyzerCategory { /// <summary> /// Invalid value, analyzer must support at least one or more of the subsequent analysis categories. /// </summary> None = 0, /// <summary> /// Analyzer reports syntax diagnostics (i.e. registers a SyntaxTree action). /// Note: an <see cref="DiagnosticAnalyzer"/> that uses this will not work properly if /// it registers a <see cref="AnalysisContext.RegisterSyntaxNodeAction{TLanguageKindEnum}(Action{SyntaxNodeAnalysisContext}, TLanguageKindEnum[])"/> and then ends /// up needing to use the <see cref="SyntaxNodeAnalysisContext.SemanticModel"/>. If a /// <see cref="SemanticModel"/> is needed, use <see cref="SemanticSpanAnalysis"/> or /// <see cref="SemanticDocumentAnalysis"/>. /// </summary> SyntaxTreeWithoutSemanticsAnalysis = 0x0001, /// <summary> /// Analyzer reports semantic diagnostics and also supports incremental span based method body analysis. /// An analyzer can support incremental method body analysis if edits within a method body only affect the diagnostics reported by the analyzer on the edited method body. /// </summary> SemanticSpanAnalysis = 0x0010, /// <summary> /// Analyzer reports semantic diagnostics but doesn't support incremental span based method body analysis. /// It needs to re-analyze the whole document for reporting semantic diagnostics even for method body editing scenarios. /// </summary> SemanticDocumentAnalysis = 0x0100, /// <summary> /// Analyzer reports project diagnostics (i.e. registers a Compilation action and/or Compilation end action diagnostics). /// </summary> ProjectAnalysis = 0x1000 } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ReplaceDocCommentTextWithTag/AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ReplaceDocCommentTextWithTag { internal abstract class AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider : CodeRefactoringProvider { protected abstract bool IsInXMLAttribute(SyntaxToken token); protected abstract bool IsKeyword(string text); protected abstract bool IsXmlTextToken(SyntaxToken token); protected abstract SyntaxNode ParseExpression(string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(span.Start, findInsideTrivia: true); if (!IsXmlTextToken(token)) { return; } if (!token.FullSpan.Contains(span)) { return; } if (IsInXMLAttribute(token)) { return; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var singleWordSpan = ExpandSpan(sourceText, span, fullyQualifiedName: false); var singleWordText = sourceText.ToString(singleWordSpan); if (singleWordText == "") { return; } // First see if they're on an appropriate keyword. if (IsKeyword(singleWordText)) { RegisterRefactoring(context, singleWordSpan, $@"<see langword=""{singleWordText}""/>"); return; } // Not a keyword, see if it semantically means anything in the current context. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = GetEnclosingSymbol(semanticModel, span.Start, cancellationToken); if (symbol == null) { return; } // See if we can expand the term out to a fully qualified name. Do this // first in case the user has something like X.memberName. We don't want // to try to bind "memberName" first as it might bind to something like // a parameter, which is not what the user intends var fullyQualifiedSpan = ExpandSpan(sourceText, span, fullyQualifiedName: true); if (fullyQualifiedSpan != singleWordSpan) { var fullyQualifiedText = sourceText.ToString(fullyQualifiedSpan); if (TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, fullyQualifiedSpan, cancellationToken)) { return; } } // Check if the single word could be binding to a type parameter or parameter // for the current symbol. var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var parameter = symbol.GetParameters().FirstOrDefault(p => syntaxFacts.StringComparer.Equals(p.Name, singleWordText)); if (parameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<paramref name=""{singleWordText}""/>"); return; } var typeParameter = symbol.GetTypeParameters().FirstOrDefault(t => syntaxFacts.StringComparer.Equals(t.Name, singleWordText)); if (typeParameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<typeparamref name=""{singleWordText}""/>"); return; } // Doc comments on a named type can see the members inside of it. So check // inside the named type for a member that matches. if (symbol is INamedTypeSymbol namedType) { var childMember = namedType.GetMembers().FirstOrDefault(m => syntaxFacts.StringComparer.Equals(m.Name, singleWordText)); if (childMember != null) { RegisterRefactoring(context, singleWordSpan, $@"<see cref=""{singleWordText}""/>"); return; } } // Finally, try to speculatively bind the name and see if it binds to anything // in the surrounding context. TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, singleWordSpan, cancellationToken); } private bool TryRegisterSeeCrefTagIfSymbol( CodeRefactoringContext context, SemanticModel semanticModel, SyntaxToken token, TextSpan replacementSpan, CancellationToken cancellationToken) { var sourceText = semanticModel.SyntaxTree.GetText(cancellationToken); var text = sourceText.ToString(replacementSpan); var parsed = ParseExpression(text); var foundSymbol = semanticModel.GetSpeculativeSymbolInfo(token.SpanStart, parsed, SpeculativeBindingOption.BindAsExpression).GetAnySymbol(); if (foundSymbol == null) { return false; } RegisterRefactoring(context, replacementSpan, $@"<see cref=""{text}""/>"); return true; } private static ISymbol GetEnclosingSymbol(SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var token = root.FindToken(position); for (var node = token.Parent; node != null; node = node.Parent) { if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is ISymbol declaration) { return declaration; } } return null; } private static void RegisterRefactoring( CodeRefactoringContext context, TextSpan expandedSpan, string replacement) { context.RegisterRefactoring( new MyCodeAction( string.Format(FeaturesResources.Use_0, replacement), c => ReplaceTextAsync(context.Document, expandedSpan, replacement, c)), expandedSpan); } private static async Task<Document> ReplaceTextAsync( Document document, TextSpan span, string replacement, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.Replace(span, replacement); return document.WithText(newText); } private static TextSpan ExpandSpan(SourceText sourceText, TextSpan span, bool fullyQualifiedName) { if (span.Length != 0) { return span; } var startInclusive = span.Start; var endExclusive = span.Start; while (startInclusive > 0 && ShouldExpandSpanBackwardOneCharacter(sourceText, startInclusive, fullyQualifiedName)) { startInclusive--; } while (endExclusive < sourceText.Length && ShouldExpandSpanForwardOneCharacter(sourceText, endExclusive, fullyQualifiedName)) { endExclusive++; } return TextSpan.FromBounds(startInclusive, endExclusive); } private static bool ShouldExpandSpanForwardOneCharacter( SourceText sourceText, int endExclusive, bool fullyQualifiedName) { var currentChar = sourceText[endExclusive]; if (char.IsLetterOrDigit(currentChar)) { return true; } // Only consume a dot in front of the current word if it is part of a dotted // word chain, and isn't just the end of a sentence. if (fullyQualifiedName && currentChar == '.' && endExclusive + 1 < sourceText.Length && char.IsLetterOrDigit(sourceText[endExclusive + 1])) { return true; } return false; } private static bool ShouldExpandSpanBackwardOneCharacter( SourceText sourceText, int startInclusive, bool fullyQualifiedName) { Debug.Assert(startInclusive > 0); var previousCharacter = sourceText[startInclusive - 1]; if (char.IsLetterOrDigit(previousCharacter)) { return true; } if (fullyQualifiedName && previousCharacter == '.') { return true; } return false; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ReplaceDocCommentTextWithTag { internal abstract class AbstractReplaceDocCommentTextWithTagCodeRefactoringProvider : CodeRefactoringProvider { protected abstract bool IsInXMLAttribute(SyntaxToken token); protected abstract bool IsKeyword(string text); protected abstract bool IsXmlTextToken(SyntaxToken token); protected abstract SyntaxNode ParseExpression(string text); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(span.Start, findInsideTrivia: true); if (!IsXmlTextToken(token)) { return; } if (!token.FullSpan.Contains(span)) { return; } if (IsInXMLAttribute(token)) { return; } var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var singleWordSpan = ExpandSpan(sourceText, span, fullyQualifiedName: false); var singleWordText = sourceText.ToString(singleWordSpan); if (singleWordText == "") { return; } // First see if they're on an appropriate keyword. if (IsKeyword(singleWordText)) { RegisterRefactoring(context, singleWordSpan, $@"<see langword=""{singleWordText}""/>"); return; } // Not a keyword, see if it semantically means anything in the current context. var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var symbol = GetEnclosingSymbol(semanticModel, span.Start, cancellationToken); if (symbol == null) { return; } // See if we can expand the term out to a fully qualified name. Do this // first in case the user has something like X.memberName. We don't want // to try to bind "memberName" first as it might bind to something like // a parameter, which is not what the user intends var fullyQualifiedSpan = ExpandSpan(sourceText, span, fullyQualifiedName: true); if (fullyQualifiedSpan != singleWordSpan) { var fullyQualifiedText = sourceText.ToString(fullyQualifiedSpan); if (TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, fullyQualifiedSpan, cancellationToken)) { return; } } // Check if the single word could be binding to a type parameter or parameter // for the current symbol. var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var parameter = symbol.GetParameters().FirstOrDefault(p => syntaxFacts.StringComparer.Equals(p.Name, singleWordText)); if (parameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<paramref name=""{singleWordText}""/>"); return; } var typeParameter = symbol.GetTypeParameters().FirstOrDefault(t => syntaxFacts.StringComparer.Equals(t.Name, singleWordText)); if (typeParameter != null) { RegisterRefactoring(context, singleWordSpan, $@"<typeparamref name=""{singleWordText}""/>"); return; } // Doc comments on a named type can see the members inside of it. So check // inside the named type for a member that matches. if (symbol is INamedTypeSymbol namedType) { var childMember = namedType.GetMembers().FirstOrDefault(m => syntaxFacts.StringComparer.Equals(m.Name, singleWordText)); if (childMember != null) { RegisterRefactoring(context, singleWordSpan, $@"<see cref=""{singleWordText}""/>"); return; } } // Finally, try to speculatively bind the name and see if it binds to anything // in the surrounding context. TryRegisterSeeCrefTagIfSymbol( context, semanticModel, token, singleWordSpan, cancellationToken); } private bool TryRegisterSeeCrefTagIfSymbol( CodeRefactoringContext context, SemanticModel semanticModel, SyntaxToken token, TextSpan replacementSpan, CancellationToken cancellationToken) { var sourceText = semanticModel.SyntaxTree.GetText(cancellationToken); var text = sourceText.ToString(replacementSpan); var parsed = ParseExpression(text); var foundSymbol = semanticModel.GetSpeculativeSymbolInfo(token.SpanStart, parsed, SpeculativeBindingOption.BindAsExpression).GetAnySymbol(); if (foundSymbol == null) { return false; } RegisterRefactoring(context, replacementSpan, $@"<see cref=""{text}""/>"); return true; } private static ISymbol GetEnclosingSymbol(SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var root = semanticModel.SyntaxTree.GetRoot(cancellationToken); var token = root.FindToken(position); for (var node = token.Parent; node != null; node = node.Parent) { if (semanticModel.GetDeclaredSymbol(node, cancellationToken) is ISymbol declaration) { return declaration; } } return null; } private static void RegisterRefactoring( CodeRefactoringContext context, TextSpan expandedSpan, string replacement) { context.RegisterRefactoring( new MyCodeAction( string.Format(FeaturesResources.Use_0, replacement), c => ReplaceTextAsync(context.Document, expandedSpan, replacement, c)), expandedSpan); } private static async Task<Document> ReplaceTextAsync( Document document, TextSpan span, string replacement, CancellationToken cancellationToken) { var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newText = text.Replace(span, replacement); return document.WithText(newText); } private static TextSpan ExpandSpan(SourceText sourceText, TextSpan span, bool fullyQualifiedName) { if (span.Length != 0) { return span; } var startInclusive = span.Start; var endExclusive = span.Start; while (startInclusive > 0 && ShouldExpandSpanBackwardOneCharacter(sourceText, startInclusive, fullyQualifiedName)) { startInclusive--; } while (endExclusive < sourceText.Length && ShouldExpandSpanForwardOneCharacter(sourceText, endExclusive, fullyQualifiedName)) { endExclusive++; } return TextSpan.FromBounds(startInclusive, endExclusive); } private static bool ShouldExpandSpanForwardOneCharacter( SourceText sourceText, int endExclusive, bool fullyQualifiedName) { var currentChar = sourceText[endExclusive]; if (char.IsLetterOrDigit(currentChar)) { return true; } // Only consume a dot in front of the current word if it is part of a dotted // word chain, and isn't just the end of a sentence. if (fullyQualifiedName && currentChar == '.' && endExclusive + 1 < sourceText.Length && char.IsLetterOrDigit(sourceText[endExclusive + 1])) { return true; } return false; } private static bool ShouldExpandSpanBackwardOneCharacter( SourceText sourceText, int startInclusive, bool fullyQualifiedName) { Debug.Assert(startInclusive > 0); var previousCharacter = sourceText[startInclusive - 1]; if (char.IsLetterOrDigit(previousCharacter)) { return true; } if (fullyQualifiedName && previousCharacter == '.') { return true; } return false; } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.NuintValueSetFactory.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.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private sealed class NuintValueSetFactory : IValueSetFactory<uint>, IValueSetFactory { public static readonly NuintValueSetFactory Instance = new NuintValueSetFactory(); private NuintValueSetFactory() { } IValueSet IValueSetFactory.AllValues => NuintValueSet.AllValues; IValueSet IValueSetFactory.NoValues => NuintValueSet.NoValues; public IValueSet<uint> Related(BinaryOperatorKind relation, uint value) { return new NuintValueSet( values: NumericValueSetFactory<uint, UIntTC>.Instance.Related(relation, value), hasLarge: relation switch { GreaterThan => true, GreaterThanOrEqual => true, _ => false } ); } IValueSet IValueSetFactory.Random(int expectedSize, Random random) { return new NuintValueSet( values: (IValueSet<uint>)NumericValueSetFactory<uint, UIntTC>.Instance.Random(expectedSize, random), hasLarge: random.NextDouble() < 0.25 ); } ConstantValue IValueSetFactory.RandomValue(Random random) => ConstantValue.CreateNativeUInt(default(UIntTC).Random(random)); IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) { return value.IsBad ? NuintValueSet.AllValues : Related(relation, default(UIntTC).FromConstantValue(value)); } bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) { var tc = default(UIntTC); return tc.Related(relation, tc.FromConstantValue(left), tc.FromConstantValue(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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private sealed class NuintValueSetFactory : IValueSetFactory<uint>, IValueSetFactory { public static readonly NuintValueSetFactory Instance = new NuintValueSetFactory(); private NuintValueSetFactory() { } IValueSet IValueSetFactory.AllValues => NuintValueSet.AllValues; IValueSet IValueSetFactory.NoValues => NuintValueSet.NoValues; public IValueSet<uint> Related(BinaryOperatorKind relation, uint value) { return new NuintValueSet( values: NumericValueSetFactory<uint, UIntTC>.Instance.Related(relation, value), hasLarge: relation switch { GreaterThan => true, GreaterThanOrEqual => true, _ => false } ); } IValueSet IValueSetFactory.Random(int expectedSize, Random random) { return new NuintValueSet( values: (IValueSet<uint>)NumericValueSetFactory<uint, UIntTC>.Instance.Random(expectedSize, random), hasLarge: random.NextDouble() < 0.25 ); } ConstantValue IValueSetFactory.RandomValue(Random random) => ConstantValue.CreateNativeUInt(default(UIntTC).Random(random)); IValueSet IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue value) { return value.IsBad ? NuintValueSet.AllValues : Related(relation, default(UIntTC).FromConstantValue(value)); } bool IValueSetFactory.Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right) { var tc = default(UIntTC); return tc.Related(relation, tc.FromConstantValue(left), tc.FromConstantValue(right)); } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualBasic/Impl/Progression/VisualBasicGraphProvider.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.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Microsoft.VisualStudio.Shell Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression <GraphProvider(Name:="VisualBasicRoslynProvider", ProjectCapability:="VB")> Friend NotInheritable Class VisualBasicGraphProvider Inherits AbstractGraphProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext, glyphService As IGlyphService, serviceProvider As SVsServiceProvider, workspaceProvider As IProgressionPrimaryWorkspaceProvider, listenerProvider As IAsynchronousOperationListenerProvider) MyBase.New(threadingContext, glyphService, serviceProvider, workspaceProvider.PrimaryWorkspace, listenerProvider) 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.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.Language.Intellisense Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Microsoft.VisualStudio.Shell Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression <GraphProvider(Name:="VisualBasicRoslynProvider", ProjectCapability:="VB")> Friend NotInheritable Class VisualBasicGraphProvider Inherits AbstractGraphProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(threadingContext As IThreadingContext, glyphService As IGlyphService, serviceProvider As SVsServiceProvider, workspaceProvider As IProgressionPrimaryWorkspaceProvider, listenerProvider As IAsynchronousOperationListenerProvider) MyBase.New(threadingContext, glyphService, serviceProvider, workspaceProvider.PrimaryWorkspace, listenerProvider) End Sub End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Semantics/SpeculationAnalyzerTests.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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests.Semantics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Semantics Public Class SpeculationAnalyzerTests Inherits SpeculationAnalyzerTestsBase <Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")> Public Sub SpeculationAnalyzerExtensionMethodExplicitInvocation() Test(<Code> Module Oombr &lt;System.Runtime.CompilerServices.Extension&gt; Public Sub Vain(arg As Integer) End Sub Sub Main() Call [|5.Vain()|] End Sub End Module </Code>.Value, "Vain(5)", False) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerIndexerPropertyWithRedundantCast() Test(<Code> Class Indexer Default Public ReadOnly Property Item(ByVal x As Integer) As Integer Get Return x End Get End Property End Class Class A Public ReadOnly Property Foo As Indexer End Class Class B Inherits A End Class Class Program Sub Main() Dim b As B = New B() Dim y As Integer = [|DirectCast(b, A)|].Foo(2) End Sub End Class </Code>.Value, "b", False) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerIndexerPropertyWithRequiredCast() Test(<Code> Class Indexer Default Public ReadOnly Property Item(ByVal x As Integer) As Integer Get Return x End Get End Property End Class Class A Public ReadOnly Property Foo As Indexer End Class Class B Inherits A Public Shadows ReadOnly Property Foo As Indexer End Class Class Program Sub Main() Dim b As B = New B() Dim y As Integer = [|DirectCast(b, A)|].Foo(2) End Sub End Class </Code>.Value, "b", True) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerDelegatePropertyWithRedundantCast() Test(<Code> Public Delegate Sub MyDelegate() Class A Public ReadOnly Property Foo As MyDelegate End Class Class B Inherits A End Class Class Program Sub Main() Dim b As B = New B() [|DirectCast(b, A)|].Foo.Invoke() End Sub End Class </Code>.Value, "b", False) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerDelegatePropertyWithRequiredCast() Test(<Code> Public Delegate Sub MyDelegate() Class A Public ReadOnly Property Foo As MyDelegate End Class Class B Inherits A Public Shadows ReadOnly Property Foo As MyDelegate End Class Class Program Sub Main() Dim b As B = New B() [|DirectCast(b, A)|].Foo.Invoke() End Sub End Class </Code>.Value, "b", True) End Sub Protected Overrides Function Parse(text As String) As SyntaxTree Return SyntaxFactory.ParseSyntaxTree(text) End Function Protected Overrides Function IsExpressionNode(node As SyntaxNode) As Boolean Return TypeOf node Is ExpressionSyntax End Function Protected Overrides Function CreateCompilation(tree As SyntaxTree) As Compilation Return VisualBasicCompilation.Create( CompilationName, {DirectCast(tree, VisualBasicSyntaxTree)}, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC0219", ReportDiagnostic.Suppress)})) End Function Protected Overrides Function CompilationSucceeded(compilation As Compilation, temporaryStream As Stream) As Boolean Dim langCompilation = DirectCast(compilation, VisualBasicCompilation) Return Not langCompilation.GetDiagnostics().Any() AndAlso Not langCompilation.Emit(temporaryStream).Diagnostics.Any() End Function Protected Overrides Function ReplacementChangesSemantics(initialNode As SyntaxNode, replacementNode As SyntaxNode, initialModel As SemanticModel) As Boolean Return New SpeculationAnalyzer(DirectCast(initialNode, ExpressionSyntax), DirectCast(replacementNode, ExpressionSyntax), initialModel, CancellationToken.None).ReplacementChangesSemantics() 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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.UnitTests.Semantics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Semantics Public Class SpeculationAnalyzerTests Inherits SpeculationAnalyzerTestsBase <Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")> Public Sub SpeculationAnalyzerExtensionMethodExplicitInvocation() Test(<Code> Module Oombr &lt;System.Runtime.CompilerServices.Extension&gt; Public Sub Vain(arg As Integer) End Sub Sub Main() Call [|5.Vain()|] End Sub End Module </Code>.Value, "Vain(5)", False) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerIndexerPropertyWithRedundantCast() Test(<Code> Class Indexer Default Public ReadOnly Property Item(ByVal x As Integer) As Integer Get Return x End Get End Property End Class Class A Public ReadOnly Property Foo As Indexer End Class Class B Inherits A End Class Class Program Sub Main() Dim b As B = New B() Dim y As Integer = [|DirectCast(b, A)|].Foo(2) End Sub End Class </Code>.Value, "b", False) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerIndexerPropertyWithRequiredCast() Test(<Code> Class Indexer Default Public ReadOnly Property Item(ByVal x As Integer) As Integer Get Return x End Get End Property End Class Class A Public ReadOnly Property Foo As Indexer End Class Class B Inherits A Public Shadows ReadOnly Property Foo As Indexer End Class Class Program Sub Main() Dim b As B = New B() Dim y As Integer = [|DirectCast(b, A)|].Foo(2) End Sub End Class </Code>.Value, "b", True) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerDelegatePropertyWithRedundantCast() Test(<Code> Public Delegate Sub MyDelegate() Class A Public ReadOnly Property Foo As MyDelegate End Class Class B Inherits A End Class Class Program Sub Main() Dim b As B = New B() [|DirectCast(b, A)|].Foo.Invoke() End Sub End Class </Code>.Value, "b", False) End Sub <Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")> Public Sub SpeculationAnalyzerDelegatePropertyWithRequiredCast() Test(<Code> Public Delegate Sub MyDelegate() Class A Public ReadOnly Property Foo As MyDelegate End Class Class B Inherits A Public Shadows ReadOnly Property Foo As MyDelegate End Class Class Program Sub Main() Dim b As B = New B() [|DirectCast(b, A)|].Foo.Invoke() End Sub End Class </Code>.Value, "b", True) End Sub Protected Overrides Function Parse(text As String) As SyntaxTree Return SyntaxFactory.ParseSyntaxTree(text) End Function Protected Overrides Function IsExpressionNode(node As SyntaxNode) As Boolean Return TypeOf node Is ExpressionSyntax End Function Protected Overrides Function CreateCompilation(tree As SyntaxTree) As Compilation Return VisualBasicCompilation.Create( CompilationName, {DirectCast(tree, VisualBasicSyntaxTree)}, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC0219", ReportDiagnostic.Suppress)})) End Function Protected Overrides Function CompilationSucceeded(compilation As Compilation, temporaryStream As Stream) As Boolean Dim langCompilation = DirectCast(compilation, VisualBasicCompilation) Return Not langCompilation.GetDiagnostics().Any() AndAlso Not langCompilation.Emit(temporaryStream).Diagnostics.Any() End Function Protected Overrides Function ReplacementChangesSemantics(initialNode As SyntaxNode, replacementNode As SyntaxNode, initialModel As SemanticModel) As Boolean Return New SpeculationAnalyzer(DirectCast(initialNode, ExpressionSyntax), DirectCast(replacementNode, ExpressionSyntax), initialModel, CancellationToken.None).ReplacementChangesSemantics() End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Wpf/InlineRename/Dashboard/DashboardAutomationPeer.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.Windows.Automation.Peers; using System.Windows.Controls; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { /// <summary> /// Custom AutomationPeer to announce that an Inline Rename session has begun. /// </summary> internal class DashboardAutomationPeer : UserControlAutomationPeer { private readonly string _identifier; public DashboardAutomationPeer(UserControl owner, string identifier) : base(owner) => _identifier = identifier; protected override bool HasKeyboardFocusCore() => true; protected override bool IsKeyboardFocusableCore() => true; protected override string GetNameCore() => string.Format(EditorFeaturesResources.An_inline_rename_session_is_active_for_identifier_0, _identifier); protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Custom; } }
// Licensed to the .NET Foundation under one or more 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.Windows.Automation.Peers; using System.Windows.Controls; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { /// <summary> /// Custom AutomationPeer to announce that an Inline Rename session has begun. /// </summary> internal class DashboardAutomationPeer : UserControlAutomationPeer { private readonly string _identifier; public DashboardAutomationPeer(UserControl owner, string identifier) : base(owner) => _identifier = identifier; protected override bool HasKeyboardFocusCore() => true; protected override bool IsKeyboardFocusableCore() => true; protected override string GetNameCore() => string.Format(EditorFeaturesResources.An_inline_rename_session_is_active_for_identifier_0, _identifier); protected override AutomationControlType GetAutomationControlTypeCore() => AutomationControlType.Custom; } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/FSharp/FSharpDocumentSpan.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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { /// <summary> /// Represents a <see cref="TextSpan"/> location in a <see cref="Document"/>. /// </summary> internal readonly struct FSharpDocumentSpan : IEquatable<FSharpDocumentSpan> { public Document Document { get; } public TextSpan SourceSpan { get; } /// <summary> /// Additional information attached to a document span by it creator. /// </summary> public ImmutableDictionary<string, object> Properties { get; } public FSharpDocumentSpan(Document document, TextSpan sourceSpan) : this(document, sourceSpan, properties: null) { } public FSharpDocumentSpan( Document document, TextSpan sourceSpan, ImmutableDictionary<string, object> properties) { Document = document; SourceSpan = sourceSpan; Properties = properties ?? ImmutableDictionary<string, object>.Empty; } public override bool Equals(object obj) => Equals((FSharpDocumentSpan)obj); public bool Equals(FSharpDocumentSpan obj) => this.Document == obj.Document && this.SourceSpan == obj.SourceSpan; public static bool operator ==(FSharpDocumentSpan d1, FSharpDocumentSpan d2) => d1.Equals(d2); public static bool operator !=(FSharpDocumentSpan d1, FSharpDocumentSpan d2) => !(d1 == d2); public override int GetHashCode() => Hash.Combine( this.Document, this.SourceSpan.GetHashCode()); internal Microsoft.CodeAnalysis.DocumentSpan ToRoslynDocumentSpan() { return new Microsoft.CodeAnalysis.DocumentSpan(this.Document, this.SourceSpan, this.Properties); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp { /// <summary> /// Represents a <see cref="TextSpan"/> location in a <see cref="Document"/>. /// </summary> internal readonly struct FSharpDocumentSpan : IEquatable<FSharpDocumentSpan> { public Document Document { get; } public TextSpan SourceSpan { get; } /// <summary> /// Additional information attached to a document span by it creator. /// </summary> public ImmutableDictionary<string, object> Properties { get; } public FSharpDocumentSpan(Document document, TextSpan sourceSpan) : this(document, sourceSpan, properties: null) { } public FSharpDocumentSpan( Document document, TextSpan sourceSpan, ImmutableDictionary<string, object> properties) { Document = document; SourceSpan = sourceSpan; Properties = properties ?? ImmutableDictionary<string, object>.Empty; } public override bool Equals(object obj) => Equals((FSharpDocumentSpan)obj); public bool Equals(FSharpDocumentSpan obj) => this.Document == obj.Document && this.SourceSpan == obj.SourceSpan; public static bool operator ==(FSharpDocumentSpan d1, FSharpDocumentSpan d2) => d1.Equals(d2); public static bool operator !=(FSharpDocumentSpan d1, FSharpDocumentSpan d2) => !(d1 == d2); public override int GetHashCode() => Hash.Combine( this.Document, this.SourceSpan.GetHashCode()); internal Microsoft.CodeAnalysis.DocumentSpan ToRoslynDocumentSpan() { return new Microsoft.CodeAnalysis.DocumentSpan(this.Document, this.SourceSpan, this.Properties); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Test/Progression/OverridesGraphQueryTests.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.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class OverridesGraphQueryTests <WpfFact> Public Async Function TestOverridesMethod1() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; abstract class Base { public abstract int $$CompareTo(object obj); } class Goo : Base, IComparable { public override int CompareTo(object obj) { throw new NotImplementedException(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New OverridesGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Base Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" Label="CompareTo"/> <Node Id="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="CompareTo"/> </Nodes> <Links> <Link Source="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Target="(@1 Type=Base Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WpfFact> Public Async Function TestOverridesMethod2() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; abstract class Base { public abstract int CompareTo(object obj); } class Goo : Base, IComparable { public override int $$CompareTo(object obj) { throw new NotImplementedException(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New OverridesGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="CompareTo"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class OverridesGraphQueryTests <WpfFact> Public Async Function TestOverridesMethod1() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; abstract class Base { public abstract int $$CompareTo(object obj); } class Goo : Base, IComparable { public override int CompareTo(object obj) { throw new NotImplementedException(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New OverridesGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Base Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" Label="CompareTo"/> <Node Id="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="CompareTo"/> </Nodes> <Links> <Link Source="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Target="(@1 Type=Base Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function <WpfFact> Public Async Function TestOverridesMethod2() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> using System; abstract class Base { public abstract int CompareTo(object obj); } class Goo : Base, IComparable { public override int $$CompareTo(object obj) { throw new NotImplementedException(); } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New OverridesGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" IsOverloaded="True" Label="CompareTo"/> </Nodes> <Links/> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/InternalUtilities/IReadOnlySet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Roslyn.Utilities { internal interface IReadOnlySet<T> { int Count { get; } bool Contains(T item); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities { internal interface IReadOnlySet<T> { int Count { get; } bool Contains(T item); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/GenerateComparisonOperators/GenerateComparisonOperatorsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< Microsoft.CodeAnalysis.GenerateComparisonOperators.GenerateComparisonOperatorsCodeRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateComparisonOperators { [UseExportProvider] public class GenerateComparisonOperatorsTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestClass() { await VerifyCS.VerifyRefactoringAsync( @" using System; [||]class C : IComparable<C> { public int CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestPreferExpressionBodies() { await new VerifyCS.Test { TestCode = @" using System; [||]class C : IComparable<C> { public int CompareTo(C c) => 0; }", FixedCode = @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) => left.CompareTo(right) < 0; public static bool operator >(C left, C right) => left.CompareTo(right) > 0; public static bool operator <=(C left, C right) => left.CompareTo(right) <= 0; public static bool operator >=(C left, C right) => left.CompareTo(right) >= 0; }", EditorConfig = CodeFixVerifierHelper.GetEditorConfigText( new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement }, }), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestExplicitImpl() { await VerifyCS.VerifyRefactoringAsync( @" using System; [||]class C : IComparable<C> { int IComparable<C>.CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { int IComparable<C>.CompareTo(C c) => 0; public static bool operator <(C left, C right) { return ((IComparable<C>)left).CompareTo(right) < 0; } public static bool operator >(C left, C right) { return ((IComparable<C>)left).CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return ((IComparable<C>)left).CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return ((IComparable<C>)left).CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestOnInterface() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : [||]IComparable<C> { public int CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestAtEndOfInterface() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : IComparable<C>[||] { public int CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestInBody() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; [||] }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMissingWithoutCompareMethod() { var code = @" using System; class C : {|CS0535:IComparable<C>|} { [||] }"; await VerifyCS.VerifyRefactoringAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMissingWithUnknownType() { var code = @" using System; class C : IComparable<{|CS0246:Goo|}> { public int CompareTo({|CS0246:Goo|} g) => 0; [||] }"; await VerifyCS.VerifyRefactoringAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMissingWithAllExistingOperators() { var code = @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } [||] }"; await VerifyCS.VerifyRefactoringAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestWithExistingOperator() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator {|CS0216:<|}(C left, C right) { return left.CompareTo(right) < 0; } [||] }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMultipleInterfaces() { var code = @" using System; class C : IComparable<C>, IComparable<int> { public int CompareTo(C c) => 0; public int CompareTo(int c) => 0; [||] }"; string GetFixedCode(string type) => $@" using System; class C : IComparable<C>, IComparable<int> {{ public int CompareTo(C c) => 0; public int CompareTo(int c) => 0; public static bool operator <(C left, {type} right) {{ return left.CompareTo(right) < 0; }} public static bool operator >(C left, {type} right) {{ return left.CompareTo(right) > 0; }} public static bool operator <=(C left, {type} right) {{ return left.CompareTo(right) <= 0; }} public static bool operator >=(C left, {type} right) {{ return left.CompareTo(right) >= 0; }} }}"; await new VerifyCS.Test { TestCode = code, FixedCode = GetFixedCode("C"), CodeActionIndex = 0, CodeActionEquivalenceKey = "Generate_for_0_C", }.RunAsync(); await new VerifyCS.Test { TestCode = code, FixedCode = GetFixedCode("int"), CodeActionIndex = 1, CodeActionEquivalenceKey = "Generate_for_0_int", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestInInterfaceWithDefaultImpl() { await VerifyCS.VerifyRefactoringAsync( @" using System; interface C : IComparable<C> { int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0; [||] }", @" using System; interface C : IComparable<C> { int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0; public static bool operator {|CS8701:<|}(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator {|CS8701:>|}(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator {|CS8701:<=|}(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator {|CS8701:>=|}(C left, C right) { return left.CompareTo(right) >= 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeRefactoringVerifier< Microsoft.CodeAnalysis.GenerateComparisonOperators.GenerateComparisonOperatorsCodeRefactoringProvider>; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.GenerateComparisonOperators { [UseExportProvider] public class GenerateComparisonOperatorsTests { [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestClass() { await VerifyCS.VerifyRefactoringAsync( @" using System; [||]class C : IComparable<C> { public int CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestPreferExpressionBodies() { await new VerifyCS.Test { TestCode = @" using System; [||]class C : IComparable<C> { public int CompareTo(C c) => 0; }", FixedCode = @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) => left.CompareTo(right) < 0; public static bool operator >(C left, C right) => left.CompareTo(right) > 0; public static bool operator <=(C left, C right) => left.CompareTo(right) <= 0; public static bool operator >=(C left, C right) => left.CompareTo(right) >= 0; }", EditorConfig = CodeFixVerifierHelper.GetEditorConfigText( new OptionsCollection(LanguageNames.CSharp) { { CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement }, }), }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestExplicitImpl() { await VerifyCS.VerifyRefactoringAsync( @" using System; [||]class C : IComparable<C> { int IComparable<C>.CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { int IComparable<C>.CompareTo(C c) => 0; public static bool operator <(C left, C right) { return ((IComparable<C>)left).CompareTo(right) < 0; } public static bool operator >(C left, C right) { return ((IComparable<C>)left).CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return ((IComparable<C>)left).CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return ((IComparable<C>)left).CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestOnInterface() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : [||]IComparable<C> { public int CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestAtEndOfInterface() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : IComparable<C>[||] { public int CompareTo(C c) => 0; }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestInBody() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; [||] }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMissingWithoutCompareMethod() { var code = @" using System; class C : {|CS0535:IComparable<C>|} { [||] }"; await VerifyCS.VerifyRefactoringAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMissingWithUnknownType() { var code = @" using System; class C : IComparable<{|CS0246:Goo|}> { public int CompareTo({|CS0246:Goo|} g) => 0; [||] }"; await VerifyCS.VerifyRefactoringAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMissingWithAllExistingOperators() { var code = @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } [||] }"; await VerifyCS.VerifyRefactoringAsync(code, code); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestWithExistingOperator() { await VerifyCS.VerifyRefactoringAsync( @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator {|CS0216:<|}(C left, C right) { return left.CompareTo(right) < 0; } [||] }", @" using System; class C : IComparable<C> { public int CompareTo(C c) => 0; public static bool operator <(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator >(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator <=(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator >=(C left, C right) { return left.CompareTo(right) >= 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestMultipleInterfaces() { var code = @" using System; class C : IComparable<C>, IComparable<int> { public int CompareTo(C c) => 0; public int CompareTo(int c) => 0; [||] }"; string GetFixedCode(string type) => $@" using System; class C : IComparable<C>, IComparable<int> {{ public int CompareTo(C c) => 0; public int CompareTo(int c) => 0; public static bool operator <(C left, {type} right) {{ return left.CompareTo(right) < 0; }} public static bool operator >(C left, {type} right) {{ return left.CompareTo(right) > 0; }} public static bool operator <=(C left, {type} right) {{ return left.CompareTo(right) <= 0; }} public static bool operator >=(C left, {type} right) {{ return left.CompareTo(right) >= 0; }} }}"; await new VerifyCS.Test { TestCode = code, FixedCode = GetFixedCode("C"), CodeActionIndex = 0, CodeActionEquivalenceKey = "Generate_for_0_C", }.RunAsync(); await new VerifyCS.Test { TestCode = code, FixedCode = GetFixedCode("int"), CodeActionIndex = 1, CodeActionEquivalenceKey = "Generate_for_0_int", }.RunAsync(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateComparisonOperators)] public async Task TestInInterfaceWithDefaultImpl() { await VerifyCS.VerifyRefactoringAsync( @" using System; interface C : IComparable<C> { int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0; [||] }", @" using System; interface C : IComparable<C> { int IComparable<C>.{|CS8701:CompareTo|}(C c) => 0; public static bool operator {|CS8701:<|}(C left, C right) { return left.CompareTo(right) < 0; } public static bool operator {|CS8701:>|}(C left, C right) { return left.CompareTo(right) > 0; } public static bool operator {|CS8701:<=|}(C left, C right) { return left.CompareTo(right) <= 0; } public static bool operator {|CS8701:>=|}(C left, C right) { return left.CompareTo(right) >= 0; } }"); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/CodeAnalysisTest/CommonSyntaxTests.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.Text; using Roslyn.Test.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using CS = Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSyntaxTests { [Fact] public void Kinds() { foreach (CS.SyntaxKind kind in Enum.GetValues(typeof(CS.SyntaxKind))) { Assert.True(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should be C# kind"); if (kind != CS.SyntaxKind.None && kind != CS.SyntaxKind.List) { Assert.False(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should not be VB kind"); } } foreach (VB.SyntaxKind kind in Enum.GetValues(typeof(VB.SyntaxKind))) { Assert.True(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should be VB kind"); if (kind != VB.SyntaxKind.None && kind != VB.SyntaxKind.List) { Assert.False(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should not be C# kind"); } } } [Fact] public void SyntaxNodeOrToken() { var d = default(SyntaxNodeOrToken); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void SyntaxNodeOrToken1() { var d = (SyntaxNodeOrToken)((SyntaxNode)null); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void CommonSyntaxToString_CSharp() { SyntaxNode node = CSharp.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = CSharp.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxToString_VisualBasic() { SyntaxNode node = VB.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = VB.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxTriviaSpan_CSharp() { var csharpToken = CSharp.SyntaxFactory.ParseExpression("1 + 123 /*hello*/").GetLastToken(); var csharpTriviaList = csharpToken.TrailingTrivia; Assert.Equal(2, csharpTriviaList.Count); var csharpTrivia = csharpTriviaList.ElementAt(1); Assert.Equal(CSharp.SyntaxKind.MultiLineCommentTrivia, CSharp.CSharpExtensions.Kind(csharpTrivia)); var correctSpan = csharpTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(17, correctSpan.End); var commonTrivia = (SyntaxTrivia)csharpTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)csharpTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)csharpToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var csharpTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, csharpTrivia2.Span); var csharpTriviaList2 = (SyntaxTriviaList)commonTriviaList; var csharpTrivia3 = csharpTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, csharpTrivia3.Span); } [Fact] public void CommonSyntaxTriviaSpan_VisualBasic() { var vbToken = VB.SyntaxFactory.ParseExpression("1 + 123 'hello").GetLastToken(); var vbTriviaList = (SyntaxTriviaList)vbToken.TrailingTrivia; Assert.Equal(2, vbTriviaList.Count); var vbTrivia = vbTriviaList.ElementAt(1); Assert.Equal(VB.SyntaxKind.CommentTrivia, VB.VisualBasicExtensions.Kind(vbTrivia)); var correctSpan = vbTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(14, correctSpan.End); var commonTrivia = (SyntaxTrivia)vbTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)vbTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)vbToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var vbTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, vbTrivia2.Span); var vbTriviaList2 = (SyntaxTriviaList)commonTriviaList; var vbTrivia3 = vbTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, vbTrivia3.Span); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void CSharpSyntax_VisualBasicKind() { var node = CSharp.SyntaxFactory.Identifier("a"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(node)); var token = CSharp.SyntaxFactory.Token(CSharp.SyntaxKind.IfKeyword); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(token)); var trivia = CSharp.SyntaxFactory.Comment("c"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(trivia)); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void VisualBasicSyntax_CSharpKind() { var node = VisualBasic.SyntaxFactory.Identifier("a"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(node)); var token = VisualBasic.SyntaxFactory.Token(VisualBasic.SyntaxKind.IfKeyword); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(token)); var trivia = VisualBasic.SyntaxFactory.CommentTrivia("c"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(trivia)); } [Fact] public void TestTrackNodes() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } [Fact] public void TestTrackNodesWithDuplicateIdAnnotations() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); var annotation = trackedExpr.GetAnnotatedNodes(SyntaxNodeExtensions.IdAnnotationKind).First() .GetAnnotations(SyntaxNodeExtensions.IdAnnotationKind).First(); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten).WithAdditionalAnnotations(annotation)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Roslyn.Test.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using CS = Microsoft.CodeAnalysis.CSharp; namespace Microsoft.CodeAnalysis.UnitTests { public class CommonSyntaxTests { [Fact] public void Kinds() { foreach (CS.SyntaxKind kind in Enum.GetValues(typeof(CS.SyntaxKind))) { Assert.True(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should be C# kind"); if (kind != CS.SyntaxKind.None && kind != CS.SyntaxKind.List) { Assert.False(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should not be VB kind"); } } foreach (VB.SyntaxKind kind in Enum.GetValues(typeof(VB.SyntaxKind))) { Assert.True(VB.VisualBasicExtensions.IsVisualBasicKind((int)kind), kind + " should be VB kind"); if (kind != VB.SyntaxKind.None && kind != VB.SyntaxKind.List) { Assert.False(CS.CSharpExtensions.IsCSharpKind((int)kind), kind + " should not be C# kind"); } } } [Fact] public void SyntaxNodeOrToken() { var d = default(SyntaxNodeOrToken); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void SyntaxNodeOrToken1() { var d = (SyntaxNodeOrToken)((SyntaxNode)null); Assert.True(d.IsToken); Assert.False(d.IsNode); Assert.Equal(0, d.RawKind); Assert.Equal("", d.Language); Assert.Equal(default(TextSpan), d.FullSpan); Assert.Equal(default(TextSpan), d.Span); Assert.Equal("", d.ToString()); Assert.Equal("", d.ToFullString()); Assert.Equal("SyntaxNodeOrToken None ", d.GetDebuggerDisplay()); } [Fact] public void CommonSyntaxToString_CSharp() { SyntaxNode node = CSharp.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = CSharp.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxToString_VisualBasic() { SyntaxNode node = VB.SyntaxFactory.IdentifierName("test"); Assert.Equal("test", node.ToString()); SyntaxNodeOrToken nodeOrToken = node; Assert.Equal("test", nodeOrToken.ToString()); SyntaxToken token = node.DescendantTokens().Single(); Assert.Equal("test", token.ToString()); SyntaxTrivia trivia = VB.SyntaxFactory.Whitespace("test"); Assert.Equal("test", trivia.ToString()); } [Fact] public void CommonSyntaxTriviaSpan_CSharp() { var csharpToken = CSharp.SyntaxFactory.ParseExpression("1 + 123 /*hello*/").GetLastToken(); var csharpTriviaList = csharpToken.TrailingTrivia; Assert.Equal(2, csharpTriviaList.Count); var csharpTrivia = csharpTriviaList.ElementAt(1); Assert.Equal(CSharp.SyntaxKind.MultiLineCommentTrivia, CSharp.CSharpExtensions.Kind(csharpTrivia)); var correctSpan = csharpTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(17, correctSpan.End); var commonTrivia = (SyntaxTrivia)csharpTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)csharpTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)csharpToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var csharpTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, csharpTrivia2.Span); var csharpTriviaList2 = (SyntaxTriviaList)commonTriviaList; var csharpTrivia3 = csharpTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, csharpTrivia3.Span); } [Fact] public void CommonSyntaxTriviaSpan_VisualBasic() { var vbToken = VB.SyntaxFactory.ParseExpression("1 + 123 'hello").GetLastToken(); var vbTriviaList = (SyntaxTriviaList)vbToken.TrailingTrivia; Assert.Equal(2, vbTriviaList.Count); var vbTrivia = vbTriviaList.ElementAt(1); Assert.Equal(VB.SyntaxKind.CommentTrivia, VB.VisualBasicExtensions.Kind(vbTrivia)); var correctSpan = vbTrivia.Span; Assert.Equal(8, correctSpan.Start); Assert.Equal(14, correctSpan.End); var commonTrivia = (SyntaxTrivia)vbTrivia; //direct conversion Assert.Equal(correctSpan, commonTrivia.Span); var commonTriviaList = (SyntaxTriviaList)vbTriviaList; var commonTrivia2 = commonTriviaList[1]; //from converted list Assert.Equal(correctSpan, commonTrivia2.Span); var commonToken = (SyntaxToken)vbToken; var commonTriviaList2 = commonToken.TrailingTrivia; var commonTrivia3 = commonTriviaList2[1]; //from converted token Assert.Equal(correctSpan, commonTrivia3.Span); var vbTrivia2 = (SyntaxTrivia)commonTrivia; //direct conversion Assert.Equal(correctSpan, vbTrivia2.Span); var vbTriviaList2 = (SyntaxTriviaList)commonTriviaList; var vbTrivia3 = vbTriviaList2.ElementAt(1); //from converted list Assert.Equal(correctSpan, vbTrivia3.Span); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void CSharpSyntax_VisualBasicKind() { var node = CSharp.SyntaxFactory.Identifier("a"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(node)); var token = CSharp.SyntaxFactory.Token(CSharp.SyntaxKind.IfKeyword); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(token)); var trivia = CSharp.SyntaxFactory.Comment("c"); Assert.Equal(VB.SyntaxKind.None, VisualBasic.VisualBasicExtensions.Kind(trivia)); } [Fact, WorkItem(824695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/824695")] public void VisualBasicSyntax_CSharpKind() { var node = VisualBasic.SyntaxFactory.Identifier("a"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(node)); var token = VisualBasic.SyntaxFactory.Token(VisualBasic.SyntaxKind.IfKeyword); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(token)); var trivia = VisualBasic.SyntaxFactory.CommentTrivia("c"); Assert.Equal(CSharp.SyntaxKind.None, CSharp.CSharpExtensions.Kind(trivia)); } [Fact] public void TestTrackNodes() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } [Fact] public void TestTrackNodesWithDuplicateIdAnnotations() { var expr = CSharp.SyntaxFactory.ParseExpression("a + b + c + d"); var exprB = expr.DescendantNodes().OfType<CSharp.Syntax.IdentifierNameSyntax>().First(n => n.Identifier.ToString() == "b"); var trackedExpr = expr.TrackNodes(exprB); var annotation = trackedExpr.GetAnnotatedNodes(SyntaxNodeExtensions.IdAnnotationKind).First() .GetAnnotations(SyntaxNodeExtensions.IdAnnotationKind).First(); // replace each expression with a parenthesized expression trackedExpr = trackedExpr.ReplaceNodes( nodes: trackedExpr.DescendantNodes().OfType<CSharp.Syntax.ExpressionSyntax>(), computeReplacementNode: (node, rewritten) => CSharp.SyntaxFactory.ParenthesizedExpression(rewritten).WithAdditionalAnnotations(annotation)); trackedExpr = trackedExpr.NormalizeWhitespace(); Assert.Equal("(((a) + (b)) + (c)) + (d)", trackedExpr.ToString()); var trackedB = trackedExpr.GetCurrentNodes(exprB).First(); Assert.Equal(CSharp.SyntaxKind.ParenthesizedExpression, CSharp.CSharpExtensions.Kind(trackedB.Parent)); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/MSBuildTest/Resources/NetCoreApp2AndTwoLibraries/Library1.csproj
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> </Project>
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFrameworks>netstandard2.0</TargetFrameworks> </PropertyGroup> </Project>
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Core/Source/ResultProvider/Expansion/AggregateExpansion.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.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class AggregateExpansion : Expansion { private readonly bool _containsFavorites; private readonly Expansion[] _expansions; internal static Expansion CreateExpansion(ArrayBuilder<Expansion> expansions) { switch (expansions.Count) { case 0: return null; case 1: return expansions[0]; default: return new AggregateExpansion(expansions.ToArray()); } } internal AggregateExpansion(Expansion[] expansions) { _expansions = expansions; if (expansions != null) { foreach (var expansion in expansions) { if (expansion.ContainsFavorites) { _containsFavorites = true; break; } } } } internal override bool ContainsFavorites => _containsFavorites; internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResult> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { foreach (var expansion in _expansions) { expansion.GetRows(resultProvider, rows, inspectionContext, parent, value, startIndex, count, visitAll, ref index); if (!visitAll && (index >= startIndex + count)) { return; } } } } }
// Licensed to the .NET Foundation under one or more 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.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class AggregateExpansion : Expansion { private readonly bool _containsFavorites; private readonly Expansion[] _expansions; internal static Expansion CreateExpansion(ArrayBuilder<Expansion> expansions) { switch (expansions.Count) { case 0: return null; case 1: return expansions[0]; default: return new AggregateExpansion(expansions.ToArray()); } } internal AggregateExpansion(Expansion[] expansions) { _expansions = expansions; if (expansions != null) { foreach (var expansion in expansions) { if (expansion.ContainsFavorites) { _containsFavorites = true; break; } } } } internal override bool ContainsFavorites => _containsFavorites; internal override void GetRows( ResultProvider resultProvider, ArrayBuilder<EvalResult> rows, DkmInspectionContext inspectionContext, EvalResultDataItem parent, DkmClrValue value, int startIndex, int count, bool visitAll, ref int index) { foreach (var expansion in _expansions) { expansion.GetRows(resultProvider, rows, inspectionContext, parent, value, startIndex, count, visitAll, ref index); if (!visitAll && (index >= startIndex + count)) { return; } } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.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.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { [UseExportProvider] public class ExtractMethodBase { protected static async Task ExpectExtractMethodToFailAsync(string codeWithMarker, bool dontPutOutOrRefOnStruct = true, string[] features = null) { ParseOptions parseOptions = null; if (features != null) { var featuresMapped = features.Select(x => new KeyValuePair<string, string>(x, string.Empty)); parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped); } using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.First(); var textSpan = testDocument.SelectedSpans.Single(); var treeAfterExtractMethod = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); } protected static async Task ExpectExtractMethodToFailAsync( string codeWithMarker, string expected, bool dontPutOutOrRefOnStruct = true, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } if (expected == "") Assert.True(false, subjectBuffer.CurrentSnapshot.GetText()); Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText()); } protected static async Task NotSupported_ExtractMethodAsync(string codeWithMarker) { using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker)) { Assert.NotNull(await Record.ExceptionAsync(async () => { var testDocument = workspace.Documents.Single(); var tree = await ExtractMethodAsync(workspace, testDocument); })); } } protected static async Task TestExtractMethodAsync( string codeWithMarker, string expected, bool temporaryFailing = false, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync( workspace, testDocument, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct, allowBestEffort: allowBestEffort); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } var actual = subjectBuffer.CurrentSnapshot.GetText(); if (temporaryFailing) { Assert.NotEqual(expected, actual); } else { if (expected != "") { AssertEx.EqualOrDiff(expected, actual); } else { // print out the entire diff to make adding tests simpler. Assert.Equal((object)expected, actual); } } } protected static async Task<SyntaxNode> ExtractMethodAsync( TestWorkspace workspace, TestHostDocument testDocument, bool succeed = true, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false) { var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var originalOptions = await document.GetOptionsAsync(); var options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options); var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None); if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion()) { return null; } Assert.True(selectedCode.ContainsValidContext); // extract method var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, localFunction: false); var result = await extractor.ExtractMethodAsync(CancellationToken.None); Assert.NotNull(result); Assert.Equal(succeed, result.Succeeded || result.SucceededWithSuggestion || (allowBestEffort && result.Status.HasBestEffort())); var doc = result.Document; return doc == null ? null : await doc.GetSyntaxRootAsync(); } protected static async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null, TextSpan? textSpanOverride = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var namedSpans = testDocument.AnnotatedSpans; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var options = await document.GetOptionsAsync(CancellationToken.None); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, textSpanOverride ?? namedSpans["b"].Single(), options); var result = await validator.GetValidSelectionAsync(CancellationToken.None); Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded()); if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion()) { Assert.Equal(namedSpans["r"].Single(), result.FinalSpan); } } protected static async Task IterateAllAsync(string code) { using var workspace = TestWorkspace.CreateCSharp(code, CodeAnalysis.CSharp.Test.Utilities.TestOptions.Regular); var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); Assert.NotNull(document); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var root = await document.GetSyntaxRootAsync(); var iterator = root.DescendantNodesAndSelf().Cast<SyntaxNode>(); var originalOptions = await document.GetOptionsAsync(); foreach (var node in iterator) { var validator = new CSharpSelectionValidator(semanticDocument, node.Span, originalOptions); var result = await validator.GetValidSelectionAsync(CancellationToken.None); // check the obvious case if (!(node is ExpressionSyntax) && !node.UnderValidContext()) { Assert.True(result.Status.FailedWithNoBestEffortSuggestion()); } } } } }
// Licensed to the .NET Foundation under one or more 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.CSharp; using Microsoft.CodeAnalysis.CSharp.ExtractMethod; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod { [UseExportProvider] public class ExtractMethodBase { protected static async Task ExpectExtractMethodToFailAsync(string codeWithMarker, bool dontPutOutOrRefOnStruct = true, string[] features = null) { ParseOptions parseOptions = null; if (features != null) { var featuresMapped = features.Select(x => new KeyValuePair<string, string>(x, string.Empty)); parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped); } using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.First(); var textSpan = testDocument.SelectedSpans.Single(); var treeAfterExtractMethod = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); } protected static async Task ExpectExtractMethodToFailAsync( string codeWithMarker, string expected, bool dontPutOutOrRefOnStruct = true, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } if (expected == "") Assert.True(false, subjectBuffer.CurrentSnapshot.GetText()); Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText()); } protected static async Task NotSupported_ExtractMethodAsync(string codeWithMarker) { using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker)) { Assert.NotNull(await Record.ExceptionAsync(async () => { var testDocument = workspace.Documents.Single(); var tree = await ExtractMethodAsync(workspace, testDocument); })); } } protected static async Task TestExtractMethodAsync( string codeWithMarker, string expected, bool temporaryFailing = false, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var subjectBuffer = testDocument.GetTextBuffer(); var tree = await ExtractMethodAsync( workspace, testDocument, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct, allowBestEffort: allowBestEffort); using (var edit = subjectBuffer.CreateEdit()) { edit.Replace(0, edit.Snapshot.Length, tree.ToFullString()); edit.Apply(); } var actual = subjectBuffer.CurrentSnapshot.GetText(); if (temporaryFailing) { Assert.NotEqual(expected, actual); } else { if (expected != "") { AssertEx.EqualOrDiff(expected, actual); } else { // print out the entire diff to make adding tests simpler. Assert.Equal((object)expected, actual); } } } protected static async Task<SyntaxNode> ExtractMethodAsync( TestWorkspace workspace, TestHostDocument testDocument, bool succeed = true, bool dontPutOutOrRefOnStruct = true, bool allowBestEffort = false) { var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var originalOptions = await document.GetOptionsAsync(); var options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options); var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None); if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion()) { return null; } Assert.True(selectedCode.ContainsValidContext); // extract method var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, localFunction: false); var result = await extractor.ExtractMethodAsync(CancellationToken.None); Assert.NotNull(result); Assert.Equal(succeed, result.Succeeded || result.SucceededWithSuggestion || (allowBestEffort && result.Status.HasBestEffort())); var doc = result.Document; return doc == null ? null : await doc.GetSyntaxRootAsync(); } protected static async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null, TextSpan? textSpanOverride = null) { using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions); var testDocument = workspace.Documents.Single(); var namedSpans = testDocument.AnnotatedSpans; var document = workspace.CurrentSolution.GetDocument(testDocument.Id); Assert.NotNull(document); var options = await document.GetOptionsAsync(CancellationToken.None); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var validator = new CSharpSelectionValidator(semanticDocument, textSpanOverride ?? namedSpans["b"].Single(), options); var result = await validator.GetValidSelectionAsync(CancellationToken.None); Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded()); if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion()) { Assert.Equal(namedSpans["r"].Single(), result.FinalSpan); } } protected static async Task IterateAllAsync(string code) { using var workspace = TestWorkspace.CreateCSharp(code, CodeAnalysis.CSharp.Test.Utilities.TestOptions.Regular); var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id); Assert.NotNull(document); var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None); var root = await document.GetSyntaxRootAsync(); var iterator = root.DescendantNodesAndSelf().Cast<SyntaxNode>(); var originalOptions = await document.GetOptionsAsync(); foreach (var node in iterator) { var validator = new CSharpSelectionValidator(semanticDocument, node.Span, originalOptions); var result = await validator.GetValidSelectionAsync(CancellationToken.None); // check the obvious case if (!(node is ExpressionSyntax) && !node.UnderValidContext()) { Assert.True(result.Status.FailedWithNoBestEffortSuggestion()); } } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/CodeFixes/xlf/CSharpCodeFixesResources.ru.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="ru" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Добавьте "this".</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Преобразовать "typeof" в "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Передача зафиксированных переменных в качестве аргументов</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Поместите двоеточие на следующей строке.</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Размещайте оператор на отдельной строке</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Удалить ненужные директивы using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Удалить пустую строку между скобками</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Удалить недостижимый код</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Предупреждение! Добавление параметров в объявление локальной функции может привести к недопустимому коду.</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="ru" original="../CSharpCodeFixesResources.resx"> <body> <trans-unit id="Add_this"> <source>Add 'this.'</source> <target state="translated">Добавьте "this".</target> <note /> </trans-unit> <trans-unit id="Convert_typeof_to_nameof"> <source>Convert 'typeof' to 'nameof'</source> <target state="translated">Преобразовать "typeof" в "nameof"</target> <note /> </trans-unit> <trans-unit id="Pass_in_captured_variables_as_arguments"> <source>Pass in captured variables as arguments</source> <target state="translated">Передача зафиксированных переменных в качестве аргументов</target> <note /> </trans-unit> <trans-unit id="Place_colon_on_following_line"> <source>Place colon on following line</source> <target state="translated">Поместите двоеточие на следующей строке.</target> <note /> </trans-unit> <trans-unit id="Place_statement_on_following_line"> <source>Place statement on following line</source> <target state="translated">Размещайте оператор на отдельной строке</target> <note /> </trans-unit> <trans-unit id="Remove_Unnecessary_Usings"> <source>Remove Unnecessary Usings</source> <target state="translated">Удалить ненужные директивы using</target> <note /> </trans-unit> <trans-unit id="Remove_blank_lines_between_braces"> <source>Remove blank line between braces</source> <target state="translated">Удалить пустую строку между скобками</target> <note /> </trans-unit> <trans-unit id="Remove_unreachable_code"> <source>Remove unreachable code</source> <target state="translated">Удалить недостижимый код</target> <note /> </trans-unit> <trans-unit id="Warning_colon_Adding_parameters_to_local_function_declaration_may_produce_invalid_code"> <source>Warning: Adding parameters to local function declaration may produce invalid code.</source> <target state="translated">Предупреждение! Добавление параметров в объявление локальной функции может привести к недопустимому коду.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.SymbolToProjectId.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.CompilerServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <inheritdoc cref="Solution.GetOriginatingProjectId"/> public ProjectId? GetOriginatingProjectId(ISymbol? symbol) { if (symbol == null) return null; var projectId = GetOriginatingProjectIdWorker(symbol); // Validate some invariants we think should hold. We want to know if this breaks, which indicates some part // of our system not working as we might expect. If they break, create NFWs so we can find out and // investigate. if (SymbolKey.IsBodyLevelSymbol(symbol)) { // If this is a method-body-level symbol, then we will have it's syntax tree. Since we already have a // mapping from syntax-trees to docs, so we can immediately map this back to it's originating project. // // Note: we don't do this for all source symbols, only method-body-level ones. That's because other // source symbols may be *retargetted*. So you can have the same symbol retargetted into multiple // projects, but which have the same syntax-tree (which is only in one project). We need to actually // check it's assembly symbol so that we get the actual project it is from (the original project, or the // retargetted project). var syntaxTree = symbol.Locations[0].SourceTree; Contract.ThrowIfNull(syntaxTree); var documentId = this.GetDocumentState(syntaxTree, projectId: null)?.Id; if (documentId == null) { try { throw new InvalidOperationException( $"We should always be able to map a body symbol back to a document:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } else if (documentId.ProjectId != projectId) { try { throw new InvalidOperationException( $"Syntax tree for a body symbol should map to the same project as the body symbol's assembly:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}\r\n{documentId.ProjectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } } return projectId; } private ProjectId? GetOriginatingProjectIdWorker(ISymbol symbol) { LazyInitialization.EnsureInitialized(ref _unrootedSymbolToProjectId, s_createTable); // Walk up the symbol so we can get to the containing namespace/assembly that will be used to map // back to a project. while (symbol != null) { var result = GetProjectIdDirectly(symbol, _unrootedSymbolToProjectId); if (result != null) return result; symbol = symbol.ContainingSymbol; } return null; } private ProjectId? GetProjectIdDirectly( ISymbol symbol, ConditionalWeakTable<ISymbol, ProjectId?> unrootedSymbolToProjectId) { if (symbol.IsKind(SymbolKind.Namespace, out INamespaceSymbol? ns)) { if (ns.ContainingCompilation != null) { // A namespace that spans a compilation. These don't belong to an assembly/module directly. // However, as we're looking for the project this corresponds to, we can look for the // source-module component (the first in the constituent namespaces) and then search using that. return GetOriginatingProjectId(ns.ConstituentNamespaces[0]); } } else if (symbol.IsKind(SymbolKind.Assembly) || symbol.IsKind(SymbolKind.NetModule) || symbol.IsKind(SymbolKind.DynamicType)) { if (!unrootedSymbolToProjectId.TryGetValue(symbol, out var projectId)) { // First, look through all the projects, and see if this symbol came from the primary assembly for // that project. (i.e. was a source symbol from that project, or was retargetted into that // project). If so, that's the originating project. // // If we don't find any primary results, then look through all the secondary assemblies (i.e. // references) for that project. This is the case for metadata symbols. A metadata symbol might be // found in many projects, so we just return the first result as that's just as good for finding the // metadata symbol as any other project. projectId = TryGetProjectId(symbol, primary: true) ?? TryGetProjectId(symbol, primary: false); // Have to lock as there's no atomic AddOrUpdate in netstandard2.0 and we could throw if two // threads tried to add the same item. #if !NETCOREAPP lock (unrootedSymbolToProjectId) { unrootedSymbolToProjectId.Remove(symbol); unrootedSymbolToProjectId.Add(symbol, projectId); } #else unrootedSymbolToProjectId.AddOrUpdate(symbol, projectId); #endif } return projectId; } else if (symbol.IsKind(SymbolKind.TypeParameter, out ITypeParameterSymbol? typeParameter) && typeParameter.TypeParameterKind == TypeParameterKind.Cref) { // Cref type parameters don't belong to any containing symbol. But we can map them to a doc/project // using the declaring syntax of the type parameter itself. var tree = typeParameter.Locations[0].SourceTree; var doc = this.GetDocumentState(tree, projectId: null); return doc?.Id.ProjectId; } return null; ProjectId? TryGetProjectId(ISymbol symbol, bool primary) { foreach (var (id, tracker) in _projectIdToTrackerMap) { if (tracker.ContainsAssemblyOrModuleOrDynamic(symbol, primary)) return id; } 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.Runtime.CompilerServices; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class SolutionState { /// <inheritdoc cref="Solution.GetOriginatingProjectId"/> public ProjectId? GetOriginatingProjectId(ISymbol? symbol) { if (symbol == null) return null; var projectId = GetOriginatingProjectIdWorker(symbol); // Validate some invariants we think should hold. We want to know if this breaks, which indicates some part // of our system not working as we might expect. If they break, create NFWs so we can find out and // investigate. if (SymbolKey.IsBodyLevelSymbol(symbol)) { // If this is a method-body-level symbol, then we will have it's syntax tree. Since we already have a // mapping from syntax-trees to docs, so we can immediately map this back to it's originating project. // // Note: we don't do this for all source symbols, only method-body-level ones. That's because other // source symbols may be *retargetted*. So you can have the same symbol retargetted into multiple // projects, but which have the same syntax-tree (which is only in one project). We need to actually // check it's assembly symbol so that we get the actual project it is from (the original project, or the // retargetted project). var syntaxTree = symbol.Locations[0].SourceTree; Contract.ThrowIfNull(syntaxTree); var documentId = this.GetDocumentState(syntaxTree, projectId: null)?.Id; if (documentId == null) { try { throw new InvalidOperationException( $"We should always be able to map a body symbol back to a document:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } else if (documentId.ProjectId != projectId) { try { throw new InvalidOperationException( $"Syntax tree for a body symbol should map to the same project as the body symbol's assembly:\r\n{symbol.Kind}\r\n{symbol.Name}\r\n{syntaxTree.FilePath}\r\n{projectId}\r\n{documentId.ProjectId}"); } catch (Exception ex) when (FatalError.ReportAndCatch(ex)) { } } } return projectId; } private ProjectId? GetOriginatingProjectIdWorker(ISymbol symbol) { LazyInitialization.EnsureInitialized(ref _unrootedSymbolToProjectId, s_createTable); // Walk up the symbol so we can get to the containing namespace/assembly that will be used to map // back to a project. while (symbol != null) { var result = GetProjectIdDirectly(symbol, _unrootedSymbolToProjectId); if (result != null) return result; symbol = symbol.ContainingSymbol; } return null; } private ProjectId? GetProjectIdDirectly( ISymbol symbol, ConditionalWeakTable<ISymbol, ProjectId?> unrootedSymbolToProjectId) { if (symbol.IsKind(SymbolKind.Namespace, out INamespaceSymbol? ns)) { if (ns.ContainingCompilation != null) { // A namespace that spans a compilation. These don't belong to an assembly/module directly. // However, as we're looking for the project this corresponds to, we can look for the // source-module component (the first in the constituent namespaces) and then search using that. return GetOriginatingProjectId(ns.ConstituentNamespaces[0]); } } else if (symbol.IsKind(SymbolKind.Assembly) || symbol.IsKind(SymbolKind.NetModule) || symbol.IsKind(SymbolKind.DynamicType)) { if (!unrootedSymbolToProjectId.TryGetValue(symbol, out var projectId)) { // First, look through all the projects, and see if this symbol came from the primary assembly for // that project. (i.e. was a source symbol from that project, or was retargetted into that // project). If so, that's the originating project. // // If we don't find any primary results, then look through all the secondary assemblies (i.e. // references) for that project. This is the case for metadata symbols. A metadata symbol might be // found in many projects, so we just return the first result as that's just as good for finding the // metadata symbol as any other project. projectId = TryGetProjectId(symbol, primary: true) ?? TryGetProjectId(symbol, primary: false); // Have to lock as there's no atomic AddOrUpdate in netstandard2.0 and we could throw if two // threads tried to add the same item. #if !NETCOREAPP lock (unrootedSymbolToProjectId) { unrootedSymbolToProjectId.Remove(symbol); unrootedSymbolToProjectId.Add(symbol, projectId); } #else unrootedSymbolToProjectId.AddOrUpdate(symbol, projectId); #endif } return projectId; } else if (symbol.IsKind(SymbolKind.TypeParameter, out ITypeParameterSymbol? typeParameter) && typeParameter.TypeParameterKind == TypeParameterKind.Cref) { // Cref type parameters don't belong to any containing symbol. But we can map them to a doc/project // using the declaring syntax of the type parameter itself. var tree = typeParameter.Locations[0].SourceTree; var doc = this.GetDocumentState(tree, projectId: null); return doc?.Id.ProjectId; } return null; ProjectId? TryGetProjectId(ISymbol symbol, bool primary) { foreach (var (id, tracker) in _projectIdToTrackerMap) { if (tracker.ContainsAssemblyOrModuleOrDynamic(symbol, primary)) return id; } return null; } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/Diagnostics/TestHostDiagnosticUpdateSource.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.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { internal class TestHostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateSource { private readonly Workspace _workspace; public TestHostDiagnosticUpdateSource(Workspace workspace) => _workspace = workspace; public override Workspace Workspace { get { return _workspace; } } public override int GetHashCode() => _workspace.GetHashCode(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { internal class TestHostDiagnosticUpdateSource : AbstractHostDiagnosticUpdateSource { private readonly Workspace _workspace; public TestHostDiagnosticUpdateSource(Workspace workspace) => _workspace = workspace; public override Workspace Workspace { get { return _workspace; } } public override int GetHashCode() => _workspace.GetHashCode(); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AbstractSymbolDescriptionBuilder.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial class AbstractSymbolDisplayService { protected abstract partial class AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.None, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, localOptions: SymbolDisplayLocalOptions.IncludeRef | SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral); private static readonly SymbolDisplayFormat s_descriptionStyle = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword); private static readonly SymbolDisplayFormat s_globalNamespaceStyle = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); private readonly SemanticModel _semanticModel; private readonly int _position; private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService; private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new(); private readonly Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> _documentationMap = new(); private readonly Func<ISymbol, string> _getNavigationHint; protected readonly Workspace Workspace; protected readonly CancellationToken CancellationToken; protected AbstractSymbolDescriptionBuilder( SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) { _anonymousTypeDisplayService = anonymousTypeDisplayService; Workspace = workspace; CancellationToken = cancellationToken; _semanticModel = semanticModel; _position = position; _getNavigationHint = GetNavigationHint; } protected abstract void AddExtensionPrefix(); protected abstract void AddAwaitablePrefix(); protected abstract void AddAwaitableExtensionPrefix(); protected abstract void AddDeprecatedPrefix(); protected abstract void AddEnumUnderlyingTypeSeparator(); protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol); protected abstract ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format); protected abstract string GetNavigationHint(ISymbol symbol); protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstantsAndModifiers { get; } protected SemanticModel GetSemanticModel(SyntaxTree tree) { if (_semanticModel.SyntaxTree == tree) { return _semanticModel; } var model = _semanticModel.GetOriginalSemanticModel(); if (model.Compilation.ContainsSyntaxTree(tree)) { return model.Compilation.GetSemanticModel(tree); } // it is from one of its p2p references foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations()) { // find the reference that contains the given tree if (referencedCompilation.ContainsSyntaxTree(tree)) { return referencedCompilation.GetSemanticModel(tree); } } // the tree, a source symbol is defined in, doesn't exist in universe // how this can happen? Debug.Assert(false, "How?"); return null; } protected Compilation GetCompilation() => _semanticModel.Compilation; private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols) { var firstSymbol = symbols[0]; await AddDescriptionPartAsync(firstSymbol).ConfigureAwait(false); AddOverloadCountPart(symbols); FixAllAnonymousTypes(firstSymbol); AddExceptions(firstSymbol); AddCaptures(firstSymbol); AddDocumentationContent(firstSymbol); } private void AddDocumentationContent(ISymbol symbol) { var formatter = Workspace.Services.GetLanguageServices(_semanticModel.Language).GetRequiredService<IDocumentationCommentFormattingService>(); if (symbol is IParameterSymbol or ITypeParameterSymbol) { // Can just defer to the standard helper here. We only want to get the summary portion for just the // param/type-param and we have no need for remarks/returns/value. _documentationMap.Add( SymbolDescriptionGroups.Documentation, symbol.GetDocumentationParts(_semanticModel, _position, formatter, CancellationToken)); return; } if (symbol is IAliasSymbol alias) symbol = alias.Target; var original = symbol.OriginalDefinition; var format = ISymbolExtensions2.CrefFormat; var compilation = _semanticModel.Compilation; // Grab the doc comment once as computing it for each portion we're concatenating can be expensive for // lsif (which does this for every symbol in an entire solution). var documentationComment = original is IMethodSymbol method ? ISymbolExtensions2.GetMethodDocumentation(method, compilation, CancellationToken) : original.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken); _documentationMap.Add( SymbolDescriptionGroups.Documentation, formatter.Format(documentationComment.SummaryText, symbol, _semanticModel, _position, format, CancellationToken)); _documentationMap.Add( SymbolDescriptionGroups.RemarksDocumentation, formatter.Format(documentationComment.RemarksText, symbol, _semanticModel, _position, format, CancellationToken)); AddReturnsDocumentationParts(symbol, formatter); AddValueDocumentationParts(symbol, formatter); return; void AddReturnsDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter) { var parts = formatter.Format(documentationComment.ReturnsText, symbol, _semanticModel, _position, format, CancellationToken); if (!parts.IsDefaultOrEmpty) { using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder); builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Returns_colon)); builder.AddRange(LineBreak().ToTaggedText()); builder.Add(new TaggedText(TextTags.ContainerStart, " ")); builder.AddRange(parts); builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty)); _documentationMap.Add(SymbolDescriptionGroups.ReturnsDocumentation, builder.ToImmutable()); } } void AddValueDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter) { var parts = formatter.Format(documentationComment.ValueText, symbol, _semanticModel, _position, format, CancellationToken); if (!parts.IsDefaultOrEmpty) { using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder); builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Value_colon)); builder.AddRange(LineBreak().ToTaggedText()); builder.Add(new TaggedText(TextTags.ContainerStart, " ")); builder.AddRange(parts); builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty)); _documentationMap.Add(SymbolDescriptionGroups.ValueDocumentation, builder.ToImmutable()); } } } private void AddExceptions(ISymbol symbol) { var exceptionTypes = symbol.GetDocumentationComment(GetCompilation(), expandIncludes: true, expandInheritdoc: true).ExceptionTypes; if (exceptionTypes.Any()) { var parts = new List<SymbolDisplayPart>(); parts.AddLineBreak(); parts.AddText(WorkspacesResources.Exceptions_colon); foreach (var exceptionString in exceptionTypes) { parts.AddRange(LineBreak()); parts.AddRange(Space(count: 2)); parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel)); } AddToGroup(SymbolDescriptionGroups.Exceptions, parts); } } /// <summary> /// If the symbol is a local or anonymous function (lambda or delegate), adds the variables captured /// by that local or anonymous function to the "Captures" group. /// </summary> /// <param name="symbol"></param> protected abstract void AddCaptures(ISymbol symbol); /// <summary> /// Given the body of a local or an anonymous function (lambda or delegate), add the variables captured /// by that local or anonymous function to the "Captures" group. /// </summary> protected void AddCaptures(SyntaxNode syntax) { var semanticModel = GetSemanticModel(syntax.SyntaxTree); if (semanticModel.IsSpeculativeSemanticModel) { // The region analysis APIs used below are not meaningful/applicable in the context of speculation (because they are designed // to ask questions about an expression if it were in a certain *scope* of code, not if it were inserted at a certain *position*). // // But in the context of symbol completion, we do prepare a description for the symbol while speculating. Only the "main description" // section of that description will be displayed. We still add a "captures" section, just in case. AddToGroup(SymbolDescriptionGroups.Captures, LineBreak()); AddToGroup(SymbolDescriptionGroups.Captures, PlainText($"{WorkspacesResources.Variables_captured_colon} ?")); return; } var analysis = semanticModel.AnalyzeDataFlow(syntax); var captures = analysis.CapturedInside.Except(analysis.VariablesDeclared).ToImmutableArray(); if (!captures.IsEmpty) { var parts = new List<SymbolDisplayPart>(); parts.AddLineBreak(); parts.AddText(WorkspacesResources.Variables_captured_colon); var first = true; foreach (var captured in captures) { if (!first) { parts.AddRange(Punctuation(",")); } parts.AddRange(Space(count: 1)); parts.AddRange(ToMinimalDisplayParts(captured, s_formatForCaptures)); first = false; } AddToGroup(SymbolDescriptionGroups.Captures, parts); } } private static readonly SymbolDisplayFormat s_formatForCaptures = SymbolDisplayFormat.MinimallyQualifiedFormat .RemoveLocalOptions(SymbolDisplayLocalOptions.IncludeType) .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeType); public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync( ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return BuildDescription(groups); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return BuildDescriptionSections(); } private async Task AddDescriptionPartAsync(ISymbol symbol) { if (symbol.IsObsolete()) { AddDeprecatedPrefix(); } if (symbol is IDiscardSymbol discard) { AddDescriptionForDiscard(discard); } else if (symbol is IDynamicTypeSymbol) { AddDescriptionForDynamicType(); } else if (symbol is IFieldSymbol field) { await AddDescriptionForFieldAsync(field).ConfigureAwait(false); } else if (symbol is ILocalSymbol local) { await AddDescriptionForLocalAsync(local).ConfigureAwait(false); } else if (symbol is IMethodSymbol method) { AddDescriptionForMethod(method); } else if (symbol is ILabelSymbol label) { AddDescriptionForLabel(label); } else if (symbol is INamedTypeSymbol namedType) { if (namedType.IsTupleType) { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.ToDisplayParts(s_descriptionStyle)); } else { AddDescriptionForNamedType(namedType); } } else if (symbol is INamespaceSymbol namespaceSymbol) { AddDescriptionForNamespace(namespaceSymbol); } else if (symbol is IParameterSymbol parameter) { await AddDescriptionForParameterAsync(parameter).ConfigureAwait(false); } else if (symbol is IPropertySymbol property) { AddDescriptionForProperty(property); } else if (symbol is IRangeVariableSymbol rangeVariable) { AddDescriptionForRangeVariable(rangeVariable); } else if (symbol is ITypeParameterSymbol typeParameter) { AddDescriptionForTypeParameter(typeParameter); } else if (symbol is IAliasSymbol alias) { await AddDescriptionPartAsync(alias.Target).ConfigureAwait(false); } else { AddDescriptionForArbitrarySymbol(symbol); } } private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups) { var finalParts = new List<SymbolDisplayPart>(); var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2); foreach (var group in orderedGroups) { if ((groups & group) == 0) { continue; } if (!finalParts.IsEmpty()) { var newLines = GetPrecedingNewLineCount(group); finalParts.AddRange(LineBreak(newLines)); } var parts = _groupMap[group]; finalParts.AddRange(parts); } return finalParts.AsImmutable(); } private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group) { switch (group) { case SymbolDescriptionGroups.MainDescription: // these parts are continuations of whatever text came before them return 0; case SymbolDescriptionGroups.Documentation: case SymbolDescriptionGroups.RemarksDocumentation: case SymbolDescriptionGroups.ReturnsDocumentation: case SymbolDescriptionGroups.ValueDocumentation: return 1; case SymbolDescriptionGroups.AnonymousTypes: return 0; case SymbolDescriptionGroups.Exceptions: case SymbolDescriptionGroups.TypeParameterMap: case SymbolDescriptionGroups.Captures: // Everything else is in a group on its own return 2; default: throw ExceptionUtilities.UnexpectedValue(group); } } private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections() { var includeNavigationHints = this.Workspace.Options.GetOption(QuickInfoOptions.IncludeNavigationHintsInQuickInfo); // Merge the two maps into one final result. var result = new Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(_documentationMap); foreach (var (group, parts) in _groupMap) { var taggedText = parts.ToTaggedText(_getNavigationHint, includeNavigationHints); if (group == SymbolDescriptionGroups.MainDescription) { // Mark the main description as a code block. taggedText = taggedText .Insert(0, new TaggedText(TextTags.CodeBlockStart, string.Empty)) .Add(new TaggedText(TextTags.CodeBlockEnd, string.Empty)); } result[group] = taggedText; } return result; } private void AddDescriptionForDynamicType() { AddToGroup(SymbolDescriptionGroups.MainDescription, Keyword("dynamic")); AddToGroup(SymbolDescriptionGroups.Documentation, PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } private void AddDescriptionForNamedType(INamedTypeSymbol symbol) { if (symbol.IsAwaitableNonDynamic(_semanticModel, _position)) { AddAwaitablePrefix(); } AddSymbolDescription(symbol); if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol)) { var allTypeParameters = symbol.GetAllTypeParameters().ToList(); var allTypeArguments = symbol.GetAllTypeArguments().ToList(); AddTypeParameterMapPart(allTypeParameters, allTypeArguments); } if (symbol.IsEnumType() && symbol.EnumUnderlyingType.SpecialType != SpecialType.System_Int32) { AddEnumUnderlyingTypeSeparator(); var underlyingTypeDisplayParts = symbol.EnumUnderlyingType.ToDisplayParts(s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)); AddToGroup(SymbolDescriptionGroups.MainDescription, underlyingTypeDisplayParts); } } private void AddSymbolDescription(INamedTypeSymbol symbol) { if (symbol.TypeKind == TypeKind.Delegate) { var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.OriginalDefinition.ToDisplayParts(style)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.OriginalDefinition.ToDisplayParts(s_descriptionStyle)); } } private static bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol) { var typeArguments = symbol.GetAllTypeArguments().ToList(); var typeParameters = symbol.GetAllTypeParameters().ToList(); for (var i = 0; i < typeArguments.Count; i++) { var typeArgument = typeArguments[i]; var typeParameter = typeParameters[i]; if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name) { continue; } return false; } return true; } private void AddDescriptionForNamespace(INamespaceSymbol symbol) { if (symbol.IsGlobalNamespace) { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.ToDisplayParts(s_globalNamespaceStyle)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.ToDisplayParts(s_descriptionStyle)); } } private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol) { var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false); // Don't bother showing disambiguating text for enum members. The icon displayed // on Quick Info should be enough. if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum) { AddToGroup(SymbolDescriptionGroups.MainDescription, parts); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.constant) : Description(FeaturesResources.field), parts); } } private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (!initializerParts.IsDefaultOrEmpty) { using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts); parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat)); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts.ToImmutable(); } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstantsAndModifiers); } private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol) { var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.local_constant) : Description(FeaturesResources.local_variable), parts); } private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts); parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat)); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts.ToImmutable(); } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private void AddDescriptionForLabel(ILabelSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.label), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.range_variable), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForMethod(IMethodSymbol method) { // TODO : show duplicated member case var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position); var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension; if (awaitable && extension) { AddAwaitableExtensionPrefix(); } else if (awaitable) { AddAwaitablePrefix(); } else if (extension) { AddExtensionPrefix(); } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat)); } private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol) { if (symbol.IsOptional) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (!initializerParts.IsDefaultOrEmpty) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.parameter), parts); return; } } AddToGroup(SymbolDescriptionGroups.MainDescription, Description(symbol.IsDiscard ? FeaturesResources.discard : FeaturesResources.parameter), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } private void AddDescriptionForDiscard(IDiscardSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.discard), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } protected void AddDescriptionForProperty(IPropertySymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); } private void AddDescriptionForArbitrarySymbol(ISymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol)); } private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol) { Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref); AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol), Space(), PlainText(FeaturesResources.in_), Space(), ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat)); } private void AddOverloadCountPart( ImmutableArray<ISymbol> symbolGroup) { var count = GetOverloadCount(symbolGroup); if (count >= 1) { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation("("), Punctuation("+"), Space(), PlainText(count.ToString()), Space(), count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_), Punctuation(")")); } } private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup) { return symbolGroup.Select(s => s.OriginalDefinition) .Where(s => !s.Equals(symbolGroup.First().OriginalDefinition)) .Where(s => s is IMethodSymbol || s.IsIndexer()) .Count(); } protected void AddTypeParameterMapPart( List<ITypeParameterSymbol> typeParameters, List<ITypeSymbol> typeArguments) { var parts = new List<SymbolDisplayPart>(); var count = typeParameters.Count; for (var i = 0; i < count; i++) { parts.AddRange(TypeParameterName(typeParameters[i].Name)); parts.AddRange(Space()); parts.AddRange(PlainText(FeaturesResources.is_)); parts.AddRange(Space()); parts.AddRange(ToMinimalDisplayParts(typeArguments[i])); if (i < count - 1) { parts.AddRange(LineBreak()); } } AddToGroup(SymbolDescriptionGroups.TypeParameterMap, parts); } protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray) => AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray); protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray) { var partsList = partsArray.Flatten().ToList(); if (partsList.Count > 0) { if (!_groupMap.TryGetValue(group, out var existingParts)) { existingParts = new List<SymbolDisplayPart>(); _groupMap.Add(group, existingParts); } existingParts.AddRange(partsList); } } private static IEnumerable<SymbolDisplayPart> Description(string description) { return Punctuation("(") .Concat(PlainText(description)) .Concat(Punctuation(")")) .Concat(Space()); } protected static IEnumerable<SymbolDisplayPart> Keyword(string text) => Part(SymbolDisplayPartKind.Keyword, text); protected static IEnumerable<SymbolDisplayPart> LineBreak(int count = 1) { for (var i = 0; i < count; i++) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n"); } } protected static IEnumerable<SymbolDisplayPart> PlainText(string text) => Part(SymbolDisplayPartKind.Text, text); protected static IEnumerable<SymbolDisplayPart> Punctuation(string text) => Part(SymbolDisplayPartKind.Punctuation, text); protected static IEnumerable<SymbolDisplayPart> Space(int count = 1) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count)); } protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { format ??= MinimallyQualifiedFormat; return ToMinimalDisplayParts(symbol, _semanticModel, _position, format); } private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text) { yield return new SymbolDisplayPart(kind, symbol, text); } private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text) => Part(kind, null, text); private static IEnumerable<SymbolDisplayPart> TypeParameterName(string text) => Part(SymbolDisplayPartKind.TypeParameterName, text); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial class AbstractSymbolDisplayService { protected abstract partial class AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.None, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, localOptions: SymbolDisplayLocalOptions.IncludeRef | SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral); private static readonly SymbolDisplayFormat s_descriptionStyle = new( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword); private static readonly SymbolDisplayFormat s_globalNamespaceStyle = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); private readonly SemanticModel _semanticModel; private readonly int _position; private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService; private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new(); private readonly Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> _documentationMap = new(); private readonly Func<ISymbol, string> _getNavigationHint; protected readonly Workspace Workspace; protected readonly CancellationToken CancellationToken; protected AbstractSymbolDescriptionBuilder( SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) { _anonymousTypeDisplayService = anonymousTypeDisplayService; Workspace = workspace; CancellationToken = cancellationToken; _semanticModel = semanticModel; _position = position; _getNavigationHint = GetNavigationHint; } protected abstract void AddExtensionPrefix(); protected abstract void AddAwaitablePrefix(); protected abstract void AddAwaitableExtensionPrefix(); protected abstract void AddDeprecatedPrefix(); protected abstract void AddEnumUnderlyingTypeSeparator(); protected abstract Task<ImmutableArray<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol); protected abstract ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SemanticModel semanticModel, int position, SymbolDisplayFormat format); protected abstract string GetNavigationHint(ISymbol symbol); protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstantsAndModifiers { get; } protected SemanticModel GetSemanticModel(SyntaxTree tree) { if (_semanticModel.SyntaxTree == tree) { return _semanticModel; } var model = _semanticModel.GetOriginalSemanticModel(); if (model.Compilation.ContainsSyntaxTree(tree)) { return model.Compilation.GetSemanticModel(tree); } // it is from one of its p2p references foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations()) { // find the reference that contains the given tree if (referencedCompilation.ContainsSyntaxTree(tree)) { return referencedCompilation.GetSemanticModel(tree); } } // the tree, a source symbol is defined in, doesn't exist in universe // how this can happen? Debug.Assert(false, "How?"); return null; } protected Compilation GetCompilation() => _semanticModel.Compilation; private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols) { var firstSymbol = symbols[0]; await AddDescriptionPartAsync(firstSymbol).ConfigureAwait(false); AddOverloadCountPart(symbols); FixAllAnonymousTypes(firstSymbol); AddExceptions(firstSymbol); AddCaptures(firstSymbol); AddDocumentationContent(firstSymbol); } private void AddDocumentationContent(ISymbol symbol) { var formatter = Workspace.Services.GetLanguageServices(_semanticModel.Language).GetRequiredService<IDocumentationCommentFormattingService>(); if (symbol is IParameterSymbol or ITypeParameterSymbol) { // Can just defer to the standard helper here. We only want to get the summary portion for just the // param/type-param and we have no need for remarks/returns/value. _documentationMap.Add( SymbolDescriptionGroups.Documentation, symbol.GetDocumentationParts(_semanticModel, _position, formatter, CancellationToken)); return; } if (symbol is IAliasSymbol alias) symbol = alias.Target; var original = symbol.OriginalDefinition; var format = ISymbolExtensions2.CrefFormat; var compilation = _semanticModel.Compilation; // Grab the doc comment once as computing it for each portion we're concatenating can be expensive for // lsif (which does this for every symbol in an entire solution). var documentationComment = original is IMethodSymbol method ? ISymbolExtensions2.GetMethodDocumentation(method, compilation, CancellationToken) : original.GetDocumentationComment(compilation, expandIncludes: true, expandInheritdoc: true, cancellationToken: CancellationToken); _documentationMap.Add( SymbolDescriptionGroups.Documentation, formatter.Format(documentationComment.SummaryText, symbol, _semanticModel, _position, format, CancellationToken)); _documentationMap.Add( SymbolDescriptionGroups.RemarksDocumentation, formatter.Format(documentationComment.RemarksText, symbol, _semanticModel, _position, format, CancellationToken)); AddReturnsDocumentationParts(symbol, formatter); AddValueDocumentationParts(symbol, formatter); return; void AddReturnsDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter) { var parts = formatter.Format(documentationComment.ReturnsText, symbol, _semanticModel, _position, format, CancellationToken); if (!parts.IsDefaultOrEmpty) { using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder); builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Returns_colon)); builder.AddRange(LineBreak().ToTaggedText()); builder.Add(new TaggedText(TextTags.ContainerStart, " ")); builder.AddRange(parts); builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty)); _documentationMap.Add(SymbolDescriptionGroups.ReturnsDocumentation, builder.ToImmutable()); } } void AddValueDocumentationParts(ISymbol symbol, IDocumentationCommentFormattingService formatter) { var parts = formatter.Format(documentationComment.ValueText, symbol, _semanticModel, _position, format, CancellationToken); if (!parts.IsDefaultOrEmpty) { using var _ = ArrayBuilder<TaggedText>.GetInstance(out var builder); builder.Add(new TaggedText(TextTags.Text, FeaturesResources.Value_colon)); builder.AddRange(LineBreak().ToTaggedText()); builder.Add(new TaggedText(TextTags.ContainerStart, " ")); builder.AddRange(parts); builder.Add(new TaggedText(TextTags.ContainerEnd, string.Empty)); _documentationMap.Add(SymbolDescriptionGroups.ValueDocumentation, builder.ToImmutable()); } } } private void AddExceptions(ISymbol symbol) { var exceptionTypes = symbol.GetDocumentationComment(GetCompilation(), expandIncludes: true, expandInheritdoc: true).ExceptionTypes; if (exceptionTypes.Any()) { var parts = new List<SymbolDisplayPart>(); parts.AddLineBreak(); parts.AddText(WorkspacesResources.Exceptions_colon); foreach (var exceptionString in exceptionTypes) { parts.AddRange(LineBreak()); parts.AddRange(Space(count: 2)); parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel)); } AddToGroup(SymbolDescriptionGroups.Exceptions, parts); } } /// <summary> /// If the symbol is a local or anonymous function (lambda or delegate), adds the variables captured /// by that local or anonymous function to the "Captures" group. /// </summary> /// <param name="symbol"></param> protected abstract void AddCaptures(ISymbol symbol); /// <summary> /// Given the body of a local or an anonymous function (lambda or delegate), add the variables captured /// by that local or anonymous function to the "Captures" group. /// </summary> protected void AddCaptures(SyntaxNode syntax) { var semanticModel = GetSemanticModel(syntax.SyntaxTree); if (semanticModel.IsSpeculativeSemanticModel) { // The region analysis APIs used below are not meaningful/applicable in the context of speculation (because they are designed // to ask questions about an expression if it were in a certain *scope* of code, not if it were inserted at a certain *position*). // // But in the context of symbol completion, we do prepare a description for the symbol while speculating. Only the "main description" // section of that description will be displayed. We still add a "captures" section, just in case. AddToGroup(SymbolDescriptionGroups.Captures, LineBreak()); AddToGroup(SymbolDescriptionGroups.Captures, PlainText($"{WorkspacesResources.Variables_captured_colon} ?")); return; } var analysis = semanticModel.AnalyzeDataFlow(syntax); var captures = analysis.CapturedInside.Except(analysis.VariablesDeclared).ToImmutableArray(); if (!captures.IsEmpty) { var parts = new List<SymbolDisplayPart>(); parts.AddLineBreak(); parts.AddText(WorkspacesResources.Variables_captured_colon); var first = true; foreach (var captured in captures) { if (!first) { parts.AddRange(Punctuation(",")); } parts.AddRange(Space(count: 1)); parts.AddRange(ToMinimalDisplayParts(captured, s_formatForCaptures)); first = false; } AddToGroup(SymbolDescriptionGroups.Captures, parts); } } private static readonly SymbolDisplayFormat s_formatForCaptures = SymbolDisplayFormat.MinimallyQualifiedFormat .RemoveLocalOptions(SymbolDisplayLocalOptions.IncludeType) .RemoveParameterOptions(SymbolDisplayParameterOptions.IncludeType); public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync( ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return BuildDescription(groups); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return BuildDescriptionSections(); } private async Task AddDescriptionPartAsync(ISymbol symbol) { if (symbol.IsObsolete()) { AddDeprecatedPrefix(); } if (symbol is IDiscardSymbol discard) { AddDescriptionForDiscard(discard); } else if (symbol is IDynamicTypeSymbol) { AddDescriptionForDynamicType(); } else if (symbol is IFieldSymbol field) { await AddDescriptionForFieldAsync(field).ConfigureAwait(false); } else if (symbol is ILocalSymbol local) { await AddDescriptionForLocalAsync(local).ConfigureAwait(false); } else if (symbol is IMethodSymbol method) { AddDescriptionForMethod(method); } else if (symbol is ILabelSymbol label) { AddDescriptionForLabel(label); } else if (symbol is INamedTypeSymbol namedType) { if (namedType.IsTupleType) { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.ToDisplayParts(s_descriptionStyle)); } else { AddDescriptionForNamedType(namedType); } } else if (symbol is INamespaceSymbol namespaceSymbol) { AddDescriptionForNamespace(namespaceSymbol); } else if (symbol is IParameterSymbol parameter) { await AddDescriptionForParameterAsync(parameter).ConfigureAwait(false); } else if (symbol is IPropertySymbol property) { AddDescriptionForProperty(property); } else if (symbol is IRangeVariableSymbol rangeVariable) { AddDescriptionForRangeVariable(rangeVariable); } else if (symbol is ITypeParameterSymbol typeParameter) { AddDescriptionForTypeParameter(typeParameter); } else if (symbol is IAliasSymbol alias) { await AddDescriptionPartAsync(alias.Target).ConfigureAwait(false); } else { AddDescriptionForArbitrarySymbol(symbol); } } private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups) { var finalParts = new List<SymbolDisplayPart>(); var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2); foreach (var group in orderedGroups) { if ((groups & group) == 0) { continue; } if (!finalParts.IsEmpty()) { var newLines = GetPrecedingNewLineCount(group); finalParts.AddRange(LineBreak(newLines)); } var parts = _groupMap[group]; finalParts.AddRange(parts); } return finalParts.AsImmutable(); } private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group) { switch (group) { case SymbolDescriptionGroups.MainDescription: // these parts are continuations of whatever text came before them return 0; case SymbolDescriptionGroups.Documentation: case SymbolDescriptionGroups.RemarksDocumentation: case SymbolDescriptionGroups.ReturnsDocumentation: case SymbolDescriptionGroups.ValueDocumentation: return 1; case SymbolDescriptionGroups.AnonymousTypes: return 0; case SymbolDescriptionGroups.Exceptions: case SymbolDescriptionGroups.TypeParameterMap: case SymbolDescriptionGroups.Captures: // Everything else is in a group on its own return 2; default: throw ExceptionUtilities.UnexpectedValue(group); } } private IDictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>> BuildDescriptionSections() { var includeNavigationHints = this.Workspace.Options.GetOption(QuickInfoOptions.IncludeNavigationHintsInQuickInfo); // Merge the two maps into one final result. var result = new Dictionary<SymbolDescriptionGroups, ImmutableArray<TaggedText>>(_documentationMap); foreach (var (group, parts) in _groupMap) { var taggedText = parts.ToTaggedText(_getNavigationHint, includeNavigationHints); if (group == SymbolDescriptionGroups.MainDescription) { // Mark the main description as a code block. taggedText = taggedText .Insert(0, new TaggedText(TextTags.CodeBlockStart, string.Empty)) .Add(new TaggedText(TextTags.CodeBlockEnd, string.Empty)); } result[group] = taggedText; } return result; } private void AddDescriptionForDynamicType() { AddToGroup(SymbolDescriptionGroups.MainDescription, Keyword("dynamic")); AddToGroup(SymbolDescriptionGroups.Documentation, PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime)); } private void AddDescriptionForNamedType(INamedTypeSymbol symbol) { if (symbol.IsAwaitableNonDynamic(_semanticModel, _position)) { AddAwaitablePrefix(); } AddSymbolDescription(symbol); if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol)) { var allTypeParameters = symbol.GetAllTypeParameters().ToList(); var allTypeArguments = symbol.GetAllTypeArguments().ToList(); AddTypeParameterMapPart(allTypeParameters, allTypeArguments); } if (symbol.IsEnumType() && symbol.EnumUnderlyingType.SpecialType != SpecialType.System_Int32) { AddEnumUnderlyingTypeSeparator(); var underlyingTypeDisplayParts = symbol.EnumUnderlyingType.ToDisplayParts(s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes)); AddToGroup(SymbolDescriptionGroups.MainDescription, underlyingTypeDisplayParts); } } private void AddSymbolDescription(INamedTypeSymbol symbol) { if (symbol.TypeKind == TypeKind.Delegate) { var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.OriginalDefinition.ToDisplayParts(style)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.OriginalDefinition.ToDisplayParts(s_descriptionStyle)); } } private static bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol) { var typeArguments = symbol.GetAllTypeArguments().ToList(); var typeParameters = symbol.GetAllTypeParameters().ToList(); for (var i = 0; i < typeArguments.Count; i++) { var typeArgument = typeArguments[i]; var typeParameter = typeParameters[i]; if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name) { continue; } return false; } return true; } private void AddDescriptionForNamespace(INamespaceSymbol symbol) { if (symbol.IsGlobalNamespace) { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.ToDisplayParts(s_globalNamespaceStyle)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.ToDisplayParts(s_descriptionStyle)); } } private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol) { var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false); // Don't bother showing disambiguating text for enum members. The icon displayed // on Quick Info should be enough. if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum) { AddToGroup(SymbolDescriptionGroups.MainDescription, parts); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.constant) : Description(FeaturesResources.field), parts); } } private async Task<ImmutableArray<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (!initializerParts.IsDefaultOrEmpty) { using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts); parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat)); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts.ToImmutable(); } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstantsAndModifiers); } private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol) { var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.local_constant) : Description(FeaturesResources.local_variable), parts); } private async Task<ImmutableArray<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { using var _ = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var parts); parts.AddRange(ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat)); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts.ToImmutable(); } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private void AddDescriptionForLabel(ILabelSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.label), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.range_variable), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForMethod(IMethodSymbol method) { // TODO : show duplicated member case var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position); var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension; if (awaitable && extension) { AddAwaitableExtensionPrefix(); } else if (awaitable) { AddAwaitablePrefix(); } else if (extension) { AddExtensionPrefix(); } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat)); } private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol) { if (symbol.IsOptional) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (!initializerParts.IsDefaultOrEmpty) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.parameter), parts); return; } } AddToGroup(SymbolDescriptionGroups.MainDescription, Description(symbol.IsDiscard ? FeaturesResources.discard : FeaturesResources.parameter), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } private void AddDescriptionForDiscard(IDiscardSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.discard), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } protected void AddDescriptionForProperty(IPropertySymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); } private void AddDescriptionForArbitrarySymbol(ISymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol)); } private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol) { Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref); AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol), Space(), PlainText(FeaturesResources.in_), Space(), ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat)); } private void AddOverloadCountPart( ImmutableArray<ISymbol> symbolGroup) { var count = GetOverloadCount(symbolGroup); if (count >= 1) { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation("("), Punctuation("+"), Space(), PlainText(count.ToString()), Space(), count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_), Punctuation(")")); } } private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup) { return symbolGroup.Select(s => s.OriginalDefinition) .Where(s => !s.Equals(symbolGroup.First().OriginalDefinition)) .Where(s => s is IMethodSymbol || s.IsIndexer()) .Count(); } protected void AddTypeParameterMapPart( List<ITypeParameterSymbol> typeParameters, List<ITypeSymbol> typeArguments) { var parts = new List<SymbolDisplayPart>(); var count = typeParameters.Count; for (var i = 0; i < count; i++) { parts.AddRange(TypeParameterName(typeParameters[i].Name)); parts.AddRange(Space()); parts.AddRange(PlainText(FeaturesResources.is_)); parts.AddRange(Space()); parts.AddRange(ToMinimalDisplayParts(typeArguments[i])); if (i < count - 1) { parts.AddRange(LineBreak()); } } AddToGroup(SymbolDescriptionGroups.TypeParameterMap, parts); } protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray) => AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray); protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray) { var partsList = partsArray.Flatten().ToList(); if (partsList.Count > 0) { if (!_groupMap.TryGetValue(group, out var existingParts)) { existingParts = new List<SymbolDisplayPart>(); _groupMap.Add(group, existingParts); } existingParts.AddRange(partsList); } } private static IEnumerable<SymbolDisplayPart> Description(string description) { return Punctuation("(") .Concat(PlainText(description)) .Concat(Punctuation(")")) .Concat(Space()); } protected static IEnumerable<SymbolDisplayPart> Keyword(string text) => Part(SymbolDisplayPartKind.Keyword, text); protected static IEnumerable<SymbolDisplayPart> LineBreak(int count = 1) { for (var i = 0; i < count; i++) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n"); } } protected static IEnumerable<SymbolDisplayPart> PlainText(string text) => Part(SymbolDisplayPartKind.Text, text); protected static IEnumerable<SymbolDisplayPart> Punctuation(string text) => Part(SymbolDisplayPartKind.Punctuation, text); protected static IEnumerable<SymbolDisplayPart> Space(int count = 1) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count)); } protected ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { format ??= MinimallyQualifiedFormat; return ToMinimalDisplayParts(symbol, _semanticModel, _position, format); } private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text) { yield return new SymbolDisplayPart(kind, symbol, text); } private static IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text) => Part(kind, null, text); private static IEnumerable<SymbolDisplayPart> TypeParameterName(string text) => Part(SymbolDisplayPartKind.TypeParameterName, text); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/MSBuildTest/Resources/ProjectFiles/CSharp/WithLink.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>TRACE;DEBUG</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>false</AllowUnsafeBlocks> <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> <LangVersion>3</LangVersion> <DocumentationFile>bin\Debug\CSharpProject.XML</DocumentationFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup> <StartupObject>CSharpProject.CSharpClass</StartupObject> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="..\OtherStuff\Foo.cs"> <Link>Blah\Foo.cs</Link> </Compile> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition="'$(Configuration)' == ''">Debug</Configuration> <Platform Condition="'$(Platform)' == ''">AnyCPU</Platform> <PlatformTarget>AnyCPU</PlatformTarget> <ProductVersion>8.0.30703</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{686DD036-86AA-443E-8A10-DDB43266A8C4}</ProjectGuid> <OutputType>Exe</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>CSharpProject</RootNamespace> <AssemblyName>CSharpProject</AssemblyName> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'"> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>TRACE;DEBUG</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> <AllowUnsafeBlocks>false</AllowUnsafeBlocks> <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> <LangVersion>3</LangVersion> <DocumentationFile>bin\Debug\CSharpProject.XML</DocumentationFile> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|AnyCPU'"> <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> <OutputPath>bin\Release\</OutputPath> <DefineConstants>TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <PropertyGroup> <StartupObject>CSharpProject.CSharpClass</StartupObject> </PropertyGroup> <ItemGroup> <Reference Include="Microsoft.CSharp" /> <Reference Include="System" /> <Reference Include="System.Core" /> </ItemGroup> <ItemGroup> <Compile Include="..\OtherStuff\Foo.cs"> <Link>Blah\Foo.cs</Link> </Compile> <Compile Include="CSharpClass.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets. <Target Name="BeforeBuild"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test/EditAndContinue/EditSessionActiveStatementsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, EditAndContinueTestHelpers.Net5RuntimeCapabilities, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.GetTestAccessor().SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); debuggingSession.RestartEditSession(inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.EditAndContinue; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Xunit; using System.Text; using System.IO; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { using static ActiveStatementTestHelpers; [UseExportProvider] public class EditSessionActiveStatementsTests : TestBase { private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeatures.AddParts(typeof(DummyLanguageService)); private static EditSession CreateEditSession( Solution solution, ImmutableArray<ManagedActiveStatementDebugInfo> activeStatements, ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> nonRemappableRegions = null, CommittedSolution.DocumentState initialState = CommittedSolution.DocumentState.MatchesBuildOutput) { var mockDebuggerService = new MockManagedEditAndContinueDebuggerService() { GetActiveStatementsImpl = () => activeStatements }; var mockCompilationOutputsProvider = new Func<Project, CompilationOutputs>(_ => new MockCompilationOutputs(Guid.NewGuid())); var debuggingSession = new DebuggingSession( new DebuggingSessionId(1), solution, mockDebuggerService, EditAndContinueTestHelpers.Net5RuntimeCapabilities, mockCompilationOutputsProvider, SpecializedCollections.EmptyEnumerable<KeyValuePair<DocumentId, CommittedSolution.DocumentState>>(), reportDiagnostics: true); if (initialState != CommittedSolution.DocumentState.None) { EditAndContinueWorkspaceServiceTests.SetDocumentsState(debuggingSession, solution, initialState); } debuggingSession.GetTestAccessor().SetNonRemappableRegions(nonRemappableRegions ?? ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty); debuggingSession.RestartEditSession(inBreakState: true, out _); return debuggingSession.EditSession; } private static Solution AddDefaultTestSolution(TestWorkspace workspace, string[] markedSources) { var solution = workspace.CurrentSolution; var project = solution .AddProject("proj", "proj", LanguageNames.CSharp) .WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); solution = project.Solution; for (var i = 0; i < markedSources.Length; i++) { var name = $"test{i + 1}.cs"; var text = SourceText.From(ActiveStatementsDescription.ClearTags(markedSources[i]), Encoding.UTF8); var id = DocumentId.CreateNewId(project.Id, name); solution = solution.AddDocument(id, name, text, filePath: Path.Combine(TempRoot.Root, name)); } workspace.ChangeSolution(solution); return solution; } [Fact] public async Task BaseActiveStatementsAndExceptionRegions1() { var markedSources = new[] { @"class Test1 { static void M1() { try { } finally { <AS:1>F1();</AS:1> } } static void F1() { <AS:0>Console.WriteLine(1);</AS:0> } }", @"class Test2 { static void M2() { try { try { <AS:3>F2();</AS:3> } catch (Exception1 e1) { } } catch (Exception2 e2) { } } static void F2() { <AS:2>Test1.M1()</AS:2> } static void Main() { try { <AS:4>M2();</AS:4> } finally { } } } " }; var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var module2 = new Guid("22222222-2222-2222-2222-222222222222"); var module3 = new Guid("33333333-3333-3333-3333-333333333333"); var module4 = new Guid("44444444-4444-4444-4444-444444444444"); var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2, 3, 4, 5 }, ilOffsets: new[] { 1, 1, 1, 2, 3 }, modules: new[] { module1, module1, module2, module2, module2 }); // add an extra active statement that has no location, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: Guid.NewGuid(), token: 0x06000005, version: 1), ilOffset: 10), documentName: null, sourceSpan: default, ActiveStatementFlags.IsNonLeafFrame)); // add an extra active statement from project not belonging to the solution, it should be ignored: activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module3, token: 0x06000005, version: 1), ilOffset: 10), "NonRoslynDocument.mcpp", new SourceSpan(1, 1, 1, 10), ActiveStatementFlags.IsNonLeafFrame)); // Add an extra active statement from language that doesn't support Roslyn EnC should be ignored: // See https://github.com/dotnet/roslyn/issues/24408 for test scenario. activeStatements = activeStatements.Add( new ManagedActiveStatementDebugInfo( new ManagedInstructionId(new ManagedMethodId(module: module4, token: 0x06000005, version: 1), ilOffset: 10), "a.dummy", new SourceSpan(2, 1, 2, 10), ActiveStatementFlags.IsNonLeafFrame)); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var projectId = solution.ProjectIds.Single(); var dummyProject = solution.AddProject("dummy_proj", "dummy_proj", DummyLanguageService.LanguageName); solution = dummyProject.Solution.AddDocument(DocumentId.CreateNewId(dummyProject.Id, DummyLanguageService.LanguageName), "a.dummy", ""); var project = solution.GetProject(projectId); var document1 = project.Documents.Single(d => d.Name == "test1.cs"); var document2 = project.Documents.Single(d => d.Name == "test2.cs"); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementsMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var statements = baseActiveStatementsMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0001", $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0001", $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000003 v1 IL_0001", // [|Test1.M1()|] in F2 $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000004 v1 IL_0002", // [|F2();|] in M2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame] mvid=22222222-2222-2222-2222-222222222222 0x06000005 v1 IL_0003", // [|M2();|] in Main $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame] mvid={module3} 0x06000005 v1 IL_000A", $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame] mvid={module4} 0x06000005 v1 IL_000A" }, statements.Select(InspectActiveStatementAndInstruction)); // Active Statements per document Assert.Equal(4, baseActiveStatementsMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document1.FilePath}: (4,32)-(4,37) flags=[MethodUpToDate, IsNonLeafFrame]", $"0: {document1.FilePath}: (9,14)-(9,35) flags=[IsLeafFrame, MethodUpToDate]" }, baseActiveStatementsMap.DocumentPathMap[document1.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"3: {document2.FilePath}: (8,20)-(8,25) flags=[MethodUpToDate, IsNonLeafFrame]", // [|F2();|] in M2 $"2: {document2.FilePath}: (21,14)-(21,24) flags=[MethodUpToDate, IsNonLeafFrame]", // [|Test1.M1()|] in F2 $"4: {document2.FilePath}: (26,20)-(26,25) flags=[MethodUpToDate, IsNonLeafFrame]" // [|M2();|] in Main }, baseActiveStatementsMap.DocumentPathMap[document2.FilePath].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"5: NonRoslynDocument.mcpp: (1,1)-(1,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["NonRoslynDocument.mcpp"].Select(InspectActiveStatement)); AssertEx.Equal(new[] { $"6: a.dummy: (2,1)-(2,10) flags=[IsNonLeafFrame]", }, baseActiveStatementsMap.DocumentPathMap["a.dummy"].Select(InspectActiveStatement)); // Exception Regions var analyzer = solution.GetProject(projectId).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements1 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document1, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document1.FilePath}: (4,8)-(4,46)]", "[]", }, oldActiveStatements1.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); var oldActiveStatements2 = await baseActiveStatementsMap.GetOldActiveStatementsAsync(analyzer, document2, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document2.FilePath}: (14,8)-(16,9), {document2.FilePath}: (10,10)-(12,11)]", "[]", $"[{document2.FilePath}: (26,35)-(26,46)]", }, oldActiveStatements2.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 updates in Document2: // Test2.M2: adding a line in front of try-catch. // Test2.F2: moving the entire method 2 lines down. var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements2, newStatements: ImmutableArray.Create( statements[3].WithFileSpan(statements[3].FileSpan.AddLineDelta(+1)), statements[2].WithFileSpan(statements[2].FileSpan.AddLineDelta(+2)), statements[4]), newExceptionRegions: ImmutableArray.Create( oldActiveStatements2[0].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+1)), oldActiveStatements2[1].ExceptionRegions.Spans, oldActiveStatements2[2].ExceptionRegions.Spans))); EditSession.GetActiveStatementAndExceptionRegionSpans( module2, baseActiveStatementsMap, updatedMethodTokens: ImmutableArray.Create(0x06000004), // contains only recompiled methods in the project we are interested in (module2) previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); AssertEx.Equal(new[] { $"0x06000004 v1 | AS {document2.FilePath}: (8,20)-(8,25) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (14,8)-(16,9) δ=1", $"0x06000004 v1 | ER {document2.FilePath}: (10,10)-(12,11) δ=1" }, nonRemappableRegions.Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000004 v1 | (15,8)-(17,9) Delta=-1", $"0x06000004 v1 | (11,10)-(13,11) Delta=-1" }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000004 v1 IL_0002: (9,20)-(9,25)" }, activeStatementsInUpdatedMethods.Select(InspectActiveStatementUpdate)); } [Fact, WorkItem(24439, "https://github.com/dotnet/roslyn/issues/24439")] public async Task BaseActiveStatementsAndExceptionRegions2() { var baseSource = @"class Test { static void F1() { try { <AS:0>F2();</AS:0> } catch (Exception) { Console.WriteLine(1); Console.WriteLine(2); Console.WriteLine(3); } /*insert1[1]*/ } static void F2() { <AS:1>throw new Exception();</AS:1> } }"; var updatedSource = Update(baseSource, marker: "1"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var baseText = SourceText.From(baseSource); var updatedText = SourceText.From(updatedSource); var baseActiveStatementInfos = GetActiveStatementDebugInfosCSharp( new[] { baseSource }, modules: new[] { module1, module1 }, methodVersions: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsLeafFrame, // F2 }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { baseSource }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, baseActiveStatementInfos); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,23) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v1 IL_0000 '<AS:0>F2();</AS:0>'", $"1: {document.FilePath}: (18,14)-(18,36) flags=[IsLeafFrame, MethodUpToDate] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v1 IL_0000 '<AS:1>throw new Exception();</AS:1>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, baseText))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(12,9) 'catch (Exception) {{']", "[]", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, baseText)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(+1))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans)) ); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000001), // F1 previousNonRemappableRegions: ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>>.Empty, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // although the span has not changed the method has, so we need to add corresponding non-remappable regions AssertEx.Equal(new[] { $"0x06000001 v1 | AS {document.FilePath}: (6,18)-(6,23) δ=0", $"0x06000001 v1 | ER {document.FilePath}: (8,8)-(12,9) δ=0", }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { "0x06000001 v1 | (8,8)-(12,9) Delta=0", }, exceptionRegionUpdates.Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { "0x06000001 v1 IL_0000: (6,18)-(6,23) '<AS:0>F2();</AS:0>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), updatedText)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_WithInitialNonRemappableRegions() { var markedSourceV1 = @"class Test { static void F1() { try { <AS:0>M();</AS:0> } <ER:0.0>catch { }</ER:0.0> } static void F2() { /*delete2 */try { } <ER:1.0>catch { <AS:1>M();</AS:1> }</ER:1.0>/*insert2[1]*/ } static void F3() { try { try { /*delete1 */<AS:2>M();</AS:2>/*insert1[3]*/ } <ER:2.0>finally { }</ER:2.0> } <ER:2.1>catch { }</ER:2.1> /*delete1 */ } static void F4() { /*insert1[1]*//*insert2[2]*/ try { try { } <ER:3.0>catch { <AS:3>M();</AS:3> }</ER:3.0> } <ER:3.1>catch { }</ER:3.1> } }"; var markedSourceV2 = Update(markedSourceV1, marker: "1"); var markedSourceV3 = Update(markedSourceV2, marker: "2"); var module1 = new Guid("11111111-1111-1111-1111-111111111111"); var sourceTextV1 = SourceText.From(markedSourceV1); var sourceTextV2 = SourceText.From(markedSourceV2); var sourceTextV3 = SourceText.From(markedSourceV3); var activeStatementsPreRemap = GetActiveStatementDebugInfosCSharp(new[] { markedSourceV1 }, modules: new[] { module1, module1, module1, module1 }, methodVersions: new[] { 2, 2, 1, 1 }, // method F3 and F4 were not remapped flags: new[] { ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F1 ActiveStatementFlags.MethodUpToDate | ActiveStatementFlags.IsNonLeafFrame, // F2 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F3 ActiveStatementFlags.None | ActiveStatementFlags.IsNonLeafFrame, // F4 }); var exceptionSpans = ActiveStatementsDescription.GetExceptionRegions(markedSourceV1); var filePath = activeStatementsPreRemap[0].DocumentName; var spanPreRemap2 = new SourceFileSpan(filePath, activeStatementsPreRemap[2].SourceSpan.ToLinePositionSpan()); var erPreRemap20 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][0])); var erPreRemap21 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[2][1])); var spanPreRemap3 = new SourceFileSpan(filePath, activeStatementsPreRemap[3].SourceSpan.ToLinePositionSpan()); var erPreRemap30 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][0])); var erPreRemap31 = new SourceFileSpan(filePath, sourceTextV1.Lines.GetLinePositionSpan(exceptionSpans[3][1])); // Assume that the following edits have been made to F3 and F4 and set up non-remappable regions mapping // from the pre-remap spans of AS:2 and AS:3 to their current location. var initialNonRemappableRegions = new Dictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> { { new ManagedMethodId(module1, 0x06000003, 1), ImmutableArray.Create( // move AS:2 one line up: new NonRemappableRegion(spanPreRemap2, lineDelta: -1, isExceptionRegion: false), // move ER:2.0 and ER:2.1 two lines down: new NonRemappableRegion(erPreRemap20, lineDelta: +2, isExceptionRegion: true), new NonRemappableRegion(erPreRemap21, lineDelta: +2, isExceptionRegion: true)) }, { new ManagedMethodId(module1, 0x06000004, 1), ImmutableArray.Create( // move AS:3 one line down: new NonRemappableRegion(spanPreRemap3, lineDelta: +1, isExceptionRegion: false), // move ER:3.0 and ER:3.1 one line down: new NonRemappableRegion(erPreRemap30, lineDelta: +1, isExceptionRegion: true), new NonRemappableRegion(erPreRemap31, lineDelta: +1, isExceptionRegion: true)) } }.ToImmutableDictionary(); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, new[] { markedSourceV2 }); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatementsPreRemap, initialNonRemappableRegions); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements var baseActiveStatements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.Ordinal).ToArray(); // Note that the spans of AS:2 and AS:3 correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"0: {document.FilePath}: (6,18)-(6,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000001 v2 IL_0000 '<AS:0>M();</AS:0>'", $"1: {document.FilePath}: (20,18)-(20,22) flags=[MethodUpToDate, IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000002 v2 IL_0000 '<AS:1>M();</AS:1>'", $"2: {document.FilePath}: (29,22)-(29,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000003 v1 IL_0000 '{{ <AS:2>M();</AS:2>'", $"3: {document.FilePath}: (53,22)-(53,26) flags=[IsNonLeafFrame] mvid=11111111-1111-1111-1111-111111111111 0x06000004 v1 IL_0000 '<AS:3>M();</AS:3>'" }, baseActiveStatements.Select(s => InspectActiveStatementAndInstruction(s, sourceTextV2))); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); // Note that the spans correspond to the base snapshot (V2). AssertEx.Equal(new[] { $"[{document.FilePath}: (8,16)-(10,9) '<ER:0.0>catch']", $"[{document.FilePath}: (18,16)-(21,9) '<ER:1.0>catch']", $"[{document.FilePath}: (38,16)-(40,9) '<ER:2.1>catch', {document.FilePath}: (34,20)-(36,13) '<ER:2.0>finally']", $"[{document.FilePath}: (56,16)-(58,9) '<ER:3.1>catch', {document.FilePath}: (51,20)-(54,13) '<ER:3.0>catch']", }, oldActiveStatements.Select(s => "[" + string.Join(", ", s.ExceptionRegions.Spans.Select(span => $"{span} '{GetFirstLineText(span.Span, sourceTextV2)}'")) + "]")); // GetActiveStatementAndExceptionRegionSpans // Assume 2 more updates: // F2: Move 'try' one line up (a new non-remappable entries will be added) // F4: Insert 2 new lines before the first 'try' (an existing non-remappable entries will be updated) var newActiveStatementsInChangedDocuments = ImmutableArray.Create( new DocumentActiveStatementChanges( oldSpans: oldActiveStatements, newStatements: ImmutableArray.Create( baseActiveStatements[0], baseActiveStatements[1].WithFileSpan(baseActiveStatements[1].FileSpan.AddLineDelta(-1)), baseActiveStatements[2], baseActiveStatements[3].WithFileSpan(baseActiveStatements[3].FileSpan.AddLineDelta(+2))), newExceptionRegions: ImmutableArray.Create( oldActiveStatements[0].ExceptionRegions.Spans, oldActiveStatements[1].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(-1)), oldActiveStatements[2].ExceptionRegions.Spans, oldActiveStatements[3].ExceptionRegions.Spans.SelectAsArray(es => es.AddLineDelta(+2))))); EditSession.GetActiveStatementAndExceptionRegionSpans( module1, baseActiveStatementMap, updatedMethodTokens: ImmutableArray.Create(0x06000002, 0x06000004), // F2, F4 initialNonRemappableRegions, newActiveStatementsInChangedDocuments, out var activeStatementsInUpdatedMethods, out var nonRemappableRegions, out var exceptionRegionUpdates); // Note: Since no method have been remapped yet all the following spans are in their pre-remap locations: AssertEx.Equal(new[] { $"0x06000002 v2 | ER {document.FilePath}: (18,16)-(21,9) δ=-1", $"0x06000002 v2 | AS {document.FilePath}: (20,18)-(20,22) δ=-1", $"0x06000003 v1 | AS {document.FilePath}: (30,22)-(30,26) δ=-1", // AS:2 moved -1 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (32,20)-(34,13) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000003 v1 | ER {document.FilePath}: (36,16)-(38,9) δ=2", // ER:2.0 moved +2 in first edit, 0 in second $"0x06000004 v1 | ER {document.FilePath}: (50,20)-(53,13) δ=3", // ER:3.0 moved +1 in first edit, +2 in second $"0x06000004 v1 | AS {document.FilePath}: (52,22)-(52,26) δ=3", // AS:3 moved +1 in first edit, +2 in second $"0x06000004 v1 | ER {document.FilePath}: (55,16)-(57,9) δ=3", // ER:3.1 moved +1 in first edit, +2 in second }, nonRemappableRegions.OrderBy(r => r.Region.Span.Span.Start.Line).Select(r => $"{r.Method.GetDebuggerDisplay()} | {r.Region.GetDebuggerDisplay()}")); AssertEx.Equal(new[] { $"0x06000002 v2 | (17,16)-(20,9) Delta=1", $"0x06000003 v1 | (34,20)-(36,13) Delta=-2", $"0x06000003 v1 | (38,16)-(40,9) Delta=-2", $"0x06000004 v1 | (53,20)-(56,13) Delta=-3", $"0x06000004 v1 | (58,16)-(60,9) Delta=-3", }, exceptionRegionUpdates.OrderBy(r => r.NewSpan.StartLine).Select(InspectExceptionRegionUpdate)); AssertEx.Equal(new[] { $"0x06000002 v2 IL_0000: (19,18)-(19,22) '<AS:1>M();</AS:1>'", $"0x06000004 v1 IL_0000: (55,22)-(55,26) '<AS:3>M();</AS:3>'" }, activeStatementsInUpdatedMethods.Select(update => $"{InspectActiveStatementUpdate(update)} '{GetFirstLineText(update.NewSpan.ToLinePositionSpan(), sourceTextV3)}'")); } [Fact] public async Task BaseActiveStatementsAndExceptionRegions_Recursion() { var markedSources = new[] { @"class C { static void M() { try { <AS:1>M();</AS:1> } catch (Exception e) { } } static void F() { <AS:0>M();</AS:0> } }" }; var thread1 = Guid.NewGuid(); var thread2 = Guid.NewGuid(); // Thread1 stack trace: F (AS:0), M (AS:1 leaf) // Thread2 stack trace: F (AS:0), M (AS:1), M (AS:1 leaf) var activeStatements = GetActiveStatementDebugInfosCSharp( markedSources, methodRowIds: new[] { 1, 2 }, ilOffsets: new[] { 1, 1 }, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.NonUserCode | ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.MethodUpToDate, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame | ActiveStatementFlags.MethodUpToDate }); using var workspace = new TestWorkspace(composition: s_composition); var solution = AddDefaultTestSolution(workspace, markedSources); var project = solution.Projects.Single(); var document = project.Documents.Single(); var editSession = CreateEditSession(solution, activeStatements); var baseActiveStatementMap = await editSession.BaseActiveStatements.GetValueAsync(CancellationToken.None).ConfigureAwait(false); // Active Statements Assert.Equal(1, baseActiveStatementMap.DocumentPathMap.Count); AssertEx.Equal(new[] { $"1: {document.FilePath}: (6,18)-(6,22) flags=[IsLeafFrame, MethodUpToDate, IsNonLeafFrame]", $"0: {document.FilePath}: (15,14)-(15,18) flags=[PartiallyExecuted, NonUserCode, MethodUpToDate, IsNonLeafFrame]", }, baseActiveStatementMap.DocumentPathMap[document.FilePath].Select(InspectActiveStatement)); Assert.Equal(2, baseActiveStatementMap.InstructionMap.Count); var statements = baseActiveStatementMap.InstructionMap.Values.OrderBy(v => v.InstructionId.Method.Token).ToArray(); var s = statements[0]; Assert.Equal(0x06000001, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsNonLeaf); s = statements[1]; Assert.Equal(0x06000002, s.InstructionId.Method.Token); Assert.Equal(document.FilePath, s.FilePath); Assert.True(s.IsLeaf); Assert.True(s.IsNonLeaf); // Exception Regions var analyzer = solution.GetProject(project.Id).LanguageServices.GetRequiredService<IEditAndContinueAnalyzer>(); var oldActiveStatements = await baseActiveStatementMap.GetOldActiveStatementsAsync(analyzer, document, CancellationToken.None).ConfigureAwait(false); AssertEx.Equal(new[] { $"[{document.FilePath}: (8,8)-(10,9)]", "[]" }, oldActiveStatements.Select(s => "[" + string.Join(",", s.ExceptionRegions.Spans) + "]")); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/ChangeSignature/ChangeSignature_CheckAllSignatureChanges.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Theory, Trait(Traits.Feature, Traits.Features.ChangeSignature)> <MemberData(NameOf(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), New Integer() {1, 3, 2, 0}, MemberType:=GetType(AbstractChangeSignatureTests))> Public Async Function TestAllSignatureChanges_1This_3Regular_2Default(totalParameters As Integer, signature As Integer()) As Task Dim markup = <Text><![CDATA[ Option Strict On Module Program ''' <summary> ''' See <see cref="M(String, Integer, String, Boolean, Integer, String)"/> ''' </summary> ''' <param name="o">o!</param> ''' <param name="a">a!</param> ''' <param name="b">b!</param> ''' <param name="c">c!</param> ''' <param name="x">x!</param> ''' <param name="y">y!</param> <System.Runtime.CompilerServices.Extension> Sub $$M(ByVal o As String, a As Integer, b As String, c As Boolean, Optional x As Integer = 0, Optional y As String = "Zero") Dim t = "Test" M(t, 1, "Two", True, 3, "Four") t.M(1, "Two", True, 3, "Four") M(t, 1, "Two", True, 3) M(t, 1, "Two", True) M(t, 1, "Two", True, 3, y:="Four") M(t, 1, "Two", c:=True) M(t, 1, "Two", True, y:="Four") M(t, 1, "Two", True, x:=3) M(t, 1, "Two", True, y:="Four", x:=3) M(t, 1, y:="Four", x:=3, b:="Two", c:=True) M(t, y:="Four", x:=3, c:=True, b:="Two", a:=1) M(y:="Four", x:=3, c:=True, b:="Two", a:=1, o:=t) End Sub End Module ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, expectedSuccess:=True, updatedSignature:=signature, totalParameters:=totalParameters, verifyNoDiagnostics:=True) End Function <Theory, Trait(Traits.Feature, Traits.Features.ChangeSignature)> <MemberData(NameOf(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), New Integer() {1, 3, 0, 1}, MemberType:=GetType(AbstractChangeSignatureTests))> Public Async Function TestAllSignatureChanges_1This_3Regular_1ParamArray(totalParameters As Integer, signature As Integer()) As Task Dim markup = <Text><![CDATA[ Option Strict On Module Program <System.Runtime.CompilerServices.Extension> Sub $$M(ByVal o As String, a As Integer, b As Boolean, c As Integer, ParamArray p As Integer()) Dim t = "Test" M(t, 1, True, 3, {4, 5}) t.M(1, True, 3, {4, 5}) M(t, 1, True, 3, 4, 5) t.M(1, True, 3, 4, 5) M(t, 1, True, 3) t.M(1, True, 3) End Sub End Module ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, expectedSuccess:=True, updatedSignature:=signature, totalParameters:=totalParameters, verifyNoDiagnostics:=True) End Function <Theory, Trait(Traits.Feature, Traits.Features.ChangeSignature)> <MemberData(NameOf(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), New Integer() {0, 3, 0, 0}, MemberType:=GetType(AbstractChangeSignatureTests))> Public Async Function TestAllSignatureChanges_Delegate_3(totalParameters As Integer, signature As Integer()) As Task Dim markup = <Text><![CDATA[ Option Strict On Class C ''' <summary> ''' <see cref="MyDelegate.Invoke(Integer, String, Boolean)"/> ''' <see cref="MyDelegate.BeginInvoke(Integer, String, Boolean, AsyncCallback, Object)"/> ''' </summary> ''' <param name="x"></param> ''' <param name="y"></param> ''' <param name="z"></param> Delegate Sub $$MyDelegate(x As Integer, y As String, z As Boolean) Event MyEvent As MyDelegate Custom Event MyEvent2 As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(1, "Two", True) RaiseEvent MyEvent2(1, "Two", True) AddHandler MyEvent, AddressOf MyEventHandler AddHandler MyEvent2, AddressOf MyEventHandler2 Dim x As MyDelegate = Nothing x(1, "Two", True) x.Invoke(1, "Two", True) x.BeginInvoke(1, "Two", True, Nothing, New Object()) End Sub ''' <param name="a"></param> ''' <param name="b"></param> ''' <param name="c"></param> Sub MyEventHandler(a As Integer, b As String, c As Boolean) End Sub Sub MyEventHandlerEmpty() End Sub Sub MyEventHandler2(a As Integer, b As String, c As Boolean) End Sub Sub MyEventHandler2Empty() End Sub Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent End Sub Sub MyOtherEventHandler2(a As Integer, b As String, c As Boolean) Handles Me.MyEvent2 End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, expectedSuccess:=True, updatedSignature:=signature, totalParameters:=totalParameters, verifyNoDiagnostics:=True) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature Partial Public Class ChangeSignatureTests Inherits AbstractChangeSignatureTests <Theory, Trait(Traits.Feature, Traits.Features.ChangeSignature)> <MemberData(NameOf(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), New Integer() {1, 3, 2, 0}, MemberType:=GetType(AbstractChangeSignatureTests))> Public Async Function TestAllSignatureChanges_1This_3Regular_2Default(totalParameters As Integer, signature As Integer()) As Task Dim markup = <Text><![CDATA[ Option Strict On Module Program ''' <summary> ''' See <see cref="M(String, Integer, String, Boolean, Integer, String)"/> ''' </summary> ''' <param name="o">o!</param> ''' <param name="a">a!</param> ''' <param name="b">b!</param> ''' <param name="c">c!</param> ''' <param name="x">x!</param> ''' <param name="y">y!</param> <System.Runtime.CompilerServices.Extension> Sub $$M(ByVal o As String, a As Integer, b As String, c As Boolean, Optional x As Integer = 0, Optional y As String = "Zero") Dim t = "Test" M(t, 1, "Two", True, 3, "Four") t.M(1, "Two", True, 3, "Four") M(t, 1, "Two", True, 3) M(t, 1, "Two", True) M(t, 1, "Two", True, 3, y:="Four") M(t, 1, "Two", c:=True) M(t, 1, "Two", True, y:="Four") M(t, 1, "Two", True, x:=3) M(t, 1, "Two", True, y:="Four", x:=3) M(t, 1, y:="Four", x:=3, b:="Two", c:=True) M(t, y:="Four", x:=3, c:=True, b:="Two", a:=1) M(y:="Four", x:=3, c:=True, b:="Two", a:=1, o:=t) End Sub End Module ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, expectedSuccess:=True, updatedSignature:=signature, totalParameters:=totalParameters, verifyNoDiagnostics:=True) End Function <Theory, Trait(Traits.Feature, Traits.Features.ChangeSignature)> <MemberData(NameOf(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), New Integer() {1, 3, 0, 1}, MemberType:=GetType(AbstractChangeSignatureTests))> Public Async Function TestAllSignatureChanges_1This_3Regular_1ParamArray(totalParameters As Integer, signature As Integer()) As Task Dim markup = <Text><![CDATA[ Option Strict On Module Program <System.Runtime.CompilerServices.Extension> Sub $$M(ByVal o As String, a As Integer, b As Boolean, c As Integer, ParamArray p As Integer()) Dim t = "Test" M(t, 1, True, 3, {4, 5}) t.M(1, True, 3, {4, 5}) M(t, 1, True, 3, 4, 5) t.M(1, True, 3, 4, 5) M(t, 1, True, 3) t.M(1, True, 3) End Sub End Module ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, expectedSuccess:=True, updatedSignature:=signature, totalParameters:=totalParameters, verifyNoDiagnostics:=True) End Function <Theory, Trait(Traits.Feature, Traits.Features.ChangeSignature)> <MemberData(NameOf(AbstractChangeSignatureTests.GetAllSignatureSpecificationsForTheory), New Integer() {0, 3, 0, 0}, MemberType:=GetType(AbstractChangeSignatureTests))> Public Async Function TestAllSignatureChanges_Delegate_3(totalParameters As Integer, signature As Integer()) As Task Dim markup = <Text><![CDATA[ Option Strict On Class C ''' <summary> ''' <see cref="MyDelegate.Invoke(Integer, String, Boolean)"/> ''' <see cref="MyDelegate.BeginInvoke(Integer, String, Boolean, AsyncCallback, Object)"/> ''' </summary> ''' <param name="x"></param> ''' <param name="y"></param> ''' <param name="z"></param> Delegate Sub $$MyDelegate(x As Integer, y As String, z As Boolean) Event MyEvent As MyDelegate Custom Event MyEvent2 As MyDelegate AddHandler(value As MyDelegate) End AddHandler RemoveHandler(value As MyDelegate) End RemoveHandler RaiseEvent(x As Integer, y As String, z As Boolean) End RaiseEvent End Event Sub M() RaiseEvent MyEvent(1, "Two", True) RaiseEvent MyEvent2(1, "Two", True) AddHandler MyEvent, AddressOf MyEventHandler AddHandler MyEvent2, AddressOf MyEventHandler2 Dim x As MyDelegate = Nothing x(1, "Two", True) x.Invoke(1, "Two", True) x.BeginInvoke(1, "Two", True, Nothing, New Object()) End Sub ''' <param name="a"></param> ''' <param name="b"></param> ''' <param name="c"></param> Sub MyEventHandler(a As Integer, b As String, c As Boolean) End Sub Sub MyEventHandlerEmpty() End Sub Sub MyEventHandler2(a As Integer, b As String, c As Boolean) End Sub Sub MyEventHandler2Empty() End Sub Sub MyOtherEventHandler(a As Integer, b As String, c As Boolean) Handles Me.MyEvent End Sub Sub MyOtherEventHandler2(a As Integer, b As String, c As Boolean) Handles Me.MyEvent2 End Sub End Class ]]></Text>.NormalizedValue() Await TestChangeSignatureViaCommandAsync( LanguageNames.VisualBasic, markup, expectedSuccess:=True, updatedSignature:=signature, totalParameters:=totalParameters, verifyNoDiagnostics:=True) End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/NotKeywordRecommender.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 NotKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NotKeywordRecommender() : base(SyntaxKind.NotKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAtStartOfPattern; } } }
// Licensed to the .NET Foundation under one or more 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 NotKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public NotKeywordRecommender() : base(SyntaxKind.NotKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsAtStartOfPattern; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/MemberDeclarationSyntaxExtensions_GetAttributes.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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class MemberDeclarationSyntaxExtensions { public static SyntaxList<AttributeListSyntax> GetAttributes(this MemberDeclarationSyntax member) { if (member != null) { return member.AttributeLists; } return SyntaxFactory.List<AttributeListSyntax>(); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class MemberDeclarationSyntaxExtensions { public static SyntaxList<AttributeListSyntax> GetAttributes(this MemberDeclarationSyntax member) { if (member != null) { return member.AttributeLists; } return SyntaxFactory.List<AttributeListSyntax>(); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/Formatting/FormattingTests_FunctionPointers.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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { [Trait(Traits.Feature, Traits.Features.Formatting)] public class FormattingTests_FunctionPointers : CSharpFormattingTestBase { [Fact] public async Task FormatFunctionPointer() { var content = @" unsafe class C { delegate * < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithManagedCallingConvention() { var content = @" unsafe class C { delegate *managed < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* managed<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConvention() { var content = @" unsafe class C { delegate *unmanaged < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged[Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnrecognizedCallingConvention() { var content = @" unsafe class C { delegate *invalid < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid <int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithInvalidCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *invalid [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid [Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } } }
// Licensed to the .NET Foundation under one or more 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 Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Formatting { [Trait(Traits.Feature, Traits.Features.Formatting)] public class FormattingTests_FunctionPointers : CSharpFormattingTestBase { [Fact] public async Task FormatFunctionPointer() { var content = @" unsafe class C { delegate * < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithManagedCallingConvention() { var content = @" unsafe class C { delegate *managed < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* managed<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConvention() { var content = @" unsafe class C { delegate *unmanaged < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnmanagedCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *unmanaged [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate* unmanaged[Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithUnrecognizedCallingConvention() { var content = @" unsafe class C { delegate *invalid < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid <int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } [Fact] public async Task FormatFunctionPointerWithInvalidCallingConventionAndSpecifiers() { var content = @" unsafe class C { delegate *invalid [ Cdecl , Thiscall ] < int , int > functionPointer; }"; var expected = @" unsafe class C { delegate*invalid [Cdecl, Thiscall]<int, int> functionPointer; }"; await AssertFormatAsync(expected, content); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./.git/hooks/pre-merge-commit.sample
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git merge" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message to # stderr if it wants to stop the merge commit. # # To enable this hook, rename this file to "pre-merge-commit". . git-sh-setup test -x "$GIT_DIR/hooks/pre-commit" && exec "$GIT_DIR/hooks/pre-commit" :
#!/bin/sh # # An example hook script to verify what is about to be committed. # Called by "git merge" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message to # stderr if it wants to stop the merge commit. # # To enable this hook, rename this file to "pre-merge-commit". . git-sh-setup test -x "$GIT_DIR/hooks/pre-commit" && exec "$GIT_DIR/hooks/pre-commit" :
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Shared/Utilities/AutomaticCodeChangeMergePolicy.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.Operations; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { /// <summary> /// a merge policy that should be used for any automatic code changes that could happen in sequences so that /// all those steps are shown to users as one undo transaction rather than multiple ones /// </summary> internal class AutomaticCodeChangeMergePolicy : IMergeTextUndoTransactionPolicy { public static readonly AutomaticCodeChangeMergePolicy Instance = new(); public bool CanMerge(ITextUndoTransaction newerTransaction, ITextUndoTransaction olderTransaction) { // We want to merge with any other transaction of our policy type return true; } public void PerformTransactionMerge(ITextUndoTransaction existingTransaction, ITextUndoTransaction newTransaction) { // Add all of our commit primitives into the existing transaction foreach (var primitive in newTransaction.UndoPrimitives) { existingTransaction.UndoPrimitives.Add(primitive); } } public bool TestCompatiblePolicy(IMergeTextUndoTransactionPolicy other) { // We are compatible with any other merging policy return other is AutomaticCodeChangeMergePolicy; } } }
// Licensed to the .NET Foundation under one or more 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.Operations; namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities { /// <summary> /// a merge policy that should be used for any automatic code changes that could happen in sequences so that /// all those steps are shown to users as one undo transaction rather than multiple ones /// </summary> internal class AutomaticCodeChangeMergePolicy : IMergeTextUndoTransactionPolicy { public static readonly AutomaticCodeChangeMergePolicy Instance = new(); public bool CanMerge(ITextUndoTransaction newerTransaction, ITextUndoTransaction olderTransaction) { // We want to merge with any other transaction of our policy type return true; } public void PerformTransactionMerge(ITextUndoTransaction existingTransaction, ITextUndoTransaction newTransaction) { // Add all of our commit primitives into the existing transaction foreach (var primitive in newTransaction.UndoPrimitives) { existingTransaction.UndoPrimitives.Add(primitive); } } public bool TestCompatiblePolicy(IMergeTextUndoTransactionPolicy other) { // We are compatible with any other merging policy return other is AutomaticCodeChangeMergePolicy; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/Structure/VisualBasicBlockStructureProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class VisualBasicBlockStructureProvider Inherits AbstractBlockStructureProvider Public Shared Function CreateDefaultNodeStructureProviderMap() As ImmutableDictionary(Of Type, ImmutableArray(Of AbstractSyntaxStructureProvider)) Dim builder = ImmutableDictionary.CreateBuilder(Of Type, ImmutableArray(Of AbstractSyntaxStructureProvider))() builder.Add(Of AccessorStatementSyntax, AccessorDeclarationStructureProvider)() builder.Add(Of ClassStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of CollectionInitializerSyntax, CollectionInitializerStructureProvider) builder.Add(Of CompilationUnitSyntax, CompilationUnitStructureProvider)() builder.Add(Of SubNewStatementSyntax, ConstructorDeclarationStructureProvider)() builder.Add(Of DelegateStatementSyntax, DelegateDeclarationStructureProvider)() builder.Add(Of DocumentationCommentTriviaSyntax, DocumentationCommentStructureProvider)() builder.Add(Of DoLoopBlockSyntax, DoLoopBlockStructureProvider) builder.Add(Of EnumStatementSyntax, EnumDeclarationStructureProvider)() builder.Add(Of EnumMemberDeclarationSyntax, EnumMemberDeclarationStructureProvider)() builder.Add(Of EventStatementSyntax, EventDeclarationStructureProvider)() builder.Add(Of DeclareStatementSyntax, ExternalMethodDeclarationStructureProvider)() builder.Add(Of FieldDeclarationSyntax, FieldDeclarationStructureProvider)() builder.Add(Of ForBlockSyntax, ForBlockStructureProvider) builder.Add(Of ForEachBlockSyntax, ForEachBlockStructureProvider) builder.Add(Of InterfaceStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of MethodStatementSyntax, MethodDeclarationStructureProvider)() builder.Add(Of ModuleStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of MultiLineIfBlockSyntax, MultiLineIfBlockStructureProvider)() builder.Add(Of MultiLineLambdaExpressionSyntax, MultilineLambdaStructureProvider)() builder.Add(Of NamespaceStatementSyntax, NamespaceDeclarationStructureProvider)() builder.Add(Of ObjectCollectionInitializerSyntax, ObjectCreationInitializerStructureProvider) builder.Add(Of ObjectMemberInitializerSyntax, ObjectCreationInitializerStructureProvider) builder.Add(Of OperatorStatementSyntax, OperatorDeclarationStructureProvider)() builder.Add(Of PropertyStatementSyntax, PropertyDeclarationStructureProvider)() builder.Add(Of RegionDirectiveTriviaSyntax, RegionDirectiveStructureProvider)() builder.Add(Of SelectBlockSyntax, SelectBlockStructureProvider) builder.Add(Of StructureStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of SyncLockBlockSyntax, SyncLockBlockStructureProvider) builder.Add(Of TryBlockSyntax, TryBlockStructureProvider) builder.Add(Of UsingBlockSyntax, UsingBlockStructureProvider) builder.Add(Of WhileBlockSyntax, WhileBlockStructureProvider) builder.Add(Of WithBlockSyntax, WithBlockStructureProvider) builder.Add(Of XmlCDataSectionSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlCommentSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlDocumentSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlElementSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlProcessingInstructionSyntax, XmlExpressionStructureProvider)() builder.Add(Of LiteralExpressionSyntax, StringLiteralExpressionStructureProvider)() builder.Add(Of InterpolatedStringExpressionSyntax, InterpolatedStringExpressionStructureProvider)() Return builder.ToImmutable() End Function Public Shared Function CreateDefaultTriviaStructureProviderMap() As ImmutableDictionary(Of Integer, ImmutableArray(Of AbstractSyntaxStructureProvider)) Dim builder = ImmutableDictionary.CreateBuilder(Of Integer, ImmutableArray(Of AbstractSyntaxStructureProvider))() builder.Add(SyntaxKind.DisabledTextTrivia, ImmutableArray.Create(Of AbstractSyntaxStructureProvider)(New DisabledTextTriviaStructureProvider())) Return builder.ToImmutable() End Function Friend Sub New() MyBase.New(CreateDefaultNodeStructureProviderMap(), CreateDefaultTriviaStructureProviderMap()) 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 Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class VisualBasicBlockStructureProvider Inherits AbstractBlockStructureProvider Public Shared Function CreateDefaultNodeStructureProviderMap() As ImmutableDictionary(Of Type, ImmutableArray(Of AbstractSyntaxStructureProvider)) Dim builder = ImmutableDictionary.CreateBuilder(Of Type, ImmutableArray(Of AbstractSyntaxStructureProvider))() builder.Add(Of AccessorStatementSyntax, AccessorDeclarationStructureProvider)() builder.Add(Of ClassStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of CollectionInitializerSyntax, CollectionInitializerStructureProvider) builder.Add(Of CompilationUnitSyntax, CompilationUnitStructureProvider)() builder.Add(Of SubNewStatementSyntax, ConstructorDeclarationStructureProvider)() builder.Add(Of DelegateStatementSyntax, DelegateDeclarationStructureProvider)() builder.Add(Of DocumentationCommentTriviaSyntax, DocumentationCommentStructureProvider)() builder.Add(Of DoLoopBlockSyntax, DoLoopBlockStructureProvider) builder.Add(Of EnumStatementSyntax, EnumDeclarationStructureProvider)() builder.Add(Of EnumMemberDeclarationSyntax, EnumMemberDeclarationStructureProvider)() builder.Add(Of EventStatementSyntax, EventDeclarationStructureProvider)() builder.Add(Of DeclareStatementSyntax, ExternalMethodDeclarationStructureProvider)() builder.Add(Of FieldDeclarationSyntax, FieldDeclarationStructureProvider)() builder.Add(Of ForBlockSyntax, ForBlockStructureProvider) builder.Add(Of ForEachBlockSyntax, ForEachBlockStructureProvider) builder.Add(Of InterfaceStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of MethodStatementSyntax, MethodDeclarationStructureProvider)() builder.Add(Of ModuleStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of MultiLineIfBlockSyntax, MultiLineIfBlockStructureProvider)() builder.Add(Of MultiLineLambdaExpressionSyntax, MultilineLambdaStructureProvider)() builder.Add(Of NamespaceStatementSyntax, NamespaceDeclarationStructureProvider)() builder.Add(Of ObjectCollectionInitializerSyntax, ObjectCreationInitializerStructureProvider) builder.Add(Of ObjectMemberInitializerSyntax, ObjectCreationInitializerStructureProvider) builder.Add(Of OperatorStatementSyntax, OperatorDeclarationStructureProvider)() builder.Add(Of PropertyStatementSyntax, PropertyDeclarationStructureProvider)() builder.Add(Of RegionDirectiveTriviaSyntax, RegionDirectiveStructureProvider)() builder.Add(Of SelectBlockSyntax, SelectBlockStructureProvider) builder.Add(Of StructureStatementSyntax, TypeDeclarationStructureProvider)() builder.Add(Of SyncLockBlockSyntax, SyncLockBlockStructureProvider) builder.Add(Of TryBlockSyntax, TryBlockStructureProvider) builder.Add(Of UsingBlockSyntax, UsingBlockStructureProvider) builder.Add(Of WhileBlockSyntax, WhileBlockStructureProvider) builder.Add(Of WithBlockSyntax, WithBlockStructureProvider) builder.Add(Of XmlCDataSectionSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlCommentSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlDocumentSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlElementSyntax, XmlExpressionStructureProvider)() builder.Add(Of XmlProcessingInstructionSyntax, XmlExpressionStructureProvider)() builder.Add(Of LiteralExpressionSyntax, StringLiteralExpressionStructureProvider)() builder.Add(Of InterpolatedStringExpressionSyntax, InterpolatedStringExpressionStructureProvider)() Return builder.ToImmutable() End Function Public Shared Function CreateDefaultTriviaStructureProviderMap() As ImmutableDictionary(Of Integer, ImmutableArray(Of AbstractSyntaxStructureProvider)) Dim builder = ImmutableDictionary.CreateBuilder(Of Integer, ImmutableArray(Of AbstractSyntaxStructureProvider))() builder.Add(SyntaxKind.DisabledTextTrivia, ImmutableArray.Create(Of AbstractSyntaxStructureProvider)(New DisabledTextTriviaStructureProvider())) Return builder.ToImmutable() End Function Friend Sub New() MyBase.New(CreateDefaultNodeStructureProviderMap(), CreateDefaultTriviaStructureProviderMap()) End Sub End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Binder/SwitchBinder.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.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SwitchBinder : LocalScopeBinder { protected readonly SwitchStatementSyntax SwitchSyntax; private readonly GeneratedLabelSymbol _breakLabel; private BoundExpression _switchGoverningExpression; private BindingDiagnosticBag _switchGoverningDiagnostics; private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) : base(next) { SwitchSyntax = switchSyntax; _breakLabel = new GeneratedLabelSymbol("break"); } protected bool PatternsEnabled => ((CSharpParseOptions)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) != false; protected BoundExpression SwitchGoverningExpression { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); Debug.Assert(_switchGoverningExpression != null); return _switchGoverningExpression; } } protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; protected uint SwitchGoverningValEscape => GetValEscape(SwitchGoverningExpression, LocalScopeDepth); protected BindingDiagnosticBag SwitchGoverningDiagnostics { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); return _switchGoverningDiagnostics; } } private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() { if (_switchGoverningExpression == null) { var switchGoverningDiagnostics = new BindingDiagnosticBag(); var boundSwitchExpression = BindSwitchGoverningExpression(switchGoverningDiagnostics); _switchGoverningDiagnostics = switchGoverningDiagnostics; Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null); } } // Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Default label(s) are indexed on a special DefaultKey object. // Invalid case labels with null constant value are indexed on the labelName. private Dictionary<object, SourceLabelSymbol> _lazySwitchLabelsMap; private static readonly object s_defaultKey = new object(); private Dictionary<object, SourceLabelSymbol> LabelsByValue { get { if (_lazySwitchLabelsMap == null && this.Labels.Length > 0) { _lazySwitchLabelsMap = BuildLabelsByValue(this.Labels); } return _lazySwitchLabelsMap; } } private static Dictionary<object, SourceLabelSymbol> BuildLabelsByValue(ImmutableArray<LabelSymbol> labels) { Debug.Assert(labels.Length > 0); var map = new Dictionary<object, SourceLabelSymbol>(labels.Length, new SwitchConstantValueHelper.SwitchLabelsComparer()); foreach (SourceLabelSymbol label in labels) { SyntaxKind labelKind = label.IdentifierNodeOrToken.Kind(); if (labelKind == SyntaxKind.IdentifierToken) { continue; } object key; var constantValue = label.SwitchCaseLabelConstant; if ((object)constantValue != null && !constantValue.IsBad) { // Case labels with a non-null constant value are indexed on their ConstantValue. key = KeyForConstant(constantValue); } else if (labelKind == SyntaxKind.DefaultSwitchLabel) { // Default label(s) are indexed on a special DefaultKey object. key = s_defaultKey; } else { // Invalid case labels with null constant value are indexed on the labelName. key = label.IdentifierNodeOrToken.AsNode(); } // If there is a duplicate label, ignore it. It will be reported when binding the switch label. if (!map.ContainsKey(key)) { map.Add(key, label); } } return map; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocals(section.Statements, GetBinder(section))); } return builder.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { var builder = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocalFunctions(section.Statements)); } return builder.ToImmutableAndFree(); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } internal override GeneratedLabelSymbol BreakLabel { get { return _breakLabel; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { // We bind the switch expression and the switch case label expressions so that the constant values can be // part of the label, but we do not report any diagnostics here. Diagnostics will be reported during binding. ArrayBuilder<LabelSymbol> labels = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { // add switch case/default labels BuildSwitchLabels(section.Labels, GetBinder(section), labels, BindingDiagnosticBag.Discarded); // add regular labels from the statements in the switch section BuildLabels(section.Statements, ref labels); } return labels.ToImmutableAndFree(); } internal override bool IsLabelsScopeBinder { get { return true; } } private void BuildSwitchLabels(SyntaxList<SwitchLabelSyntax> labelsSyntax, Binder sectionBinder, ArrayBuilder<LabelSymbol> labels, BindingDiagnosticBag tempDiagnosticBag) { // add switch case/default labels foreach (var labelSyntax in labelsSyntax) { ConstantValue boundLabelConstantOpt = null; switch (labelSyntax.Kind()) { case SyntaxKind.CaseSwitchLabel: // compute the constant value to place in the label symbol var caseLabel = (CaseSwitchLabelSyntax)labelSyntax; Debug.Assert(caseLabel.Value != null); var boundLabelExpression = sectionBinder.BindTypeOrRValue(caseLabel.Value, tempDiagnosticBag); if (boundLabelExpression is BoundTypeExpression type) { // Nothing to do at this point. The label will be bound later. } else { _ = ConvertCaseExpression(labelSyntax, boundLabelExpression, sectionBinder, out boundLabelConstantOpt, tempDiagnosticBag); } break; case SyntaxKind.CasePatternSwitchLabel: // bind the pattern, to cause its pattern variables to be inferred if necessary var matchLabel = (CasePatternSwitchLabelSyntax)labelSyntax; _ = sectionBinder.BindPattern( matchLabel.Pattern, SwitchGoverningType, SwitchGoverningValEscape, permitDesignations: true, labelSyntax.HasErrors, tempDiagnosticBag); break; default: // No constant value break; } // Create the label symbol labels.Add(new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, labelSyntax, boundLabelConstantOpt)); } } protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, Binder sectionBinder, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) { bool hasErrors = false; if (isGotoCaseExpr) { // SPEC VIOLATION for Dev10 COMPATIBILITY: // Dev10 compiler violates the SPEC comment below: // "if the constant-expression is not implicitly convertible (§6.1) to // the governing type of the nearest enclosing switch statement, // a compile-time error occurs" // If there is no implicit conversion from gotoCaseExpression to switchGoverningType, // but there exists an explicit conversion, Dev10 compiler generates a warning "WRN_GotoCaseShouldConvert" // instead of an error. See test "CS0469_NoImplicitConversionWarning". CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, caseExpression, SwitchGoverningType); hasErrors = true; } else if (!conversion.IsImplicit) { diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, node.Location, SwitchGoverningType); hasErrors = true; } caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); } return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics); } private static readonly object s_nullKey = new object(); protected static object KeyForConstant(ConstantValue constantValue) { Debug.Assert((object)constantValue != null); return constantValue.IsNull ? s_nullKey : constantValue.Value; } protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Invalid case labels (with null constant value) are indexed on the label syntax. object key; if ((object)constantValue != null && !constantValue.IsBad) { key = KeyForConstant(constantValue); } else { key = labelSyntax; } return FindMatchingSwitchLabel(key); } private SourceLabelSymbol GetDefaultLabel() { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Default label(s) are indexed on a special DefaultKey object. return FindMatchingSwitchLabel(s_defaultKey); } private SourceLabelSymbol FindMatchingSwitchLabel(object key) { Debug.Assert(key != null); var labelsMap = LabelsByValue; if (labelsMap != null) { SourceLabelSymbol label; if (labelsMap.TryGetValue(key, out label)) { Debug.Assert((object)label != null); return label; } } return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return SwitchSyntax; } } # region "Switch statement binding methods" // Bind the switch expression private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { // We are at present inside the switch binder, but the switch expression is not // bound in the context of the switch binder; it's bound in the context of the // enclosing binder. For example: // // class C { // int x; // void M() { // switch(x) { // case 1: // int x; // // The "x" in "switch(x)" refers to this.x, not the local x that is in scope inside the switch block. Debug.Assert(ScopeDesignator == SwitchSyntax); ExpressionSyntax node = SwitchSyntax.Expression; var binder = this.GetBinder(node); Debug.Assert(binder != null); var switchGoverningExpression = binder.BindRValueWithoutTargetType(node, diagnostics); var switchGoverningType = switchGoverningExpression.Type; if ((object)switchGoverningType != null && !switchGoverningType.IsErrorType()) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise if exactly one user-defined implicit conversion (§6.4) exists from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types, then the result is the switch governing type // SPEC: 3) Otherwise (in C# 7 and later) the switch governing type is the type of the // SPEC: switch expression. if (switchGoverningType.IsValidV6SwitchGoverningType()) { // Condition (1) satisfied // Note: dev11 actually checks the stripped type, but nullable was introduced at the same // time, so it doesn't really matter. if (switchGoverningType.SpecialType == SpecialType.System_Boolean) { CheckFeatureAvailability(node, MessageID.IDS_FeatureSwitchOnBool, diagnostics); } return switchGoverningExpression; } else { TypeSymbol resultantGoverningType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(switchGoverningType, out resultantGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (conversion.IsValid) { // Condition (2) satisfied Debug.Assert(conversion.Kind == ConversionKind.ImplicitUserDefined); Debug.Assert(conversion.Method.IsUserDefinedConversion()); Debug.Assert(conversion.UserDefinedToConversion.IsIdentity); Debug.Assert(resultantGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); return binder.CreateConversion(node, switchGoverningExpression, conversion, isCast: false, conversionGroupOpt: null, resultantGoverningType, diagnostics); } else if (!switchGoverningType.IsVoidType()) { // Otherwise (3) satisfied if (!PatternsEnabled) { diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, node.Location); } return switchGoverningExpression; } else { switchGoverningType = CreateErrorType(switchGoverningType.Name); } } } if (!switchGoverningExpression.HasAnyErrors) { Debug.Assert((object)switchGoverningExpression.Type == null || switchGoverningExpression.Type.IsVoidType()); diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, node.Location, switchGoverningExpression.Display); } return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(switchGoverningExpression), switchGoverningType ?? CreateErrorType()); } private Dictionary<SyntaxNode, LabelSymbol> _labelsByNode; protected Dictionary<SyntaxNode, LabelSymbol> LabelsByNode { get { if (_labelsByNode == null) { var result = new Dictionary<SyntaxNode, LabelSymbol>(); foreach (var label in Labels) { var node = ((SourceLabelSymbol)label).IdentifierNodeOrToken.AsNode(); if (node != null) { result.Add(node, label); } } _labelsByNode = result; } return _labelsByNode; } } internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement || node.Kind() == SyntaxKind.GotoDefaultStatement); BoundExpression gotoCaseExpressionOpt = null; // Prevent cascading diagnostics if (!node.HasErrors) { ConstantValue gotoCaseExpressionConstant = null; bool hasErrors = false; SourceLabelSymbol matchedLabelSymbol; // SPEC: If the goto case statement is not enclosed by a switch statement, if the constant-expression // SPEC: is not implicitly convertible (§6.1) to the governing type of the nearest enclosing switch statement, // SPEC: or if the nearest enclosing switch statement does not contain a case label with the given constant value, // SPEC: a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing // SPEC: switch statement does not contain a default label, a compile-time error occurs. if (node.Expression != null) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement); // Bind the goto case expression gotoCaseExpressionOpt = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); gotoCaseExpressionOpt = ConvertCaseExpression(node, gotoCaseExpressionOpt, gotoBinder, out gotoCaseExpressionConstant, diagnostics, isGotoCaseExpr: true); // Check for bind errors hasErrors = hasErrors || gotoCaseExpressionOpt.HasAnyErrors; if (!hasErrors && gotoCaseExpressionConstant == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, node.Location); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(gotoCaseExpressionOpt, diagnostics); // LabelSymbols for all the switch case labels are created by BuildLabels(). // Fetch the matching switch case label symbols matchedLabelSymbol = FindMatchingSwitchCaseLabel(gotoCaseExpressionConstant, node); } else { Debug.Assert(node.Kind() == SyntaxKind.GotoDefaultStatement); matchedLabelSymbol = GetDefaultLabel(); } if ((object)matchedLabelSymbol == null) { if (!hasErrors) { // No matching case label/default label found var labelName = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); if (node.Kind() == SyntaxKind.GotoCaseStatement) { labelName += " " + gotoCaseExpressionConstant.Value?.ToString(); } labelName += ":"; diagnostics.Add(ErrorCode.ERR_LabelNotFound, node.Location, labelName); hasErrors = true; } } else { return new BoundGotoStatement(node, matchedLabelSymbol, gotoCaseExpressionOpt, null, hasErrors); } } return new BoundBadStatement( syntax: node, childBoundNodes: gotoCaseExpressionOpt != null ? ImmutableArray.Create<BoundNode>(gotoCaseExpressionOpt) : ImmutableArray<BoundNode>.Empty, hasErrors: true); } #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.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SwitchBinder : LocalScopeBinder { protected readonly SwitchStatementSyntax SwitchSyntax; private readonly GeneratedLabelSymbol _breakLabel; private BoundExpression _switchGoverningExpression; private BindingDiagnosticBag _switchGoverningDiagnostics; private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) : base(next) { SwitchSyntax = switchSyntax; _breakLabel = new GeneratedLabelSymbol("break"); } protected bool PatternsEnabled => ((CSharpParseOptions)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) != false; protected BoundExpression SwitchGoverningExpression { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); Debug.Assert(_switchGoverningExpression != null); return _switchGoverningExpression; } } protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; protected uint SwitchGoverningValEscape => GetValEscape(SwitchGoverningExpression, LocalScopeDepth); protected BindingDiagnosticBag SwitchGoverningDiagnostics { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); return _switchGoverningDiagnostics; } } private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() { if (_switchGoverningExpression == null) { var switchGoverningDiagnostics = new BindingDiagnosticBag(); var boundSwitchExpression = BindSwitchGoverningExpression(switchGoverningDiagnostics); _switchGoverningDiagnostics = switchGoverningDiagnostics; Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null); } } // Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Default label(s) are indexed on a special DefaultKey object. // Invalid case labels with null constant value are indexed on the labelName. private Dictionary<object, SourceLabelSymbol> _lazySwitchLabelsMap; private static readonly object s_defaultKey = new object(); private Dictionary<object, SourceLabelSymbol> LabelsByValue { get { if (_lazySwitchLabelsMap == null && this.Labels.Length > 0) { _lazySwitchLabelsMap = BuildLabelsByValue(this.Labels); } return _lazySwitchLabelsMap; } } private static Dictionary<object, SourceLabelSymbol> BuildLabelsByValue(ImmutableArray<LabelSymbol> labels) { Debug.Assert(labels.Length > 0); var map = new Dictionary<object, SourceLabelSymbol>(labels.Length, new SwitchConstantValueHelper.SwitchLabelsComparer()); foreach (SourceLabelSymbol label in labels) { SyntaxKind labelKind = label.IdentifierNodeOrToken.Kind(); if (labelKind == SyntaxKind.IdentifierToken) { continue; } object key; var constantValue = label.SwitchCaseLabelConstant; if ((object)constantValue != null && !constantValue.IsBad) { // Case labels with a non-null constant value are indexed on their ConstantValue. key = KeyForConstant(constantValue); } else if (labelKind == SyntaxKind.DefaultSwitchLabel) { // Default label(s) are indexed on a special DefaultKey object. key = s_defaultKey; } else { // Invalid case labels with null constant value are indexed on the labelName. key = label.IdentifierNodeOrToken.AsNode(); } // If there is a duplicate label, ignore it. It will be reported when binding the switch label. if (!map.ContainsKey(key)) { map.Add(key, label); } } return map; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocals(section.Statements, GetBinder(section))); } return builder.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { var builder = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocalFunctions(section.Statements)); } return builder.ToImmutableAndFree(); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } internal override GeneratedLabelSymbol BreakLabel { get { return _breakLabel; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { // We bind the switch expression and the switch case label expressions so that the constant values can be // part of the label, but we do not report any diagnostics here. Diagnostics will be reported during binding. ArrayBuilder<LabelSymbol> labels = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { // add switch case/default labels BuildSwitchLabels(section.Labels, GetBinder(section), labels, BindingDiagnosticBag.Discarded); // add regular labels from the statements in the switch section BuildLabels(section.Statements, ref labels); } return labels.ToImmutableAndFree(); } internal override bool IsLabelsScopeBinder { get { return true; } } private void BuildSwitchLabels(SyntaxList<SwitchLabelSyntax> labelsSyntax, Binder sectionBinder, ArrayBuilder<LabelSymbol> labels, BindingDiagnosticBag tempDiagnosticBag) { // add switch case/default labels foreach (var labelSyntax in labelsSyntax) { ConstantValue boundLabelConstantOpt = null; switch (labelSyntax.Kind()) { case SyntaxKind.CaseSwitchLabel: // compute the constant value to place in the label symbol var caseLabel = (CaseSwitchLabelSyntax)labelSyntax; Debug.Assert(caseLabel.Value != null); var boundLabelExpression = sectionBinder.BindTypeOrRValue(caseLabel.Value, tempDiagnosticBag); if (boundLabelExpression is BoundTypeExpression type) { // Nothing to do at this point. The label will be bound later. } else { _ = ConvertCaseExpression(labelSyntax, boundLabelExpression, sectionBinder, out boundLabelConstantOpt, tempDiagnosticBag); } break; case SyntaxKind.CasePatternSwitchLabel: // bind the pattern, to cause its pattern variables to be inferred if necessary var matchLabel = (CasePatternSwitchLabelSyntax)labelSyntax; _ = sectionBinder.BindPattern( matchLabel.Pattern, SwitchGoverningType, SwitchGoverningValEscape, permitDesignations: true, labelSyntax.HasErrors, tempDiagnosticBag); break; default: // No constant value break; } // Create the label symbol labels.Add(new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, labelSyntax, boundLabelConstantOpt)); } } protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, Binder sectionBinder, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) { bool hasErrors = false; if (isGotoCaseExpr) { // SPEC VIOLATION for Dev10 COMPATIBILITY: // Dev10 compiler violates the SPEC comment below: // "if the constant-expression is not implicitly convertible (§6.1) to // the governing type of the nearest enclosing switch statement, // a compile-time error occurs" // If there is no implicit conversion from gotoCaseExpression to switchGoverningType, // but there exists an explicit conversion, Dev10 compiler generates a warning "WRN_GotoCaseShouldConvert" // instead of an error. See test "CS0469_NoImplicitConversionWarning". CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, caseExpression, SwitchGoverningType); hasErrors = true; } else if (!conversion.IsImplicit) { diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, node.Location, SwitchGoverningType); hasErrors = true; } caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); } return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics); } private static readonly object s_nullKey = new object(); protected static object KeyForConstant(ConstantValue constantValue) { Debug.Assert((object)constantValue != null); return constantValue.IsNull ? s_nullKey : constantValue.Value; } protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Invalid case labels (with null constant value) are indexed on the label syntax. object key; if ((object)constantValue != null && !constantValue.IsBad) { key = KeyForConstant(constantValue); } else { key = labelSyntax; } return FindMatchingSwitchLabel(key); } private SourceLabelSymbol GetDefaultLabel() { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Default label(s) are indexed on a special DefaultKey object. return FindMatchingSwitchLabel(s_defaultKey); } private SourceLabelSymbol FindMatchingSwitchLabel(object key) { Debug.Assert(key != null); var labelsMap = LabelsByValue; if (labelsMap != null) { SourceLabelSymbol label; if (labelsMap.TryGetValue(key, out label)) { Debug.Assert((object)label != null); return label; } } return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return SwitchSyntax; } } # region "Switch statement binding methods" // Bind the switch expression private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { // We are at present inside the switch binder, but the switch expression is not // bound in the context of the switch binder; it's bound in the context of the // enclosing binder. For example: // // class C { // int x; // void M() { // switch(x) { // case 1: // int x; // // The "x" in "switch(x)" refers to this.x, not the local x that is in scope inside the switch block. Debug.Assert(ScopeDesignator == SwitchSyntax); ExpressionSyntax node = SwitchSyntax.Expression; var binder = this.GetBinder(node); Debug.Assert(binder != null); var switchGoverningExpression = binder.BindRValueWithoutTargetType(node, diagnostics); var switchGoverningType = switchGoverningExpression.Type; if ((object)switchGoverningType != null && !switchGoverningType.IsErrorType()) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise if exactly one user-defined implicit conversion (§6.4) exists from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types, then the result is the switch governing type // SPEC: 3) Otherwise (in C# 7 and later) the switch governing type is the type of the // SPEC: switch expression. if (switchGoverningType.IsValidV6SwitchGoverningType()) { // Condition (1) satisfied // Note: dev11 actually checks the stripped type, but nullable was introduced at the same // time, so it doesn't really matter. if (switchGoverningType.SpecialType == SpecialType.System_Boolean) { CheckFeatureAvailability(node, MessageID.IDS_FeatureSwitchOnBool, diagnostics); } return switchGoverningExpression; } else { TypeSymbol resultantGoverningType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(switchGoverningType, out resultantGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (conversion.IsValid) { // Condition (2) satisfied Debug.Assert(conversion.Kind == ConversionKind.ImplicitUserDefined); Debug.Assert(conversion.Method.IsUserDefinedConversion()); Debug.Assert(conversion.UserDefinedToConversion.IsIdentity); Debug.Assert(resultantGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); return binder.CreateConversion(node, switchGoverningExpression, conversion, isCast: false, conversionGroupOpt: null, resultantGoverningType, diagnostics); } else if (!switchGoverningType.IsVoidType()) { // Otherwise (3) satisfied if (!PatternsEnabled) { diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, node.Location); } return switchGoverningExpression; } else { switchGoverningType = CreateErrorType(switchGoverningType.Name); } } } if (!switchGoverningExpression.HasAnyErrors) { Debug.Assert((object)switchGoverningExpression.Type == null || switchGoverningExpression.Type.IsVoidType()); diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, node.Location, switchGoverningExpression.Display); } return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(switchGoverningExpression), switchGoverningType ?? CreateErrorType()); } private Dictionary<SyntaxNode, LabelSymbol> _labelsByNode; protected Dictionary<SyntaxNode, LabelSymbol> LabelsByNode { get { if (_labelsByNode == null) { var result = new Dictionary<SyntaxNode, LabelSymbol>(); foreach (var label in Labels) { var node = ((SourceLabelSymbol)label).IdentifierNodeOrToken.AsNode(); if (node != null) { result.Add(node, label); } } _labelsByNode = result; } return _labelsByNode; } } internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement || node.Kind() == SyntaxKind.GotoDefaultStatement); BoundExpression gotoCaseExpressionOpt = null; // Prevent cascading diagnostics if (!node.HasErrors) { ConstantValue gotoCaseExpressionConstant = null; bool hasErrors = false; SourceLabelSymbol matchedLabelSymbol; // SPEC: If the goto case statement is not enclosed by a switch statement, if the constant-expression // SPEC: is not implicitly convertible (§6.1) to the governing type of the nearest enclosing switch statement, // SPEC: or if the nearest enclosing switch statement does not contain a case label with the given constant value, // SPEC: a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing // SPEC: switch statement does not contain a default label, a compile-time error occurs. if (node.Expression != null) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement); // Bind the goto case expression gotoCaseExpressionOpt = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); gotoCaseExpressionOpt = ConvertCaseExpression(node, gotoCaseExpressionOpt, gotoBinder, out gotoCaseExpressionConstant, diagnostics, isGotoCaseExpr: true); // Check for bind errors hasErrors = hasErrors || gotoCaseExpressionOpt.HasAnyErrors; if (!hasErrors && gotoCaseExpressionConstant == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, node.Location); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(gotoCaseExpressionOpt, diagnostics); // LabelSymbols for all the switch case labels are created by BuildLabels(). // Fetch the matching switch case label symbols matchedLabelSymbol = FindMatchingSwitchCaseLabel(gotoCaseExpressionConstant, node); } else { Debug.Assert(node.Kind() == SyntaxKind.GotoDefaultStatement); matchedLabelSymbol = GetDefaultLabel(); } if ((object)matchedLabelSymbol == null) { if (!hasErrors) { // No matching case label/default label found var labelName = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); if (node.Kind() == SyntaxKind.GotoCaseStatement) { labelName += " " + gotoCaseExpressionConstant.Value?.ToString(); } labelName += ":"; diagnostics.Add(ErrorCode.ERR_LabelNotFound, node.Location, labelName); hasErrors = true; } } else { return new BoundGotoStatement(node, matchedLabelSymbol, gotoCaseExpressionOpt, null, hasErrors); } } return new BoundBadStatement( syntax: node, childBoundNodes: gotoCaseExpressionOpt != null ? ImmutableArray.Create<BoundNode>(gotoCaseExpressionOpt) : ImmutableArray<BoundNode>.Empty, hasErrors: true); } #endregion } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Structure/Providers/FieldDeclarationStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class FieldDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<FieldDeclarationSyntax> { protected override void CollectBlockSpans( FieldDeclarationSyntax fieldDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(fieldDeclaration, ref spans, optionProvider); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class FieldDeclarationStructureProvider : AbstractSyntaxNodeStructureProvider<FieldDeclarationSyntax> { protected override void CollectBlockSpans( FieldDeclarationSyntax fieldDeclaration, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CSharpStructureHelpers.CollectCommentBlockSpans(fieldDeclaration, ref spans, optionProvider); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.FloatingTC.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { internal static partial class ValueSetFactory { /// <summary> /// A type class providing primitive operations needed to support a value set for a floating-point type. /// </summary> private interface FloatingTC<T> : INumericTC<T> { /// <summary> /// A "not a number" value for the floating-point type <typeparamref name="T"/>. /// All NaN values are treated as equivalent. /// </summary> T NaN { 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. namespace Microsoft.CodeAnalysis.CSharp { internal static partial class ValueSetFactory { /// <summary> /// A type class providing primitive operations needed to support a value set for a floating-point type. /// </summary> private interface FloatingTC<T> : INumericTC<T> { /// <summary> /// A "not a number" value for the floating-point type <typeparamref name="T"/>. /// All NaN values are treated as equivalent. /// </summary> T NaN { get; } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./docs/features/local-functions.work.md
Local Function Status ===================== This is a checklist for current and outstanding work on the local functions feature, as spec'd in [local-functions.md](./local-functions.md). -------------------- Known issues ============ Compiler: - [ ] Parser builds nodes for local functions when feature not enabled (#9940) - [ ] Compiler crash: base call to state machine method, in state machine method (#9872) - [ ] Need custom warning for unused local function (#9661) - [ ] Generate quick action does not offer to generate local (#9352) - [ ] Parser ambiguity research (#10388) - [ ] Dynamic support (#10389) - [ ] Referring to local function in expression tree (#10390) - [ ] Resolve definite assignment rules (#10391) - [ ] Remove support for `var` return type (#10392) - [ ] Update error messages (#10393) IDE: - [ ] Some selections around local functions fail extract method refactoring [ ] (#8719) - [ ] Extracting local function passed to an Action introduces compiler error [ ] (#8718) - [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717) - [ ] Inline temp introductes compiler error (#8716) - [ ] Call hierarchy search never terminates on local functions (#8654) - [ ] Nav bar doesn't support local functions (#8648) - [ ] No outlining for local functions (#8647) - [ ] Squiggles all over the place when using an unsupported modifier (#8645) - [ ] Peek definition errors out on local function (#8644) - [ ] Void keyword not recommended while declaring local function (#8616) - [ ] Change signature doesn't update the signature of the local function (#8539) Feature Completeness Progress ============================= - [x] N-level nested local functions - [x] Capture - Works alongside lambdas and behaves very similarly in fallback cases - Has zero-allocation closures (struct frames by ref) on functions never converted to a delegate and are not an iterator/async - [x] Standard parameter features - params - ref/out - named/optional - [x] Visibility - May revisit design (currently shadows, may do overloads) - [x] Generics - Nongeneric local functions in generic methods (same as lambdas). - Generic local functions in nongeneric methods. - Generic local functions in generic methods. - Arbitrary nesting of generic local functions. - Generic local functions with constraints. - [x] Inferred return type - [x] Iterators - [x] Async
Local Function Status ===================== This is a checklist for current and outstanding work on the local functions feature, as spec'd in [local-functions.md](./local-functions.md). -------------------- Known issues ============ Compiler: - [ ] Parser builds nodes for local functions when feature not enabled (#9940) - [ ] Compiler crash: base call to state machine method, in state machine method (#9872) - [ ] Need custom warning for unused local function (#9661) - [ ] Generate quick action does not offer to generate local (#9352) - [ ] Parser ambiguity research (#10388) - [ ] Dynamic support (#10389) - [ ] Referring to local function in expression tree (#10390) - [ ] Resolve definite assignment rules (#10391) - [ ] Remove support for `var` return type (#10392) - [ ] Update error messages (#10393) IDE: - [ ] Some selections around local functions fail extract method refactoring [ ] (#8719) - [ ] Extracting local function passed to an Action introduces compiler error [ ] (#8718) - [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717) - [ ] Inline temp introductes compiler error (#8716) - [ ] Call hierarchy search never terminates on local functions (#8654) - [ ] Nav bar doesn't support local functions (#8648) - [ ] No outlining for local functions (#8647) - [ ] Squiggles all over the place when using an unsupported modifier (#8645) - [ ] Peek definition errors out on local function (#8644) - [ ] Void keyword not recommended while declaring local function (#8616) - [ ] Change signature doesn't update the signature of the local function (#8539) Feature Completeness Progress ============================= - [x] N-level nested local functions - [x] Capture - Works alongside lambdas and behaves very similarly in fallback cases - Has zero-allocation closures (struct frames by ref) on functions never converted to a delegate and are not an iterator/async - [x] Standard parameter features - params - ref/out - named/optional - [x] Visibility - May revisit design (currently shadows, may do overloads) - [x] Generics - Nongeneric local functions in generic methods (same as lambdas). - Generic local functions in nongeneric methods. - Generic local functions in generic methods. - Arbitrary nesting of generic local functions. - Generic local functions with constraints. - [x] Inferred return type - [x] Iterators - [x] Async
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Library/VsNavInfo/NavInfoNodeEnum.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo { internal class NavInfoNodeEnum : IVsEnumNavInfoNodes { private readonly ImmutableArray<NavInfoNode> _nodes; private int _index; public NavInfoNodeEnum(ImmutableArray<NavInfoNode> nodes) => _nodes = nodes; public int Clone(out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NavInfoNodeEnum(_nodes); return VSConstants.S_OK; } public int Next(uint celt, IVsNavInfoNode[] rgelt, out uint pceltFetched) { var i = 0; for (; i < celt && _index < _nodes.Length; i++, _index++) { rgelt[i] = _nodes[_index]; } pceltFetched = (uint)i; return i < celt ? VSConstants.S_FALSE : VSConstants.S_OK; } public int Reset() { _index = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _index += (int)celt; return VSConstants.S_OK; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.VsNavInfo { internal class NavInfoNodeEnum : IVsEnumNavInfoNodes { private readonly ImmutableArray<NavInfoNode> _nodes; private int _index; public NavInfoNodeEnum(ImmutableArray<NavInfoNode> nodes) => _nodes = nodes; public int Clone(out IVsEnumNavInfoNodes ppEnum) { ppEnum = new NavInfoNodeEnum(_nodes); return VSConstants.S_OK; } public int Next(uint celt, IVsNavInfoNode[] rgelt, out uint pceltFetched) { var i = 0; for (; i < celt && _index < _nodes.Length; i++, _index++) { rgelt[i] = _nodes[_index]; } pceltFetched = (uint)i; return i < celt ? VSConstants.S_FALSE : VSConstants.S_OK; } public int Reset() { _index = 0; return VSConstants.S_OK; } public int Skip(uint celt) { _index += (int)celt; return VSConstants.S_OK; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicOrganizing.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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicOrganizing : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicOrganizing(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicOrganizing)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)] public void RemoveAndSort() { SetUpEditor(@"Imports System.Linq$$ Imports System Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices Class Test Sub Method(<CallerMemberName> Optional str As String = Nothing) Dim data As COMException End Sub End Class"); VisualStudio.ExecuteCommand("Edit.RemoveAndSort"); VisualStudio.Editor.Verify.TextContains(@"Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Class Test Sub Method(<CallerMemberName> Optional str As String = Nothing) Dim data As COMException End Sub End Class"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicOrganizing : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicOrganizing(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicOrganizing)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Organizing)] public void RemoveAndSort() { SetUpEditor(@"Imports System.Linq$$ Imports System Imports System.Runtime.InteropServices Imports System.Runtime.CompilerServices Class Test Sub Method(<CallerMemberName> Optional str As String = Nothing) Dim data As COMException End Sub End Class"); VisualStudio.ExecuteCommand("Edit.RemoveAndSort"); VisualStudio.Editor.Verify.TextContains(@"Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Class Test Sub Method(<CallerMemberName> Optional str As String = Nothing) Dim data As COMException End Sub End Class"); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons_Constants.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; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial struct InvocationReasons { public static readonly InvocationReasons DocumentAdded = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentAdded, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons DocumentRemoved = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentRemoved, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged, PredefinedInvocationReasons.HighPriority)); public static readonly InvocationReasons ProjectParseOptionChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.ProjectParseOptionsChanged, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons ProjectConfigurationChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.ProjectConfigurationChanged, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons SolutionRemoved = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SolutionRemoved, PredefinedInvocationReasons.DocumentRemoved)); public static readonly InvocationReasons DocumentOpened = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentOpened, PredefinedInvocationReasons.HighPriority)); public static readonly InvocationReasons DocumentClosed = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentClosed, PredefinedInvocationReasons.HighPriority)); public static readonly InvocationReasons DocumentChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons AdditionalDocumentChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons SyntaxChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SyntaxChanged)); public static readonly InvocationReasons SemanticChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons Reanalyze = new(PredefinedInvocationReasons.Reanalyze); public static readonly InvocationReasons ReanalyzeHighPriority = Reanalyze.With(PredefinedInvocationReasons.HighPriority); } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial struct InvocationReasons { public static readonly InvocationReasons DocumentAdded = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentAdded, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons DocumentRemoved = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentRemoved, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged, PredefinedInvocationReasons.HighPriority)); public static readonly InvocationReasons ProjectParseOptionChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.ProjectParseOptionsChanged, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons ProjectConfigurationChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.ProjectConfigurationChanged, PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons SolutionRemoved = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SolutionRemoved, PredefinedInvocationReasons.DocumentRemoved)); public static readonly InvocationReasons DocumentOpened = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentOpened, PredefinedInvocationReasons.HighPriority)); public static readonly InvocationReasons DocumentClosed = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.DocumentClosed, PredefinedInvocationReasons.HighPriority)); public static readonly InvocationReasons DocumentChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons AdditionalDocumentChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SyntaxChanged, PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons SyntaxChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SyntaxChanged)); public static readonly InvocationReasons SemanticChanged = new( ImmutableHashSet.Create<string>( PredefinedInvocationReasons.SemanticChanged)); public static readonly InvocationReasons Reanalyze = new(PredefinedInvocationReasons.Reanalyze); public static readonly InvocationReasons ReanalyzeHighPriority = Reanalyze.With(PredefinedInvocationReasons.HighPriority); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/LiveShare/Impl/LiveShareConstants.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.VisualStudio.LanguageServices.LiveShare { internal class LiveShareConstants { // The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client public const string RoslynContractName = "Roslyn"; // The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client public const string RoslynLSPSDKContractName = "RoslynLSPSDK"; public const string TypeScriptLanguageName = "TypeScript"; public const string CSharpContractName = "CSharp"; public const string VisualBasicContractName = "VisualBasic"; public const string TypeScriptContractName = "TypeScript"; } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.LiveShare { internal class LiveShareConstants { // The service name for an LSP server implemented using Roslyn designed to be used with the Roslyn client public const string RoslynContractName = "Roslyn"; // The service name for an LSP server implemented using Roslyn designed to be used with the LSP SDK client public const string RoslynLSPSDKContractName = "RoslynLSPSDK"; public const string TypeScriptLanguageName = "TypeScript"; public const string CSharpContractName = "CSharp"; public const string VisualBasicContractName = "VisualBasic"; public const string TypeScriptContractName = "TypeScript"; } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Compilation/SpeculativeSyntaxTreeSemanticModel.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Allows asking semantic questions about a tree of syntax nodes that did not appear in the original source code. ''' Typically, an instance is obtained by a call to SemanticModel.TryGetSpeculativeSemanticModel. ''' </summary> Friend NotInheritable Class SpeculativeSyntaxTreeSemanticModel Inherits SyntaxTreeSemanticModel Private ReadOnly _parentSemanticModel As SyntaxTreeSemanticModel Private ReadOnly _root As ExpressionSyntax Private ReadOnly _rootBinder As Binder Private ReadOnly _position As Integer Private ReadOnly _bindingOption As SpeculativeBindingOption Public Shared Function Create(parentSemanticModel As SyntaxTreeSemanticModel, root As ExpressionSyntax, binder As Binder, position As Integer, bindingOption As SpeculativeBindingOption) As SpeculativeSyntaxTreeSemanticModel Debug.Assert(parentSemanticModel IsNot Nothing) Debug.Assert(root IsNot Nothing) Debug.Assert(binder IsNot Nothing) Debug.Assert(binder.IsSemanticModelBinder) Return New SpeculativeSyntaxTreeSemanticModel(parentSemanticModel, root, binder, position, bindingOption) End Function Private Sub New(parentSemanticModel As SyntaxTreeSemanticModel, root As ExpressionSyntax, binder As Binder, position As Integer, bindingOption As SpeculativeBindingOption) MyBase.New(parentSemanticModel.Compilation, DirectCast(parentSemanticModel.Compilation.SourceModule, SourceModuleSymbol), root.SyntaxTree) _parentSemanticModel = parentSemanticModel _root = root _rootBinder = binder _position = position _bindingOption = bindingOption End Sub Public Overrides ReadOnly Property IsSpeculativeSemanticModel As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property OriginalPositionForSpeculation As Integer Get Return Me._position End Get End Property Public Overrides ReadOnly Property ParentModel As SemanticModel Get Return Me._parentSemanticModel End Get End Property Friend Overrides ReadOnly Property Root As SyntaxNode Get Return _root End Get End Property Public Overrides ReadOnly Property SyntaxTree As SyntaxTree Get Return _root.SyntaxTree End Get End Property Friend Overrides Function Bind(binder As Binder, node As SyntaxNode, diagnostics As BindingDiagnosticBag) As BoundNode Return _parentSemanticModel.Bind(binder, node, diagnostics) End Function Friend Overrides Function GetEnclosingBinder(position As Integer) As Binder Return _rootBinder End Function Private Function GetSpeculativeBindingOption(node As ExpressionSyntax) As SpeculativeBindingOption If SyntaxFacts.IsInNamespaceOrTypeContext(node) Then Return SpeculativeBindingOption.BindAsTypeOrNamespace End If Return _bindingOption End Function Friend Overrides Function GetExpressionSymbolInfo(node As ExpressionSyntax, options As VBSemanticModel.SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo If (options And VBSemanticModel.SymbolInfoOptions.PreserveAliases) <> 0 Then Debug.Assert(TypeOf node Is IdentifierNameSyntax) Dim aliasSymbol = _parentSemanticModel.GetSpeculativeAliasInfo(_position, DirectCast(node, IdentifierNameSyntax), Me.GetSpeculativeBindingOption(node)) Return SymbolInfoFactory.Create(ImmutableArray.Create(Of ISymbol)(aliasSymbol), If(aliasSymbol IsNot Nothing, LookupResultKind.Good, LookupResultKind.Empty)) End If Return _parentSemanticModel.GetSpeculativeSymbolInfo(_position, node, Me.GetSpeculativeBindingOption(node)) End Function Friend Overrides Function GetExpressionTypeInfo(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo Return _parentSemanticModel.GetSpeculativeTypeInfoWorker(_position, node, Me.GetSpeculativeBindingOption(node)) End Function Friend Overrides Function GetExpressionMemberGroup(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol) Return _parentSemanticModel.GetExpressionMemberGroup(node, cancellationToken) End Function Friend Overrides Function GetExpressionConstantValue(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ConstantValue Return _parentSemanticModel.GetExpressionConstantValue(node, cancellationToken) End Function Public Overrides Function GetSyntaxDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Throw New NotSupportedException() End Function Public Overrides Function GetDeclarationDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Throw New NotSupportedException() End Function Public Overrides Function GetDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Throw New NotSupportedException() 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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ''' <summary> ''' Allows asking semantic questions about a tree of syntax nodes that did not appear in the original source code. ''' Typically, an instance is obtained by a call to SemanticModel.TryGetSpeculativeSemanticModel. ''' </summary> Friend NotInheritable Class SpeculativeSyntaxTreeSemanticModel Inherits SyntaxTreeSemanticModel Private ReadOnly _parentSemanticModel As SyntaxTreeSemanticModel Private ReadOnly _root As ExpressionSyntax Private ReadOnly _rootBinder As Binder Private ReadOnly _position As Integer Private ReadOnly _bindingOption As SpeculativeBindingOption Public Shared Function Create(parentSemanticModel As SyntaxTreeSemanticModel, root As ExpressionSyntax, binder As Binder, position As Integer, bindingOption As SpeculativeBindingOption) As SpeculativeSyntaxTreeSemanticModel Debug.Assert(parentSemanticModel IsNot Nothing) Debug.Assert(root IsNot Nothing) Debug.Assert(binder IsNot Nothing) Debug.Assert(binder.IsSemanticModelBinder) Return New SpeculativeSyntaxTreeSemanticModel(parentSemanticModel, root, binder, position, bindingOption) End Function Private Sub New(parentSemanticModel As SyntaxTreeSemanticModel, root As ExpressionSyntax, binder As Binder, position As Integer, bindingOption As SpeculativeBindingOption) MyBase.New(parentSemanticModel.Compilation, DirectCast(parentSemanticModel.Compilation.SourceModule, SourceModuleSymbol), root.SyntaxTree) _parentSemanticModel = parentSemanticModel _root = root _rootBinder = binder _position = position _bindingOption = bindingOption End Sub Public Overrides ReadOnly Property IsSpeculativeSemanticModel As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property OriginalPositionForSpeculation As Integer Get Return Me._position End Get End Property Public Overrides ReadOnly Property ParentModel As SemanticModel Get Return Me._parentSemanticModel End Get End Property Friend Overrides ReadOnly Property Root As SyntaxNode Get Return _root End Get End Property Public Overrides ReadOnly Property SyntaxTree As SyntaxTree Get Return _root.SyntaxTree End Get End Property Friend Overrides Function Bind(binder As Binder, node As SyntaxNode, diagnostics As BindingDiagnosticBag) As BoundNode Return _parentSemanticModel.Bind(binder, node, diagnostics) End Function Friend Overrides Function GetEnclosingBinder(position As Integer) As Binder Return _rootBinder End Function Private Function GetSpeculativeBindingOption(node As ExpressionSyntax) As SpeculativeBindingOption If SyntaxFacts.IsInNamespaceOrTypeContext(node) Then Return SpeculativeBindingOption.BindAsTypeOrNamespace End If Return _bindingOption End Function Friend Overrides Function GetExpressionSymbolInfo(node As ExpressionSyntax, options As VBSemanticModel.SymbolInfoOptions, Optional cancellationToken As CancellationToken = Nothing) As SymbolInfo If (options And VBSemanticModel.SymbolInfoOptions.PreserveAliases) <> 0 Then Debug.Assert(TypeOf node Is IdentifierNameSyntax) Dim aliasSymbol = _parentSemanticModel.GetSpeculativeAliasInfo(_position, DirectCast(node, IdentifierNameSyntax), Me.GetSpeculativeBindingOption(node)) Return SymbolInfoFactory.Create(ImmutableArray.Create(Of ISymbol)(aliasSymbol), If(aliasSymbol IsNot Nothing, LookupResultKind.Good, LookupResultKind.Empty)) End If Return _parentSemanticModel.GetSpeculativeSymbolInfo(_position, node, Me.GetSpeculativeBindingOption(node)) End Function Friend Overrides Function GetExpressionTypeInfo(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As VisualBasicTypeInfo Return _parentSemanticModel.GetSpeculativeTypeInfoWorker(_position, node, Me.GetSpeculativeBindingOption(node)) End Function Friend Overrides Function GetExpressionMemberGroup(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Symbol) Return _parentSemanticModel.GetExpressionMemberGroup(node, cancellationToken) End Function Friend Overrides Function GetExpressionConstantValue(node As ExpressionSyntax, Optional cancellationToken As CancellationToken = Nothing) As ConstantValue Return _parentSemanticModel.GetExpressionConstantValue(node, cancellationToken) End Function Public Overrides Function GetSyntaxDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Throw New NotSupportedException() End Function Public Overrides Function GetDeclarationDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Throw New NotSupportedException() End Function Public Overrides Function GetDiagnostics(Optional span As TextSpan? = Nothing, Optional cancellationToken As CancellationToken = Nothing) As ImmutableArray(Of Diagnostic) Throw New NotSupportedException() End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/BoundTree/BoundSpillSequence.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundSpillSequence { public BoundSpillSequence( SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundExpression> sideEffects, BoundExpression value, TypeSymbol type, bool hasErrors = false) : this(syntax, locals, MakeStatements(sideEffects), value, type, hasErrors) { } private static ImmutableArray<BoundStatement> MakeStatements(ImmutableArray<BoundExpression> expressions) { return expressions.SelectAsArray<BoundExpression, BoundStatement>( expression => new BoundExpressionStatement(expression.Syntax, expression, expression.HasErrors)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal partial class BoundSpillSequence { public BoundSpillSequence( SyntaxNode syntax, ImmutableArray<LocalSymbol> locals, ImmutableArray<BoundExpression> sideEffects, BoundExpression value, TypeSymbol type, bool hasErrors = false) : this(syntax, locals, MakeStatements(sideEffects), value, type, hasErrors) { } private static ImmutableArray<BoundStatement> MakeStatements(ImmutableArray<BoundExpression> expressions) { return expressions.SelectAsArray<BoundExpression, BoundStatement>( expression => new BoundExpressionStatement(expression.Syntax, expression, expression.HasErrors)); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Host/Mef/IWorkspaceServiceFactory.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.Host.Mef { /// <summary> /// A factory that creates instances of a specific <see cref="IWorkspaceService"/>. /// /// Implement a <see cref="IWorkspaceServiceFactory"/> when you want to provide <see cref="IWorkspaceService"/> instances that use other services. /// </summary> public interface IWorkspaceServiceFactory { /// <summary> /// Creates a new <see cref="IWorkspaceService"/> instance. /// Returns <c>null</c> if the service is not applicable to the given workspace. /// </summary> /// <param name="workspaceServices">The <see cref="HostWorkspaceServices"/> that can be used to access other services.</param> IWorkspaceService CreateService(HostWorkspaceServices workspaceServices); } }
// Licensed to the .NET Foundation under one or more 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.Host.Mef { /// <summary> /// A factory that creates instances of a specific <see cref="IWorkspaceService"/>. /// /// Implement a <see cref="IWorkspaceServiceFactory"/> when you want to provide <see cref="IWorkspaceService"/> instances that use other services. /// </summary> public interface IWorkspaceServiceFactory { /// <summary> /// Creates a new <see cref="IWorkspaceService"/> instance. /// Returns <c>null</c> if the service is not applicable to the given workspace. /// </summary> /// <param name="workspaceServices">The <see cref="HostWorkspaceServices"/> that can be used to access other services.</param> IWorkspaceService CreateService(HostWorkspaceServices workspaceServices); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/Model/AbstractNode.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.Xml.Serialization; namespace CSharpSyntaxGenerator { public class AbstractNode : TreeType { public readonly List<Field> Fields = new List<Field>(); } }
// Licensed to the .NET Foundation under one or more 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.Xml.Serialization; namespace CSharpSyntaxGenerator { public class AbstractNode : TreeType { public readonly List<Field> Fields = new List<Field>(); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest2/Recommendations/VoidKeywordRecommenderTests.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 VoidKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"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 TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType2(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInTypeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [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 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 TestAfterMultipleRootAttributes() { await VerifyKeywordAsync(@"[goo][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 TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPartial() { await VerifyKeywordAsync( @"class C { 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 TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { 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 TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { 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 TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { 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 TestAfterStaticInClass() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() { await VerifyKeywordAsync( @"delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInUnsafeBlock(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeMethod() { await VerifyKeywordAsync( @"class C { unsafe void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeClass() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameter() { await VerifyAbsenceAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter1() { await VerifyKeywordAsync( @"class C { unsafe void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter2() { await VerifyKeywordAsync( @"unsafe class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast2() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast2() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConversionOperator() { await VerifyKeywordAsync( @"class C { unsafe implicit operator int(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeOperator() { await VerifyKeywordAsync( @"class C { unsafe int operator ++(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConstructor() { await VerifyKeywordAsync( @"class C { unsafe C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDestructor() { await VerifyKeywordAsync( @"class C { unsafe ~C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeProperty() { await VerifyKeywordAsync( @"class C { unsafe int Goo { get { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeIndexer() { await VerifyKeywordAsync( @"class C { unsafe int this[int i] { get { $$"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInDefault(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInSizeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDefaultExpression() { await VerifyKeywordAsync( @"unsafe class C { static void Method1(void* p1 = default($$"); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefaultExpression() { await VerifyAbsenceAsync( @"class C { static void Method1(void* p1 = default($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction() { await VerifyKeywordAsync(@" class C { void M() { $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction2() { await VerifyKeywordAsync(@" class C { void M() { async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction3() { await VerifyAbsenceAsync(@" class C { void M() { async async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction4() { await VerifyAbsenceAsync(@" class C { void M() { var async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction5() { await VerifyAbsenceAsync(@" using System; class C { void M(Action<int> a) { M(async $$ () => } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction6() { await VerifyKeywordAsync(@" class C { void M() { unsafe async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction7() { await VerifyKeywordAsync(@" using System; class C { void M(Action<int> a) { M(async () => { async $$ }) } }"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer01() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer02() { await VerifyKeywordAsync(@" class C<T> { C<delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer03() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer04() { await VerifyKeywordAsync(@" class C { delegate*<int, v$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestAfterReadonlyInStruct() { await VerifyKeywordAsync(@" struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonlyInRecordStruct() { await VerifyKeywordAsync(@" record struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestNotAfterReadonlyInClass() { await VerifyAbsenceAsync(@" class C { public readonly $$"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #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 VoidKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot() { await VerifyKeywordAsync( @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass() { await VerifyKeywordAsync( @"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 TestNotAfterStackAlloc() { await VerifyAbsenceAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInCastType2(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var str = (($$)items) as string;", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInTypeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [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 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 TestAfterMultipleRootAttributes() { await VerifyKeywordAsync(@"[goo][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 TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPartial() { await VerifyKeywordAsync( @"class C { 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 TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterInternal() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterInternal_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"internal $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPrivate() { await VerifyAbsenceAsync(SourceCodeKind.Regular, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterPrivate_Script() { await VerifyKeywordAsync(SourceCodeKind.Script, @"private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { 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 TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { 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 TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { 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 TestAfterStaticInClass() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterStaticPublic() => await VerifyAbsenceAsync(SourceCodeKind.Regular, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStaticPublic_Interactive() => await VerifyKeywordAsync(SourceCodeKind.Script, @"static public $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegate() { await VerifyKeywordAsync( @"delegate $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotAfterAnonymousDelegate(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"var q = delegate $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterEvent() { await VerifyAbsenceAsync( @"class C { event $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterVoid() { await VerifyAbsenceAsync( @"class C { void $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNew() { await VerifyAbsenceAsync( @"new $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedNew() { await VerifyKeywordAsync( @"class C { new $$"); } [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInUnsafeBlock(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"unsafe { $$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeMethod() { await VerifyKeywordAsync( @"class C { unsafe void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeClass() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInParameter() { await VerifyAbsenceAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter1() { await VerifyKeywordAsync( @"class C { unsafe void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeParameter2() { await VerifyKeywordAsync( @"unsafe class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCast2() { await VerifyAbsenceAsync( @"class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeCast2() { await VerifyKeywordAsync( @"unsafe class C { void Goo() { hr = GetRealProcAddress(""CompareAssemblyIdentity"", ($$**)pfnCompareAssemblyIdentity);"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConversionOperator() { await VerifyKeywordAsync( @"class C { unsafe implicit operator int(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeOperator() { await VerifyKeywordAsync( @"class C { unsafe int operator ++(C c) { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeConstructor() { await VerifyKeywordAsync( @"class C { unsafe C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDestructor() { await VerifyKeywordAsync( @"class C { unsafe ~C() { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeProperty() { await VerifyKeywordAsync( @"class C { unsafe int Goo { get { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeIndexer() { await VerifyKeywordAsync( @"class C { unsafe int this[int i] { get { $$"); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestNotInDefault(bool topLevelStatement) { await VerifyAbsenceAsync(AddInsideMethod( @"default($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [CombinatorialData] public async Task TestInSizeOf(bool topLevelStatement) { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$", topLevelStatement: topLevelStatement), options: CSharp9ParseOptions); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUnsafeDefaultExpression() { await VerifyKeywordAsync( @"unsafe class C { static void Method1(void* p1 = default($$"); } [WorkItem(544347, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544347")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInDefaultExpression() { await VerifyAbsenceAsync( @"class C { static void Method1(void* p1 = default($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterAsyncAsType() => await VerifyAbsenceAsync(@"class c { async async $$ }"); [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction() { await VerifyKeywordAsync(@" class C { void M() { $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [WorkItem(14525, "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction2() { await VerifyKeywordAsync(@" class C { void M() { async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction3() { await VerifyAbsenceAsync(@" class C { void M() { async async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction4() { await VerifyAbsenceAsync(@" class C { void M() { var async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction5() { await VerifyAbsenceAsync(@" using System; class C { void M(Action<int> a) { M(async $$ () => } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction6() { await VerifyKeywordAsync(@" class C { void M() { unsafe async $$ } }"); } [Fact] [WorkItem(8617, "https://github.com/dotnet/roslyn/issues/8617")] [CompilerTrait(CompilerFeature.LocalFunctions)] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestLocalFunction7() { await VerifyKeywordAsync(@" using System; class C { void M(Action<int> a) { M(async () => { async $$ }) } }"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer01() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer02() { await VerifyKeywordAsync(@" class C<T> { C<delegate*<$$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer03() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact] [Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointer04() { await VerifyKeywordAsync(@" class C { delegate*<int, v$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestAfterReadonlyInStruct() { await VerifyKeywordAsync(@" struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterReadonlyInRecordStruct() { await VerifyKeywordAsync(@" record struct S { public readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [WorkItem(43295, "https://github.com/dotnet/roslyn/issues/43295")] public async Task TestNotAfterReadonlyInClass() { await VerifyAbsenceAsync(@" class C { public readonly $$"); } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Text/Shared/Extensions/ITextSnapshotExtensions.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.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text.Shared.Extensions { internal static partial class ITextSnapshotExtensions { public static SnapshotPoint GetPoint(this ITextSnapshot snapshot, int position) => new SnapshotPoint(snapshot, position); public static SnapshotPoint? TryGetPoint(this ITextSnapshot snapshot, int lineNumber, int columnIndex) { var position = snapshot.TryGetPosition(lineNumber, columnIndex); if (position.HasValue) { return new SnapshotPoint(snapshot, position.Value); } else { return null; } } /// <summary> /// Convert a <see cref="LinePositionSpan"/> to <see cref="TextSpan"/>. /// </summary> public static TextSpan GetTextSpan(this ITextSnapshot snapshot, LinePositionSpan span) { return TextSpan.FromBounds( GetPosition(snapshot, span.Start.Line, span.Start.Character), GetPosition(snapshot, span.End.Line, span.End.Character)); } public static int GetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) => TryGetPosition(snapshot, lineNumber, columnIndex) ?? throw new InvalidOperationException(TextEditorResources.The_snapshot_does_not_contain_the_specified_position); public static int? TryGetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) { if (lineNumber < 0 || lineNumber >= snapshot.LineCount) { return null; } var end = snapshot.GetLineFromLineNumber(lineNumber).Start.Position + columnIndex; if (end < 0 || end > snapshot.Length) { return null; } return end; } public static bool TryGetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex, out SnapshotPoint position) { position = new SnapshotPoint(); if (lineNumber < 0 || lineNumber >= snapshot.LineCount) { return false; } var line = snapshot.GetLineFromLineNumber(lineNumber); if (columnIndex < 0 || columnIndex >= line.Length) { return false; } var result = line.Start.Position + columnIndex; position = new SnapshotPoint(snapshot, result); return true; } public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int start, int length) => new SnapshotSpan(snapshot, new Span(start, length)); public static SnapshotSpan GetSpanFromBounds(this ITextSnapshot snapshot, int start, int end) => new SnapshotSpan(snapshot, Span.FromBounds(start, end)); public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, Span span) => new SnapshotSpan(snapshot, span); public static ITagSpan<TTag> GetTagSpan<TTag>(this ITextSnapshot snapshot, Span span, TTag tag) where TTag : ITag { return new TagSpan<TTag>(new SnapshotSpan(snapshot, span), tag); } public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) => TryGetSpan(snapshot, startLine, startIndex, endLine, endIndex) ?? throw new InvalidOperationException(TextEditorResources.The_snapshot_does_not_contain_the_specified_span); public static SnapshotSpan? TryGetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) { var startPosition = snapshot.TryGetPosition(startLine, startIndex); var endPosition = snapshot.TryGetPosition(endLine, endIndex); if (startPosition == null || endPosition == null) { return null; } return new SnapshotSpan(snapshot, Span.FromBounds(startPosition.Value, endPosition.Value)); } public static SnapshotSpan GetFullSpan(this ITextSnapshot snapshot) { Contract.ThrowIfNull(snapshot); return new SnapshotSpan(snapshot, new Span(0, snapshot.Length)); } public static NormalizedSnapshotSpanCollection GetSnapshotSpanCollection(this ITextSnapshot snapshot) { Contract.ThrowIfNull(snapshot); return new NormalizedSnapshotSpanCollection(snapshot.GetFullSpan()); } public static void GetLineAndCharacter(this ITextSnapshot snapshot, int position, out int lineNumber, out int characterIndex) { var line = snapshot.GetLineFromPosition(position); lineNumber = line.LineNumber; characterIndex = position - line.Start.Position; } /// <summary> /// Returns the leading whitespace of the line located at the specified position in the given snapshot. /// </summary> public static string GetLeadingWhitespaceOfLineAtPosition(this ITextSnapshot snapshot, int position) { Contract.ThrowIfNull(snapshot); var line = snapshot.GetLineFromPosition(position); var linePosition = line.GetFirstNonWhitespacePosition(); if (!linePosition.HasValue) { return line.GetText(); } var lineText = line.GetText(); return lineText.Substring(0, linePosition.Value - line.Start); } public static bool AreOnSameLine(this ITextSnapshot snapshot, int x1, int x2) => snapshot.GetLineNumberFromPosition(x1) == snapshot.GetLineNumberFromPosition(x2); } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text.Shared.Extensions { internal static partial class ITextSnapshotExtensions { public static SnapshotPoint GetPoint(this ITextSnapshot snapshot, int position) => new SnapshotPoint(snapshot, position); public static SnapshotPoint? TryGetPoint(this ITextSnapshot snapshot, int lineNumber, int columnIndex) { var position = snapshot.TryGetPosition(lineNumber, columnIndex); if (position.HasValue) { return new SnapshotPoint(snapshot, position.Value); } else { return null; } } /// <summary> /// Convert a <see cref="LinePositionSpan"/> to <see cref="TextSpan"/>. /// </summary> public static TextSpan GetTextSpan(this ITextSnapshot snapshot, LinePositionSpan span) { return TextSpan.FromBounds( GetPosition(snapshot, span.Start.Line, span.Start.Character), GetPosition(snapshot, span.End.Line, span.End.Character)); } public static int GetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) => TryGetPosition(snapshot, lineNumber, columnIndex) ?? throw new InvalidOperationException(TextEditorResources.The_snapshot_does_not_contain_the_specified_position); public static int? TryGetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex) { if (lineNumber < 0 || lineNumber >= snapshot.LineCount) { return null; } var end = snapshot.GetLineFromLineNumber(lineNumber).Start.Position + columnIndex; if (end < 0 || end > snapshot.Length) { return null; } return end; } public static bool TryGetPosition(this ITextSnapshot snapshot, int lineNumber, int columnIndex, out SnapshotPoint position) { position = new SnapshotPoint(); if (lineNumber < 0 || lineNumber >= snapshot.LineCount) { return false; } var line = snapshot.GetLineFromLineNumber(lineNumber); if (columnIndex < 0 || columnIndex >= line.Length) { return false; } var result = line.Start.Position + columnIndex; position = new SnapshotPoint(snapshot, result); return true; } public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int start, int length) => new SnapshotSpan(snapshot, new Span(start, length)); public static SnapshotSpan GetSpanFromBounds(this ITextSnapshot snapshot, int start, int end) => new SnapshotSpan(snapshot, Span.FromBounds(start, end)); public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, Span span) => new SnapshotSpan(snapshot, span); public static ITagSpan<TTag> GetTagSpan<TTag>(this ITextSnapshot snapshot, Span span, TTag tag) where TTag : ITag { return new TagSpan<TTag>(new SnapshotSpan(snapshot, span), tag); } public static SnapshotSpan GetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) => TryGetSpan(snapshot, startLine, startIndex, endLine, endIndex) ?? throw new InvalidOperationException(TextEditorResources.The_snapshot_does_not_contain_the_specified_span); public static SnapshotSpan? TryGetSpan(this ITextSnapshot snapshot, int startLine, int startIndex, int endLine, int endIndex) { var startPosition = snapshot.TryGetPosition(startLine, startIndex); var endPosition = snapshot.TryGetPosition(endLine, endIndex); if (startPosition == null || endPosition == null) { return null; } return new SnapshotSpan(snapshot, Span.FromBounds(startPosition.Value, endPosition.Value)); } public static SnapshotSpan GetFullSpan(this ITextSnapshot snapshot) { Contract.ThrowIfNull(snapshot); return new SnapshotSpan(snapshot, new Span(0, snapshot.Length)); } public static NormalizedSnapshotSpanCollection GetSnapshotSpanCollection(this ITextSnapshot snapshot) { Contract.ThrowIfNull(snapshot); return new NormalizedSnapshotSpanCollection(snapshot.GetFullSpan()); } public static void GetLineAndCharacter(this ITextSnapshot snapshot, int position, out int lineNumber, out int characterIndex) { var line = snapshot.GetLineFromPosition(position); lineNumber = line.LineNumber; characterIndex = position - line.Start.Position; } /// <summary> /// Returns the leading whitespace of the line located at the specified position in the given snapshot. /// </summary> public static string GetLeadingWhitespaceOfLineAtPosition(this ITextSnapshot snapshot, int position) { Contract.ThrowIfNull(snapshot); var line = snapshot.GetLineFromPosition(position); var linePosition = line.GetFirstNonWhitespacePosition(); if (!linePosition.HasValue) { return line.GetText(); } var lineText = line.GetText(); return lineText.Substring(0, linePosition.Value - line.Start); } public static bool AreOnSameLine(this ITextSnapshot snapshot, int x1, int x2) => snapshot.GetLineNumberFromPosition(x1) == snapshot.GetLineNumberFromPosition(x2); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Syntax/Syntax/LambdaUtilitiesTests.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.VisualBasic.UnitTests Public Class LambdaUtilitiesTests <Fact> Public Sub AreEquivalentIgnoringLambdaBodies1() Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(1)"), SyntaxFactory.ParseExpression("F(1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(1)"), SyntaxFactory.ParseExpression("F(2)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Function(a) 1)"), SyntaxFactory.ParseExpression("F(Function(a) 2)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Sub(a) Console.WriteLine(1))"), SyntaxFactory.ParseExpression("F(Sub(a) Console.WriteLine(2))"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Function(a) : Return 1 : End Function)"), SyntaxFactory.ParseExpression("F(Function(a) : Return 2 : End Function)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Sub(a) : Console.WriteLine(1)) : End Sub)"), SyntaxFactory.ParseExpression("F(Sub(a) : Console.WriteLine(2)) : End Sub)"))) ' RECONSIDER: lambda header is currently considered to be part of the body Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Sub(a) : Console.WriteLine(1)) : End Sub)"), SyntaxFactory.ParseExpression("F(Sub(b) : Console.WriteLine(1)) : End Sub)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2,3} Select 1)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Let a = 1, b = 2 Select a)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Let a = 4, b = 3 Select b)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2}, y in {3,4} Where x > 0 Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2}, y in {3,4,5} Where x < 0 Select 2)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4} On F(1) Equals G(1) And F(2) Equals G(2) Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4} On F(2) Equals G(2) And F(3) Equals G(3) Select 1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4} On F(1) Equals G(1) Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4,5} On F(1) Equals G(1) Select 1)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f1, x.g1 Descending, x.h1 Ascending Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f2, x.g2 Descending, x.h2 Ascending Select 1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f, x.g Descending, x.h Ascending Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f, x.g Descending, x.h Descending Select 1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Skip F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Skip F(2) Select a"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Skip While F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Skip While F(2) Select a"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Take F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Take F(2) Select a"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Take While F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Take While F(2) Select a"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b In Id({1}, 2) Join b2 In Id({1}, 3) On Id(b, 4) Equals Id(b2, 5) And Id(b, 6) Equals Id(b2, 7) On Id(b, 8) Equals Id(a, 9) And Id(b, 10) Equals Id(a, 11) Group Join c In Id({1}, 12) On Id(c, 13) Equals Id(b, 14) And Id(c, 15) Equals Id(b, 16) Into d1 = Count(Id(1, 17)), e1 = Count(Id(1, 18))) "), SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b In Id({1}, 2) Join b2 In Id({1}, 3) On Id(b, 40) Equals Id(b2, 50) And Id(b, 60) Equals Id(b2, 70) On Id(b, 80) Equals Id(a, 90) And Id(b, 100) Equals Id(a, 110) Group Join c In Id({1}, 12) On Id(c, 130) Equals Id(b, 140) And Id(c, 150) Equals Id(b, 160) Into d1 = Count(Id(1, 170)), e1 = Count(Id(1, 180))) "))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b2 In Id({1}, 3) On Id(a, 4) Equals Id(b2, 5) Group Join c In Id({1}, 12) On Id(c, 13) Equals Id(b, 14) And Id(c, 15) Equals Id(b, 16) Into d1 = Count(Id(1, 17)), e1 = Count(Id(1, 18))) "), SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b2 In Id({1}, 3) On Id(a, 4) Equals Id(b2, 5) Group Join c In Id({10000000}, 12) On Id(c, 13) Equals Id(b, 14) And Id(c, 15) Equals Id(b, 16) Into d1 = Count(Id(1, 17)), e1 = Count(Id(1, 18))) "))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression(" F(From a In {1} Aggregate b In {1}, c in {1} From d In {1} Let h = 1 Where d > 1 Into q = Count(b), p = Distinct() "), SyntaxFactory.ParseExpression(" F(From a In {1} Aggregate b In {10}, c in {10} From d In {10} Let h = 10 Where d > 10 Into q = Count(b + 1), p = Distinct() "))) 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.VisualBasic.UnitTests Public Class LambdaUtilitiesTests <Fact> Public Sub AreEquivalentIgnoringLambdaBodies1() Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(1)"), SyntaxFactory.ParseExpression("F(1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(1)"), SyntaxFactory.ParseExpression("F(2)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Function(a) 1)"), SyntaxFactory.ParseExpression("F(Function(a) 2)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Sub(a) Console.WriteLine(1))"), SyntaxFactory.ParseExpression("F(Sub(a) Console.WriteLine(2))"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Function(a) : Return 1 : End Function)"), SyntaxFactory.ParseExpression("F(Function(a) : Return 2 : End Function)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Sub(a) : Console.WriteLine(1)) : End Sub)"), SyntaxFactory.ParseExpression("F(Sub(a) : Console.WriteLine(2)) : End Sub)"))) ' RECONSIDER: lambda header is currently considered to be part of the body Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(Sub(a) : Console.WriteLine(1)) : End Sub)"), SyntaxFactory.ParseExpression("F(Sub(b) : Console.WriteLine(1)) : End Sub)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2,3} Select 1)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Let a = 1, b = 2 Select a)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Let a = 4, b = 3 Select b)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2}, y in {3,4} Where x > 0 Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2}, y in {3,4,5} Where x < 0 Select 2)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4} On F(1) Equals G(1) And F(2) Equals G(2) Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4} On F(2) Equals G(2) And F(3) Equals G(3) Select 1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4} On F(1) Equals G(1) Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Join y In {3,4,5} On F(1) Equals G(1) Select 1)"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f1, x.g1 Descending, x.h1 Ascending Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f2, x.g2 Descending, x.h2 Ascending Select 1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f, x.g Descending, x.h Ascending Select 1)"), SyntaxFactory.ParseExpression("F(From x In {1,2} Order By x.f, x.g Descending, x.h Descending Select 1)"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Skip F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Skip F(2) Select a"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Skip While F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Skip While F(2) Select a"))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Take F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Take F(2) Select a"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression("F(From a In {1} Take While F(1) Select a"), SyntaxFactory.ParseExpression("F(From a In {1} Take While F(2) Select a"))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b In Id({1}, 2) Join b2 In Id({1}, 3) On Id(b, 4) Equals Id(b2, 5) And Id(b, 6) Equals Id(b2, 7) On Id(b, 8) Equals Id(a, 9) And Id(b, 10) Equals Id(a, 11) Group Join c In Id({1}, 12) On Id(c, 13) Equals Id(b, 14) And Id(c, 15) Equals Id(b, 16) Into d1 = Count(Id(1, 17)), e1 = Count(Id(1, 18))) "), SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b In Id({1}, 2) Join b2 In Id({1}, 3) On Id(b, 40) Equals Id(b2, 50) And Id(b, 60) Equals Id(b2, 70) On Id(b, 80) Equals Id(a, 90) And Id(b, 100) Equals Id(a, 110) Group Join c In Id({1}, 12) On Id(c, 130) Equals Id(b, 140) And Id(c, 150) Equals Id(b, 160) Into d1 = Count(Id(1, 170)), e1 = Count(Id(1, 180))) "))) Assert.False(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b2 In Id({1}, 3) On Id(a, 4) Equals Id(b2, 5) Group Join c In Id({1}, 12) On Id(c, 13) Equals Id(b, 14) And Id(c, 15) Equals Id(b, 16) Into d1 = Count(Id(1, 17)), e1 = Count(Id(1, 18))) "), SyntaxFactory.ParseExpression(" F(From a In Id({1}, 1) Join b2 In Id({1}, 3) On Id(a, 4) Equals Id(b2, 5) Group Join c In Id({10000000}, 12) On Id(c, 13) Equals Id(b, 14) And Id(c, 15) Equals Id(b, 16) Into d1 = Count(Id(1, 17)), e1 = Count(Id(1, 18))) "))) Assert.True(LambdaUtilities.AreEquivalentIgnoringLambdaBodies( SyntaxFactory.ParseExpression(" F(From a In {1} Aggregate b In {1}, c in {1} From d In {1} Let h = 1 Where d > 1 Into q = Count(b), p = Distinct() "), SyntaxFactory.ParseExpression(" F(From a In {1} Aggregate b In {10}, c in {10} From d In {10} Let h = 10 Where d > 10 Into q = Count(b + 1), p = Distinct() "))) End Sub End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/ParameterSymbolReferenceFinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class ParameterSymbolReferenceFinder : AbstractReferenceFinder<IParameterSymbol> { protected override bool CanFind(IParameterSymbol symbol) => true; protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IParameterSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // TODO(cyrusn): We can be smarter with parameters. They will either be found // within the method that they were declared on, or they will referenced // elsewhere as "paramName:" or "paramName:=". We can narrow the search by // filtering down to matches of that form. For now we just return any document // that references something with this name. return FindDocumentsAsync(project, documents, cancellationToken, symbol.Name); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IParameterSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var symbolsMatchAsync = GetParameterSymbolsMatchFunction( symbol, document.Project.Solution, cancellationToken); return FindReferencesInDocumentUsingIdentifierAsync( symbol, symbol.Name, document, semanticModel, symbolsMatchAsync, cancellationToken); } private static Func<SyntaxToken, SemanticModel, ValueTask<(bool matched, CandidateReason reason)>> GetParameterSymbolsMatchFunction( IParameterSymbol parameter, Solution solution, CancellationToken cancellationToken) { // Get the standard function for comparing parameters. This function will just // directly compare the parameter symbols for SymbolEquivalence. var standardFunction = GetStandardSymbolsMatchFunction( parameter, findParentNode: null, solution: solution, cancellationToken: cancellationToken); // HOwever, we also want to consider parameter symbols them same if they unify across // VB's synthesized AnonymousDelegate parameters. var containingMethod = parameter.ContainingSymbol as IMethodSymbol; if (containingMethod?.AssociatedAnonymousDelegate == null) { // This was a normal parameter, so just use the normal comparison function. return standardFunction; } var invokeMethod = containingMethod.AssociatedAnonymousDelegate.DelegateInvokeMethod; var ordinal = parameter.Ordinal; if (invokeMethod == null || ordinal >= invokeMethod.Parameters.Length) { return standardFunction; } // This was parameter of a method that had an associated synthesized anonyomous-delegate. // IN that case, we want it to match references to the corresponding parameter in that // anonymous-delegate's invoke method. So get he symbol match function that will chec // for equivalence with that parameter. var anonymousDelegateParameter = invokeMethod.Parameters[ordinal]; var anonParameterFunc = GetStandardSymbolsMatchFunction( anonymousDelegateParameter, findParentNode: null, solution: solution, cancellationToken: cancellationToken); // Return a new function which is a compound of the two functions we have. return async (token, model) => { // First try the standard function. var result = await standardFunction(token, model).ConfigureAwait(false); if (!result.matched) { // If it fails, fall back to the anon-delegate function. result = await anonParameterFunc(token, model).ConfigureAwait(false); } return result; }; } protected override async Task<ImmutableArray<(ISymbol symbol, FindReferencesCascadeDirection cascadeDirection)>> DetermineCascadedSymbolsAsync( IParameterSymbol parameter, Solution solution, IImmutableSet<Project>? projects, FindReferencesSearchOptions options, FindReferencesCascadeDirection cascadeDirection, CancellationToken cancellationToken) { if (parameter.IsThis) { return ImmutableArray<(ISymbol symbol, FindReferencesCascadeDirection cascadeDirection)>.Empty; } using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var symbols); await CascadeBetweenAnonymousFunctionParametersAsync(solution, parameter, symbols, cancellationToken).ConfigureAwait(false); CascadeBetweenPropertyAndAccessorParameters(parameter, symbols); CascadeBetweenDelegateMethodParameters(parameter, symbols); CascadeBetweenPartialMethodParameters(parameter, symbols); using var _2 = ArrayBuilder<(ISymbol symbol, FindReferencesCascadeDirection cascadeDirection)>.GetInstance(symbols.Count, out var result); foreach (var symbol in symbols) result.Add((symbol, cascadeDirection)); return result.ToImmutable(); } private static async Task CascadeBetweenAnonymousFunctionParametersAsync( Solution solution, IParameterSymbol parameter, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { if (parameter.ContainingSymbol.IsAnonymousFunction()) { var parameterNode = parameter.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (parameterNode != null) { var document = solution.GetDocument(parameterNode.SyntaxTree); if (document != null) { var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); if (semanticFacts.ExposesAnonymousFunctionParameterNames) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var lambdaNode = parameter.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType != null) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var container = GetContainer(semanticModel, parameterNode, syntaxFacts); if (container != null) { CascadeBetweenAnonymousFunctionParameters( document, semanticModel, container, parameter, convertedType, results, cancellationToken); } } } } } } } private static void CascadeBetweenAnonymousFunctionParameters( Document document, SemanticModel semanticModel, SyntaxNode container, IParameterSymbol parameter, ITypeSymbol convertedType1, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var token in container.DescendantTokens()) { if (IdentifiersMatch(syntaxFacts, parameter.Name, token)) { var symbol = semanticModel.GetDeclaredSymbol(token.GetRequiredParent(), cancellationToken); if (symbol is IParameterSymbol && symbol.ContainingSymbol.IsAnonymousFunction() && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(parameter.ContainingSymbol, symbol.ContainingSymbol, syntaxFacts.IsCaseSensitive) && ParameterNamesMatch(syntaxFacts, (IMethodSymbol)parameter.ContainingSymbol, (IMethodSymbol)symbol.ContainingSymbol)) { var lambdaNode = symbol.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType2 = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType1.Equals(convertedType2)) { results.Add(symbol); } } } } } private static bool ParameterNamesMatch(ISyntaxFactsService syntaxFacts, IMethodSymbol methodSymbol1, IMethodSymbol methodSymbol2) { for (var i = 0; i < methodSymbol1.Parameters.Length; i++) { if (!syntaxFacts.TextMatch(methodSymbol1.Parameters[i].Name, methodSymbol2.Parameters[i].Name)) { return false; } } return true; } private static SyntaxNode? GetContainer(SemanticModel semanticModel, SyntaxNode parameterNode, ISyntaxFactsService syntaxFactsService) { for (var current = parameterNode; current != null; current = current.Parent) { var declaredSymbol = semanticModel.GetDeclaredSymbol(current); if (declaredSymbol is IMethodSymbol method && method.MethodKind != MethodKind.AnonymousFunction) { return current; } } return syntaxFactsService.GetContainingVariableDeclaratorOfFieldDeclaration(parameterNode); } private static void CascadeBetweenPropertyAndAccessorParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; var containingSymbol = parameter.ContainingSymbol; if (containingSymbol is IMethodSymbol containingMethod) { if (containingMethod.AssociatedSymbol is IPropertySymbol property) { AddParameterAtIndex(results, ordinal, property.Parameters); } } else if (containingSymbol is IPropertySymbol containingProperty) { if (containingProperty.GetMethod != null && ordinal < containingProperty.GetMethod.Parameters.Length) { results.Add(containingProperty.GetMethod.Parameters[ordinal]); } if (containingProperty.SetMethod != null && ordinal < containingProperty.SetMethod.Parameters.Length) { results.Add(containingProperty.SetMethod.Parameters[ordinal]); } } } private static void CascadeBetweenDelegateMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; if (parameter.ContainingSymbol is IMethodSymbol containingMethod) { var containingType = containingMethod.ContainingType; if (containingType.IsDelegateType()) { if (containingMethod.MethodKind == MethodKind.DelegateInvoke) { // cascade to the corresponding parameter in the BeginInvoke method. var beginInvokeMethod = containingType.GetMembers(WellKnownMemberNames.DelegateBeginInvokeName) .OfType<IMethodSymbol>() .FirstOrDefault(); AddParameterAtIndex(results, ordinal, beginInvokeMethod?.Parameters); } else if (containingMethod.ContainingType.IsDelegateType() && containingMethod.Name == WellKnownMemberNames.DelegateBeginInvokeName) { // cascade to the corresponding parameter in the Invoke method. AddParameterAtIndex(results, ordinal, containingType.DelegateInvokeMethod?.Parameters); } } } } private static void AddParameterAtIndex( ArrayBuilder<ISymbol> results, int ordinal, ImmutableArray<IParameterSymbol>? parameters) { if (parameters != null && ordinal < parameters.Value.Length) { results.Add(parameters.Value[ordinal]); } } private static void CascadeBetweenPartialMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { if (parameter.ContainingSymbol is IMethodSymbol) { var ordinal = parameter.Ordinal; var method = (IMethodSymbol)parameter.ContainingSymbol; if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.Parameters.Length) { results.Add(method.PartialDefinitionPart.Parameters[ordinal]); } if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.Parameters.Length) { results.Add(method.PartialImplementationPart.Parameters[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.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class ParameterSymbolReferenceFinder : AbstractReferenceFinder<IParameterSymbol> { protected override bool CanFind(IParameterSymbol symbol) => true; protected override Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( IParameterSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { // TODO(cyrusn): We can be smarter with parameters. They will either be found // within the method that they were declared on, or they will referenced // elsewhere as "paramName:" or "paramName:=". We can narrow the search by // filtering down to matches of that form. For now we just return any document // that references something with this name. return FindDocumentsAsync(project, documents, cancellationToken, symbol.Name); } protected override ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( IParameterSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var symbolsMatchAsync = GetParameterSymbolsMatchFunction( symbol, document.Project.Solution, cancellationToken); return FindReferencesInDocumentUsingIdentifierAsync( symbol, symbol.Name, document, semanticModel, symbolsMatchAsync, cancellationToken); } private static Func<SyntaxToken, SemanticModel, ValueTask<(bool matched, CandidateReason reason)>> GetParameterSymbolsMatchFunction( IParameterSymbol parameter, Solution solution, CancellationToken cancellationToken) { // Get the standard function for comparing parameters. This function will just // directly compare the parameter symbols for SymbolEquivalence. var standardFunction = GetStandardSymbolsMatchFunction( parameter, findParentNode: null, solution: solution, cancellationToken: cancellationToken); // HOwever, we also want to consider parameter symbols them same if they unify across // VB's synthesized AnonymousDelegate parameters. var containingMethod = parameter.ContainingSymbol as IMethodSymbol; if (containingMethod?.AssociatedAnonymousDelegate == null) { // This was a normal parameter, so just use the normal comparison function. return standardFunction; } var invokeMethod = containingMethod.AssociatedAnonymousDelegate.DelegateInvokeMethod; var ordinal = parameter.Ordinal; if (invokeMethod == null || ordinal >= invokeMethod.Parameters.Length) { return standardFunction; } // This was parameter of a method that had an associated synthesized anonyomous-delegate. // IN that case, we want it to match references to the corresponding parameter in that // anonymous-delegate's invoke method. So get he symbol match function that will chec // for equivalence with that parameter. var anonymousDelegateParameter = invokeMethod.Parameters[ordinal]; var anonParameterFunc = GetStandardSymbolsMatchFunction( anonymousDelegateParameter, findParentNode: null, solution: solution, cancellationToken: cancellationToken); // Return a new function which is a compound of the two functions we have. return async (token, model) => { // First try the standard function. var result = await standardFunction(token, model).ConfigureAwait(false); if (!result.matched) { // If it fails, fall back to the anon-delegate function. result = await anonParameterFunc(token, model).ConfigureAwait(false); } return result; }; } protected override async Task<ImmutableArray<(ISymbol symbol, FindReferencesCascadeDirection cascadeDirection)>> DetermineCascadedSymbolsAsync( IParameterSymbol parameter, Solution solution, IImmutableSet<Project>? projects, FindReferencesSearchOptions options, FindReferencesCascadeDirection cascadeDirection, CancellationToken cancellationToken) { if (parameter.IsThis) { return ImmutableArray<(ISymbol symbol, FindReferencesCascadeDirection cascadeDirection)>.Empty; } using var _1 = ArrayBuilder<ISymbol>.GetInstance(out var symbols); await CascadeBetweenAnonymousFunctionParametersAsync(solution, parameter, symbols, cancellationToken).ConfigureAwait(false); CascadeBetweenPropertyAndAccessorParameters(parameter, symbols); CascadeBetweenDelegateMethodParameters(parameter, symbols); CascadeBetweenPartialMethodParameters(parameter, symbols); using var _2 = ArrayBuilder<(ISymbol symbol, FindReferencesCascadeDirection cascadeDirection)>.GetInstance(symbols.Count, out var result); foreach (var symbol in symbols) result.Add((symbol, cascadeDirection)); return result.ToImmutable(); } private static async Task CascadeBetweenAnonymousFunctionParametersAsync( Solution solution, IParameterSymbol parameter, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { if (parameter.ContainingSymbol.IsAnonymousFunction()) { var parameterNode = parameter.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (parameterNode != null) { var document = solution.GetDocument(parameterNode.SyntaxTree); if (document != null) { var semanticFacts = document.GetRequiredLanguageService<ISemanticFactsService>(); if (semanticFacts.ExposesAnonymousFunctionParameterNames) { var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var lambdaNode = parameter.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType != null) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var container = GetContainer(semanticModel, parameterNode, syntaxFacts); if (container != null) { CascadeBetweenAnonymousFunctionParameters( document, semanticModel, container, parameter, convertedType, results, cancellationToken); } } } } } } } private static void CascadeBetweenAnonymousFunctionParameters( Document document, SemanticModel semanticModel, SyntaxNode container, IParameterSymbol parameter, ITypeSymbol convertedType1, ArrayBuilder<ISymbol> results, CancellationToken cancellationToken) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); foreach (var token in container.DescendantTokens()) { if (IdentifiersMatch(syntaxFacts, parameter.Name, token)) { var symbol = semanticModel.GetDeclaredSymbol(token.GetRequiredParent(), cancellationToken); if (symbol is IParameterSymbol && symbol.ContainingSymbol.IsAnonymousFunction() && SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(parameter.ContainingSymbol, symbol.ContainingSymbol, syntaxFacts.IsCaseSensitive) && ParameterNamesMatch(syntaxFacts, (IMethodSymbol)parameter.ContainingSymbol, (IMethodSymbol)symbol.ContainingSymbol)) { var lambdaNode = symbol.ContainingSymbol.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).First(); var convertedType2 = semanticModel.GetTypeInfo(lambdaNode, cancellationToken).ConvertedType; if (convertedType1.Equals(convertedType2)) { results.Add(symbol); } } } } } private static bool ParameterNamesMatch(ISyntaxFactsService syntaxFacts, IMethodSymbol methodSymbol1, IMethodSymbol methodSymbol2) { for (var i = 0; i < methodSymbol1.Parameters.Length; i++) { if (!syntaxFacts.TextMatch(methodSymbol1.Parameters[i].Name, methodSymbol2.Parameters[i].Name)) { return false; } } return true; } private static SyntaxNode? GetContainer(SemanticModel semanticModel, SyntaxNode parameterNode, ISyntaxFactsService syntaxFactsService) { for (var current = parameterNode; current != null; current = current.Parent) { var declaredSymbol = semanticModel.GetDeclaredSymbol(current); if (declaredSymbol is IMethodSymbol method && method.MethodKind != MethodKind.AnonymousFunction) { return current; } } return syntaxFactsService.GetContainingVariableDeclaratorOfFieldDeclaration(parameterNode); } private static void CascadeBetweenPropertyAndAccessorParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; var containingSymbol = parameter.ContainingSymbol; if (containingSymbol is IMethodSymbol containingMethod) { if (containingMethod.AssociatedSymbol is IPropertySymbol property) { AddParameterAtIndex(results, ordinal, property.Parameters); } } else if (containingSymbol is IPropertySymbol containingProperty) { if (containingProperty.GetMethod != null && ordinal < containingProperty.GetMethod.Parameters.Length) { results.Add(containingProperty.GetMethod.Parameters[ordinal]); } if (containingProperty.SetMethod != null && ordinal < containingProperty.SetMethod.Parameters.Length) { results.Add(containingProperty.SetMethod.Parameters[ordinal]); } } } private static void CascadeBetweenDelegateMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { var ordinal = parameter.Ordinal; if (parameter.ContainingSymbol is IMethodSymbol containingMethod) { var containingType = containingMethod.ContainingType; if (containingType.IsDelegateType()) { if (containingMethod.MethodKind == MethodKind.DelegateInvoke) { // cascade to the corresponding parameter in the BeginInvoke method. var beginInvokeMethod = containingType.GetMembers(WellKnownMemberNames.DelegateBeginInvokeName) .OfType<IMethodSymbol>() .FirstOrDefault(); AddParameterAtIndex(results, ordinal, beginInvokeMethod?.Parameters); } else if (containingMethod.ContainingType.IsDelegateType() && containingMethod.Name == WellKnownMemberNames.DelegateBeginInvokeName) { // cascade to the corresponding parameter in the Invoke method. AddParameterAtIndex(results, ordinal, containingType.DelegateInvokeMethod?.Parameters); } } } } private static void AddParameterAtIndex( ArrayBuilder<ISymbol> results, int ordinal, ImmutableArray<IParameterSymbol>? parameters) { if (parameters != null && ordinal < parameters.Value.Length) { results.Add(parameters.Value[ordinal]); } } private static void CascadeBetweenPartialMethodParameters( IParameterSymbol parameter, ArrayBuilder<ISymbol> results) { if (parameter.ContainingSymbol is IMethodSymbol) { var ordinal = parameter.Ordinal; var method = (IMethodSymbol)parameter.ContainingSymbol; if (method.PartialDefinitionPart != null && ordinal < method.PartialDefinitionPart.Parameters.Length) { results.Add(method.PartialDefinitionPart.Parameters[ordinal]); } if (method.PartialImplementationPart != null && ordinal < method.PartialImplementationPart.Parameters.Length) { results.Add(method.PartialImplementationPart.Parameters[ordinal]); } } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/xlf/EditorFeaturesResources.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="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">모든 메서드</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">명확하게 하기 위해 항상</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">식별자 '{0}'의 인라인 이름 바꾸기 세션이 활성 상태입니다. 추가 옵션에 액세스하려면 인라인 이름 바꾸기를 다시 호출하세요. 언제든지 이름을 바꾸려는 식별자를 계속 편집할 수 있습니다.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">변경 내용 적용</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">사용되지 않는 매개 변수를 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">구성 변경</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">코드 정리가 구성되지 않았습니다.</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">지금 구성</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">'this.' 또는 'Me.'를 기본으로 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">이 메시지를 다시 표시하지 않음</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">계속하시겠습니까? 계속하면 손상된 코드가 생성될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">가져오지 않은 네임스페이스의 항목</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">확장기</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">메서드 추출에서 다음 문제가 발생했습니다.</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">필터</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">로컬, 매개 변수 및 멤버의 경우</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">멤버 액세스 식의 경우</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">추가 정리를 수행 하는 문서</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">'{0}'에 대한 도움 받기</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Bing에서 '{0}'에 대한 도움 받기</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">제안을 수집하는 중 - '{0}'</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">제안을 수집하는 중 - 솔루션이 완전히 로드될 때까지 기다리는 중</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">기본으로 이동</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">산술 연산자</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">기타 이항 연산자</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">기타 연산자</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">관계 연산자</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">들여쓰기 크기</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">인라인 힌트</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">최종 줄 바꿈 삽입</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">잘못된 어셈블리 이름</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">어셈블리 이름에 잘못된 문자가 있음</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">키워드 - 제어</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">베이스를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">필요한 경우 사용 안 함</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">줄 바꿈</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">아니요</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">public이 아닌 메서드</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">연산자 - 오버로드됨</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">붙여넣기 추적</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">'GetHashCode'에서 'System.HashCode' 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">coalesce 식 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">컬렉션 이니셜라이저 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">복합 대입 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">할당이 포함된 'if'보다 조건식 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">반환이 포함된 'if'보다 조건식 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">명시적 튜플 이름 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">프레임워크 형식 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">유추된 무명 형식 멤버 이름 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">유추된 튜플 요소 이름 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">참조 같음 검사에 대해 'is null' 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">null 전파 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">개체 이니셜라이저 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">미리 정의된 형식 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">읽기 전용 필드 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">간단한 부울 식을 기본으로 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">'this.' 또는 'Me.'를 기본으로 사용하세요.</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">전처리기 텍스트</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">문장 부호</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 이벤트 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 필드 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 메서드 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 속성 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">파일 이름 바꾸기(형식이 파일 이름과 일치하지 않음)(_F)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">파일 이름 바꾸기(부분 형식에서 허용되지 않음)(_F)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">기호의 파일 이름 바꾸기(_F)</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">주석 분할</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">문자열 - 이스케이프 문자</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">기호 - 정적</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">탭 크기</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">기호에 베이스가 없습니다.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">블록 주석 토글</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">줄 주석 토글</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">블록 주석을 토글하는 중...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">줄 주석을 토글하는 중...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">탭 사용</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">사용자 멤버 - 상수</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">사용자 멤버 - 열거형 멤버</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">사용자 멤버 - 이벤트</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">사용자 멤버 - 확장 메서드</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">사용자 멤버 - 필드</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">사용자 멤버 - 레이블</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">사용자 멤버 - 로컬</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">사용자 멤버 - 메서드</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">사용자 멤버 - 네임스페이스</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">사용자 멤버 - 매개 변수</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">사용자 멤버 - 속성</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">사용자 형식 - 클래스</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">사용자 형식 - 대리자</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">사용자 형식 - 열거형</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">사용자 형식 - 인터페이스</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="new">User Types - Record Structs</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">사용자 유형 - 레코드</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">사용자 형식 - 구조</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">사용자 형식 - 형식 매개 변수</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">문자열 - 축자</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">백그라운드 작업이 완료될 때까지 대기 중...</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">경고</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">XML 문서 주석 - 특성 이름</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">XML 문서 주석 - CData 섹션</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">XML 문서 주석 - 텍스트</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">XML 문서 주석 - 구분 기호</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">XML 문서 주석 - 주석</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">사용자 형식 - 모듈</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">VB XML 리터럴 - 특성 이름</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">VB XML 리터럴 - 특성 인용 문자</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">VB XML 리터럴 - 특성 값</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">VB XML 리터럴 - CData 섹션</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">VB XML 리터럴 - 주석</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">VB XML 리터럴 - 구분 기호</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">VB XML 리터럴 - 포함 식</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">VB XML 리터럴 - 엔터티 참조</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">VB XML 리터럴 - 이름</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">VB XML 리터럴 - 처리 명령</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">VB XML 리터럴 - 텍스트</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">XML 문서 주석 - 특성 인용 문자</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">XML 문서 주석 - 특성 값</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">불필요한 코드</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">편집 다시 실행</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">이름 바꾸기로 1개의 파일에서 1개의 참조가 업데이트됩니다.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">이름 바꾸기로 1개의 파일에서 {0}개의 참조가 업데이트됩니다.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">이름 바꾸기로 {1}개의 파일에서 {0}개의 참조가 업데이트됩니다.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">예</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">이 요소는 읽기 전용 파일에 포함되어 있으므로 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">이 요소는 탐색할 수 없는 위치에 있으므로 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">'{0}' 기본</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">충돌 {0}개가 해결됩니다.</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">구현된 멤버 '{0}'개</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">해결할 수 없는 충돌 {0}개</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">"{0}" 적용 중...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">다음 콘텐츠가 있는 '{1}'에 대한 '{0}' 추가 중:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">'{0}' 프로젝트 추가 중</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">'{0}' 프로젝트를 제거하는 중</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">'{0}'에 대한 프로젝트 참조 변경 중</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">'{1}'에 대한 '{0}' 참조 추가 중</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">'{1}'에서 '{0}' 참조를 제거하는 중</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">'{1}'에 대한 '{0}' 분석기 참조 추가 중</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">'{1}'에서 '{0}' 분석기 참조를 제거하는 중</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">XML 끝 태그 완료</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">태그 완료 중</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">필드 캡슐화</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">"필드 캡슐화" 리팩토링 적용 중...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">캡슐화할 필드의 정의를 선택하세요.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">지정한 작업 영역에서 실행을 취소할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">검색 중...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">취소되었습니다.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">정보를 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">사용법을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">구현</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">구현자</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">재정의</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">재정의 수행자</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">직접 호출됨</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">간접적으로 호출됨</target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">호출됨</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">참조됨</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">참조를 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">파생 형식을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">구현을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} - (줄 {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">클래스 파트</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">구조체 파트</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">인터페이스 파트</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">형식 파트</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">상속</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">상속 대상</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">동일한 키로 이미 문서를 추적하는 중</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">자동 속성 선호</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">문서를 현재 추적하고 있지 않습니다.</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">이름 바꾸기 정보 계산 중...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">파일 업데이트 중...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">이름 바꾸기 작업이 취소되었거나 잘못되었습니다.</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">기호 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">텍스트 버퍼 변경</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">이름 바꾸기 작업이 제대로 완료되지 않았습니다. 일부 파일이 업데이트되지 않았을 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">'{1}'(으)로 '{0}' 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">경고 미리 보기</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(외부)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">자동 줄 끝내기</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">자동 완성 중...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">자동 쌍 완성</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">활성 인라인 이름 바꾸기 세션이 여전히 활성화되어 있습니다. 새 세션을 시작하기 전에 완료하세요.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">버퍼는 작업 영역의 일부가 아닙니다.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">토큰이 작업 영역에 포함되어 있지 않습니다.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">식별자의 이름을 바꿔야 합니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">이 요소의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">이 요소의 이름을 바꾸기 전에 코드 오류를 해결하세요.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">연산자의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">메타데이터에서 정의된 요소의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">이전 전송 요소의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">탐색 모음</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">탐색 모음을 새로 고치는 중...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">형식 토큰</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">스마트 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">참조 찾기</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">참조를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">"{0}"의 참조를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">선택 영역을 주석으로 처리</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">선택 영역의 주석 처리 제거</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">현재 선택한 텍스트를 주석으로 처리하는 중...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">현재 선택한 텍스트의 주석 처리를 제거하는 중...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">새 줄 삽입</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">문서 주석</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">문서 주석 삽입 중...</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">메서드 추출</target> <note /> </trans-unit> <trans-unit id="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">"메서드 추출" 리팩토링 적용 중...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">문서 서식</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document...</source> <target state="translated">문서 서식을 지정하는 중...</target> <note /> </trans-unit> <trans-unit id="Formatting"> <source>Formatting</source> <target state="translated">서식</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">선택 영역 서식</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">현재 선택한 텍스트의 서식을 지정하는 중...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">캐럿에서 기호를 탐색할 수 없습니다.</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="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">정의를 탐색하는 중...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">문서 구성</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">문서 구성 중...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">강조 표시된 정의</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">새 이름이 유효한 식별자가 아닙니다.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">인라인 이름 바꾸기 픽스업</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">인라인 이름 바꾸기의 충돌이 해결됨</target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">인라인 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">이름 바꾸기 시작</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">충돌 해결 표시</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">이름을 바꿀 토큰을 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">충돌</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">텍스트 탐색</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">단어 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">바깥쪽 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">다음 형제의 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">이전 형제의 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">이름 바꾸기: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">전구 세션이 이미 해제되었습니다.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">자동 쌍 완성 끝점 표식 색</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">익명 형식의 멤버 이름은 아직 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">엔진은 대화형 창에 연결되어 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">현재 프롬프트 설정을 변경합니다.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">예기치 않은 텍스트: '{0}'</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">triggerSpan이 지정한 작업 영역에 포함되어 있지 않습니다.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">이 세션은 이미 해제되었습니다.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">트랜잭션이 이미 완료되었습니다.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">원본 오류가 아닙니다. 줄/열을 사용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">다른 텍스트 스냅샷에서 위치를 비교할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">XML 문서 주석 - 엔터티 참조</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">XML 문서 주석 - 이름</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">XML 문서 주석 - 처리 명령</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">활성 문</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">정보 피킹을 로드하는 중...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">피킹</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">적용(_A)</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">오버로드 포함(_O)</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">주석 포함(_C)</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">문자열 포함(_S)</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">적용</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">시그니처 변경</target> <note /> </trans-unit> <trans-unit id="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">변경 내용 미리 보기 - {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">코드 변경 내용 미리 보기:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">변경 내용 미리 보기</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">서식 붙여넣기</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">붙여넣은 텍스트의 서식을 지정하는 중...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">개체의 정의가 숨겨집니다.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">자동 서식</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">구조체 "out/ref" 매개 변수를 만들지 않는 방법으로 오류를 수정할 수 있습니다. 계속하시겠습니까?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">시그니처 변경:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">'{0}'에서 '{1}'(으)로 이름 바꾸기:</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">필드 캡슐화:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">호출 계층 구조</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">'{0}'에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">'{0}' 기본 멤버에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">'{0}' 인터페이스 구현에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">호출 계층 구조 정보 계산 중</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">'{0}' 구현</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">이니셜라이저</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">'{0}' 필드에 대한 참조</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">재정의에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">변경 사항 미리 보기(_P)</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">적용</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">취소</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">변경 내용</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</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="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">IntelliSense 커밋 서식</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">추적 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">다음 내용과 함께 '{1}'에서 '{0}'을(를) 제거 중:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">'{0}'은(는) '{1}' 작업을 지원하지 않습니다. 하지만 이 작업을 지원하는 중첩 '{2}'을(를) 포함할 수 있습니다('{2}.{3}' 참조).</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">중괄호 완성</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">이름 바꾸기 세션이 활성인 동안에는 작업을 적용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">이름 바꾸기 추적 세션이 취소되었고 더 이상 사용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">강조 표시되어 작성된 참조</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">커서는 멤버 이름에 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">중괄호 일치</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">구현을 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">구현으로 이동</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">기호에 구현이 없습니다.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">새 이름: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">이름 변경을 시작할 강조 표시된 위치를 수정합니다.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">붙여넣기</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">탐색하는 중...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">제안 줄임표(…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'{0}' 참조</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'{0}' 구현</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'{0}' 선언</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">인라인 이름 바꾸기 충돌</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">인라인 이름 바꾸기 필드 배경 및 테두리</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">인라인 이름 바꾸기 필드 텍스트</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">주석 편집 차단</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">선택 영역 주석 처리/주석 처리 제거</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">코드 완성</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">대화형으로 실행</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">인터페이스 추출</target> <note /> </trans-unit> <trans-unit id="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">인접 멤버로 이동</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">대화형</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">대화형으로 붙여넣기</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">강조 표시 참조로 이동</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">개요</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">추적 이름 바꾸기 취소</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">시그니처 도움말</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">스마트 토큰 포맷터</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="../EditorFeaturesResources.resx"> <body> <trans-unit id="All_methods"> <source>All methods</source> <target state="translated">모든 메서드</target> <note /> </trans-unit> <trans-unit id="Always_for_clarity"> <source>Always for clarity</source> <target state="translated">명확하게 하기 위해 항상</target> <note /> </trans-unit> <trans-unit id="An_inline_rename_session_is_active_for_identifier_0"> <source>An inline rename session is active for identifier '{0}'. Invoke inline rename again to access additional options. You may continue to edit the identifier being renamed at any time.</source> <target state="translated">식별자 '{0}'의 인라인 이름 바꾸기 세션이 활성 상태입니다. 추가 옵션에 액세스하려면 인라인 이름 바꾸기를 다시 호출하세요. 언제든지 이름을 바꾸려는 식별자를 계속 편집할 수 있습니다.</target> <note>For screenreaders. {0} is the identifier being renamed.</note> </trans-unit> <trans-unit id="Applying_changes"> <source>Applying changes</source> <target state="translated">변경 내용 적용</target> <note /> </trans-unit> <trans-unit id="Avoid_unused_parameters"> <source>Avoid unused parameters</source> <target state="translated">사용되지 않는 매개 변수를 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Change_configuration"> <source>Change configuration</source> <target state="translated">구성 변경</target> <note /> </trans-unit> <trans-unit id="Code_cleanup_is_not_configured"> <source>Code cleanup is not configured</source> <target state="translated">코드 정리가 구성되지 않았습니다.</target> <note /> </trans-unit> <trans-unit id="Configure_it_now"> <source>Configure it now</source> <target state="translated">지금 구성</target> <note /> </trans-unit> <trans-unit id="Do_not_prefer_this_or_Me"> <source>Do not prefer 'this.' or 'Me.'</source> <target state="translated">'this.' 또는 'Me.'를 기본으로 사용하지 마세요.</target> <note /> </trans-unit> <trans-unit id="Do_not_show_this_message_again"> <source>Do not show this message again</source> <target state="translated">이 메시지를 다시 표시하지 않음</target> <note /> </trans-unit> <trans-unit id="Do_you_still_want_to_proceed_This_may_produce_broken_code"> <source>Do you still want to proceed? This may produce broken code.</source> <target state="translated">계속하시겠습니까? 계속하면 손상된 코드가 생성될 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Expander_display_text"> <source>items from unimported namespaces</source> <target state="translated">가져오지 않은 네임스페이스의 항목</target> <note /> </trans-unit> <trans-unit id="Expander_image_element"> <source>Expander</source> <target state="translated">확장기</target> <note /> </trans-unit> <trans-unit id="Extract_method_encountered_the_following_issues"> <source>Extract method encountered the following issues:</source> <target state="translated">메서드 추출에서 다음 문제가 발생했습니다.</target> <note /> </trans-unit> <trans-unit id="Filter_image_element"> <source>Filter</source> <target state="translated">필터</target> <note>Caption/tooltip for "Filter" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="For_locals_parameters_and_members"> <source>For locals, parameters and members</source> <target state="translated">로컬, 매개 변수 및 멤버의 경우</target> <note /> </trans-unit> <trans-unit id="For_member_access_expressions"> <source>For member access expressions</source> <target state="translated">멤버 액세스 식의 경우</target> <note /> </trans-unit> <trans-unit id="Format_document_performed_additional_cleanup"> <source>Format Document performed additional cleanup</source> <target state="translated">추가 정리를 수행 하는 문서</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0"> <source>Get help for '{0}'</source> <target state="translated">'{0}'에 대한 도움 받기</target> <note /> </trans-unit> <trans-unit id="Get_help_for_0_from_Bing"> <source>Get help for '{0}' from Bing</source> <target state="translated">Bing에서 '{0}'에 대한 도움 받기</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_0"> <source>Gathering Suggestions - '{0}'</source> <target state="translated">제안을 수집하는 중 - '{0}'</target> <note /> </trans-unit> <trans-unit id="Gathering_Suggestions_Waiting_for_the_solution_to_fully_load"> <source>Gathering Suggestions - Waiting for the solution to fully load</source> <target state="translated">제안을 수집하는 중 - 솔루션이 완전히 로드될 때까지 기다리는 중</target> <note /> </trans-unit> <trans-unit id="Go_To_Base"> <source>Go To Base</source> <target state="translated">기본으로 이동</target> <note /> </trans-unit> <trans-unit id="In_arithmetic_binary_operators"> <source>In arithmetic operators</source> <target state="translated">산술 연산자</target> <note /> </trans-unit> <trans-unit id="In_other_binary_operators"> <source>In other binary operators</source> <target state="translated">기타 이항 연산자</target> <note /> </trans-unit> <trans-unit id="In_other_operators"> <source>In other operators</source> <target state="translated">기타 연산자</target> <note /> </trans-unit> <trans-unit id="In_relational_binary_operators"> <source>In relational operators</source> <target state="translated">관계 연산자</target> <note /> </trans-unit> <trans-unit id="Indentation_Size"> <source>Indentation Size</source> <target state="translated">들여쓰기 크기</target> <note /> </trans-unit> <trans-unit id="Inline_Hints"> <source>Inline Hints</source> <target state="translated">인라인 힌트</target> <note /> </trans-unit> <trans-unit id="Insert_Final_Newline"> <source>Insert Final Newline</source> <target state="translated">최종 줄 바꿈 삽입</target> <note /> </trans-unit> <trans-unit id="Invalid_assembly_name"> <source>Invalid assembly name</source> <target state="translated">잘못된 어셈블리 이름</target> <note /> </trans-unit> <trans-unit id="Invalid_characters_in_assembly_name"> <source>Invalid characters in assembly name</source> <target state="translated">어셈블리 이름에 잘못된 문자가 있음</target> <note /> </trans-unit> <trans-unit id="Keyword_Control"> <source>Keyword - Control</source> <target state="translated">키워드 - 제어</target> <note /> </trans-unit> <trans-unit id="Locating_bases"> <source>Locating bases...</source> <target state="translated">베이스를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Never_if_unnecessary"> <source>Never if unnecessary</source> <target state="translated">필요한 경우 사용 안 함</target> <note /> </trans-unit> <trans-unit id="New_Line"> <source>New Line</source> <target state="translated">줄 바꿈</target> <note /> </trans-unit> <trans-unit id="No"> <source>No</source> <target state="translated">아니요</target> <note /> </trans-unit> <trans-unit id="Non_public_methods"> <source>Non-public methods</source> <target state="translated">public이 아닌 메서드</target> <note /> </trans-unit> <trans-unit id="Operator_Overloaded"> <source>Operator - Overloaded</source> <target state="translated">연산자 - 오버로드됨</target> <note /> </trans-unit> <trans-unit id="Paste_Tracking"> <source>Paste Tracking</source> <target state="translated">붙여넣기 추적</target> <note /> </trans-unit> <trans-unit id="Prefer_System_HashCode_in_GetHashCode"> <source>Prefer 'System.HashCode' in 'GetHashCode'</source> <target state="translated">'GetHashCode'에서 'System.HashCode' 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_coalesce_expression"> <source>Prefer coalesce expression</source> <target state="translated">coalesce 식 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_collection_initializer"> <source>Prefer collection initializer</source> <target state="translated">컬렉션 이니셜라이저 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_compound_assignments"> <source>Prefer compound assignments</source> <target state="translated">복합 대입 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_assignments"> <source>Prefer conditional expression over 'if' with assignments</source> <target state="translated">할당이 포함된 'if'보다 조건식 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_conditional_expression_over_if_with_returns"> <source>Prefer conditional expression over 'if' with returns</source> <target state="translated">반환이 포함된 'if'보다 조건식 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_explicit_tuple_name"> <source>Prefer explicit tuple name</source> <target state="translated">명시적 튜플 이름 기본 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_framework_type"> <source>Prefer framework type</source> <target state="translated">프레임워크 형식 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_anonymous_type_member_names"> <source>Prefer inferred anonymous type member names</source> <target state="translated">유추된 무명 형식 멤버 이름 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_inferred_tuple_names"> <source>Prefer inferred tuple element names</source> <target state="translated">유추된 튜플 요소 이름 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_is_null_for_reference_equality_checks"> <source>Prefer 'is null' for reference equality checks</source> <target state="translated">참조 같음 검사에 대해 'is null' 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_null_propagation"> <source>Prefer null propagation</source> <target state="translated">null 전파 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_object_initializer"> <source>Prefer object initializer</source> <target state="translated">개체 이니셜라이저 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_predefined_type"> <source>Prefer predefined type</source> <target state="translated">미리 정의된 형식 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_readonly_fields"> <source>Prefer readonly fields</source> <target state="translated">읽기 전용 필드 선호</target> <note /> </trans-unit> <trans-unit id="Prefer_simplified_boolean_expressions"> <source>Prefer simplified boolean expressions</source> <target state="translated">간단한 부울 식을 기본으로 사용</target> <note /> </trans-unit> <trans-unit id="Prefer_this_or_Me"> <source>Prefer 'this.' or 'Me.'</source> <target state="translated">'this.' 또는 'Me.'를 기본으로 사용하세요.</target> <note /> </trans-unit> <trans-unit id="Preprocessor_Text"> <source>Preprocessor Text</source> <target state="translated">전처리기 텍스트</target> <note /> </trans-unit> <trans-unit id="Punctuation"> <source>Punctuation</source> <target state="translated">문장 부호</target> <note /> </trans-unit> <trans-unit id="Qualify_event_access_with_this_or_Me"> <source>Qualify event access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 이벤트 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Qualify_field_access_with_this_or_Me"> <source>Qualify field access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 필드 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Qualify_method_access_with_this_or_Me"> <source>Qualify method access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 메서드 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Qualify_property_access_with_this_or_Me"> <source>Qualify property access with 'this' or 'Me'</source> <target state="translated">'this' 또는 'Me'를 사용하여 속성 액세스를 한정합니다.</target> <note /> </trans-unit> <trans-unit id="Reassigned_variable"> <source>Reassigned variable</source> <target state="new">Reassigned variable</target> <note /> </trans-unit> <trans-unit id="Rename_file_name_doesnt_match"> <source>Rename _file (type does not match file name)</source> <target state="translated">파일 이름 바꾸기(형식이 파일 이름과 일치하지 않음)(_F)</target> <note /> </trans-unit> <trans-unit id="Rename_file_partial_type"> <source>Rename _file (not allowed on partial types)</source> <target state="translated">파일 이름 바꾸기(부분 형식에서 허용되지 않음)(_F)</target> <note>Disabled text status for file rename</note> </trans-unit> <trans-unit id="Rename_symbols_file"> <source>Rename symbol's _file</source> <target state="translated">기호의 파일 이름 바꾸기(_F)</target> <note>Indicates that the file a symbol is defined in will also be renamed</note> </trans-unit> <trans-unit id="Split_comment"> <source>Split comment</source> <target state="translated">주석 분할</target> <note /> </trans-unit> <trans-unit id="String_Escape_Character"> <source>String - Escape Character</source> <target state="translated">문자열 - 이스케이프 문자</target> <note /> </trans-unit> <trans-unit id="Symbol_Static"> <source>Symbol - Static</source> <target state="translated">기호 - 정적</target> <note /> </trans-unit> <trans-unit id="Tab_Size"> <source>Tab Size</source> <target state="translated">탭 크기</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_base"> <source>The symbol has no base.</source> <target state="translated">기호에 베이스가 없습니다.</target> <note /> </trans-unit> <trans-unit id="Toggle_Block_Comment"> <source>Toggle Block Comment</source> <target state="translated">블록 주석 토글</target> <note /> </trans-unit> <trans-unit id="Toggle_Line_Comment"> <source>Toggle Line Comment</source> <target state="translated">줄 주석 토글</target> <note /> </trans-unit> <trans-unit id="Toggling_block_comment"> <source>Toggling block comment...</source> <target state="translated">블록 주석을 토글하는 중...</target> <note /> </trans-unit> <trans-unit id="Toggling_line_comment"> <source>Toggling line comment...</source> <target state="translated">줄 주석을 토글하는 중...</target> <note /> </trans-unit> <trans-unit id="Use_Tabs"> <source>Use Tabs</source> <target state="translated">탭 사용</target> <note /> </trans-unit> <trans-unit id="User_Members_Constants"> <source>User Members - Constants</source> <target state="translated">사용자 멤버 - 상수</target> <note /> </trans-unit> <trans-unit id="User_Members_Enum_Members"> <source>User Members - Enum Members</source> <target state="translated">사용자 멤버 - 열거형 멤버</target> <note /> </trans-unit> <trans-unit id="User_Members_Events"> <source>User Members - Events</source> <target state="translated">사용자 멤버 - 이벤트</target> <note /> </trans-unit> <trans-unit id="User_Members_Extension_Methods"> <source>User Members - Extension Methods</source> <target state="translated">사용자 멤버 - 확장 메서드</target> <note /> </trans-unit> <trans-unit id="User_Members_Fields"> <source>User Members - Fields</source> <target state="translated">사용자 멤버 - 필드</target> <note /> </trans-unit> <trans-unit id="User_Members_Labels"> <source>User Members - Labels</source> <target state="translated">사용자 멤버 - 레이블</target> <note /> </trans-unit> <trans-unit id="User_Members_Locals"> <source>User Members - Locals</source> <target state="translated">사용자 멤버 - 로컬</target> <note /> </trans-unit> <trans-unit id="User_Members_Methods"> <source>User Members - Methods</source> <target state="translated">사용자 멤버 - 메서드</target> <note /> </trans-unit> <trans-unit id="User_Members_Namespaces"> <source>User Members - Namespaces</source> <target state="translated">사용자 멤버 - 네임스페이스</target> <note /> </trans-unit> <trans-unit id="User_Members_Parameters"> <source>User Members - Parameters</source> <target state="translated">사용자 멤버 - 매개 변수</target> <note /> </trans-unit> <trans-unit id="User_Members_Properties"> <source>User Members - Properties</source> <target state="translated">사용자 멤버 - 속성</target> <note /> </trans-unit> <trans-unit id="User_Types_Classes"> <source>User Types - Classes</source> <target state="translated">사용자 형식 - 클래스</target> <note /> </trans-unit> <trans-unit id="User_Types_Delegates"> <source>User Types - Delegates</source> <target state="translated">사용자 형식 - 대리자</target> <note /> </trans-unit> <trans-unit id="User_Types_Enums"> <source>User Types - Enums</source> <target state="translated">사용자 형식 - 열거형</target> <note /> </trans-unit> <trans-unit id="User_Types_Interfaces"> <source>User Types - Interfaces</source> <target state="translated">사용자 형식 - 인터페이스</target> <note /> </trans-unit> <trans-unit id="User_Types_Record_Structs"> <source>User Types - Record Structs</source> <target state="new">User Types - Record Structs</target> <note /> </trans-unit> <trans-unit id="User_Types_Records"> <source>User Types - Records</source> <target state="translated">사용자 유형 - 레코드</target> <note /> </trans-unit> <trans-unit id="User_Types_Structures"> <source>User Types - Structures</source> <target state="translated">사용자 형식 - 구조</target> <note /> </trans-unit> <trans-unit id="User_Types_Type_Parameters"> <source>User Types - Type Parameters</source> <target state="translated">사용자 형식 - 형식 매개 변수</target> <note /> </trans-unit> <trans-unit id="String_Verbatim"> <source>String - Verbatim</source> <target state="translated">문자열 - 축자</target> <note /> </trans-unit> <trans-unit id="Waiting_for_background_work_to_finish"> <source>Waiting for background work to finish...</source> <target state="translated">백그라운드 작업이 완료될 때까지 대기 중...</target> <note /> </trans-unit> <trans-unit id="Warning_image_element"> <source>Warning</source> <target state="translated">경고</target> <note>Caption/tooltip for "Warning" image element displayed in completion popup.</note> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Name"> <source>XML Doc Comments - Attribute Name</source> <target state="translated">XML 문서 주석 - 특성 이름</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_CData_Section"> <source>XML Doc Comments - CData Section</source> <target state="translated">XML 문서 주석 - CData 섹션</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Text"> <source>XML Doc Comments - Text</source> <target state="translated">XML 문서 주석 - 텍스트</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Delimiter"> <source>XML Doc Comments - Delimiter</source> <target state="translated">XML 문서 주석 - 구분 기호</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Comment"> <source>XML Doc Comments - Comment</source> <target state="translated">XML 문서 주석 - 주석</target> <note /> </trans-unit> <trans-unit id="User_Types_Modules"> <source>User Types - Modules</source> <target state="translated">사용자 형식 - 모듈</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Name"> <source>VB XML Literals - Attribute Name</source> <target state="translated">VB XML 리터럴 - 특성 이름</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Quotes"> <source>VB XML Literals - Attribute Quotes</source> <target state="translated">VB XML 리터럴 - 특성 인용 문자</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Attribute_Value"> <source>VB XML Literals - Attribute Value</source> <target state="translated">VB XML 리터럴 - 특성 값</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_CData_Section"> <source>VB XML Literals - CData Section</source> <target state="translated">VB XML 리터럴 - CData 섹션</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Comment"> <source>VB XML Literals - Comment</source> <target state="translated">VB XML 리터럴 - 주석</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Delimiter"> <source>VB XML Literals - Delimiter</source> <target state="translated">VB XML 리터럴 - 구분 기호</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Embedded_Expression"> <source>VB XML Literals - Embedded Expression</source> <target state="translated">VB XML 리터럴 - 포함 식</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Entity_Reference"> <source>VB XML Literals - Entity Reference</source> <target state="translated">VB XML 리터럴 - 엔터티 참조</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Name"> <source>VB XML Literals - Name</source> <target state="translated">VB XML 리터럴 - 이름</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Processing_Instruction"> <source>VB XML Literals - Processing Instruction</source> <target state="translated">VB XML 리터럴 - 처리 명령</target> <note /> </trans-unit> <trans-unit id="VB_XML_Literals_Text"> <source>VB XML Literals - Text</source> <target state="translated">VB XML 리터럴 - 텍스트</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Quotes"> <source>XML Doc Comments - Attribute Quotes</source> <target state="translated">XML 문서 주석 - 특성 인용 문자</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Attribute_Value"> <source>XML Doc Comments - Attribute Value</source> <target state="translated">XML 문서 주석 - 특성 값</target> <note /> </trans-unit> <trans-unit id="Unnecessary_Code"> <source>Unnecessary Code</source> <target state="translated">불필요한 코드</target> <note /> </trans-unit> <trans-unit id="Rude_Edit"> <source>Rude Edit</source> <target state="translated">편집 다시 실행</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_1_reference_in_1_file"> <source>Rename will update 1 reference in 1 file.</source> <target state="translated">이름 바꾸기로 1개의 파일에서 1개의 참조가 업데이트됩니다.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_file"> <source>Rename will update {0} references in 1 file.</source> <target state="translated">이름 바꾸기로 1개의 파일에서 {0}개의 참조가 업데이트됩니다.</target> <note /> </trans-unit> <trans-unit id="Rename_will_update_0_references_in_1_files"> <source>Rename will update {0} references in {1} files.</source> <target state="translated">이름 바꾸기로 {1}개의 파일에서 {0}개의 참조가 업데이트됩니다.</target> <note /> </trans-unit> <trans-unit id="Yes"> <source>Yes</source> <target state="translated">예</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_contained_in_a_read_only_file"> <source>You cannot rename this element because it is contained in a read-only file.</source> <target state="translated">이 요소는 읽기 전용 파일에 포함되어 있으므로 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element_because_it_is_in_a_location_that_cannot_be_navigated_to"> <source>You cannot rename this element because it is in a location that cannot be navigated to.</source> <target state="translated">이 요소는 탐색할 수 없는 위치에 있으므로 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="_0_bases"> <source>'{0}' bases</source> <target state="translated">'{0}' 기본</target> <note /> </trans-unit> <trans-unit id="_0_conflict_s_will_be_resolved"> <source>{0} conflict(s) will be resolved</source> <target state="translated">충돌 {0}개가 해결됩니다.</target> <note /> </trans-unit> <trans-unit id="_0_implemented_members"> <source>'{0}' implemented members</source> <target state="translated">구현된 멤버 '{0}'개</target> <note /> </trans-unit> <trans-unit id="_0_unresolvable_conflict_s"> <source>{0} unresolvable conflict(s)</source> <target state="translated">해결할 수 없는 충돌 {0}개</target> <note /> </trans-unit> <trans-unit id="Applying_0"> <source>Applying "{0}"...</source> <target state="translated">"{0}" 적용 중...</target> <note /> </trans-unit> <trans-unit id="Adding_0_to_1_with_content_colon"> <source>Adding '{0}' to '{1}' with content:</source> <target state="translated">다음 콘텐츠가 있는 '{1}'에 대한 '{0}' 추가 중:</target> <note /> </trans-unit> <trans-unit id="Adding_project_0"> <source>Adding project '{0}'</source> <target state="translated">'{0}' 프로젝트 추가 중</target> <note /> </trans-unit> <trans-unit id="Removing_project_0"> <source>Removing project '{0}'</source> <target state="translated">'{0}' 프로젝트를 제거하는 중</target> <note /> </trans-unit> <trans-unit id="Changing_project_references_for_0"> <source>Changing project references for '{0}'</source> <target state="translated">'{0}'에 대한 프로젝트 참조 변경 중</target> <note /> </trans-unit> <trans-unit id="Adding_reference_0_to_1"> <source>Adding reference '{0}' to '{1}'</source> <target state="translated">'{1}'에 대한 '{0}' 참조 추가 중</target> <note /> </trans-unit> <trans-unit id="Removing_reference_0_from_1"> <source>Removing reference '{0}' from '{1}'</source> <target state="translated">'{1}'에서 '{0}' 참조를 제거하는 중</target> <note /> </trans-unit> <trans-unit id="Adding_analyzer_reference_0_to_1"> <source>Adding analyzer reference '{0}' to '{1}'</source> <target state="translated">'{1}'에 대한 '{0}' 분석기 참조 추가 중</target> <note /> </trans-unit> <trans-unit id="Removing_analyzer_reference_0_from_1"> <source>Removing analyzer reference '{0}' from '{1}'</source> <target state="translated">'{1}'에서 '{0}' 분석기 참조를 제거하는 중</target> <note /> </trans-unit> <trans-unit id="XML_End_Tag_Completion"> <source>XML End Tag Completion</source> <target state="translated">XML 끝 태그 완료</target> <note /> </trans-unit> <trans-unit id="Completing_Tag"> <source>Completing Tag</source> <target state="translated">태그 완료 중</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field"> <source>Encapsulate Field</source> <target state="translated">필드 캡슐화</target> <note /> </trans-unit> <trans-unit id="Applying_Encapsulate_Field_refactoring"> <source>Applying "Encapsulate Field" refactoring...</source> <target state="translated">"필드 캡슐화" 리팩토링 적용 중...</target> <note /> </trans-unit> <trans-unit id="Please_select_the_definition_of_the_field_to_encapsulate"> <source>Please select the definition of the field to encapsulate.</source> <target state="translated">캡슐화할 필드의 정의를 선택하세요.</target> <note /> </trans-unit> <trans-unit id="Given_Workspace_doesn_t_support_Undo"> <source>Given Workspace doesn't support Undo</source> <target state="translated">지정한 작업 영역에서 실행을 취소할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Searching"> <source>Searching...</source> <target state="translated">검색 중...</target> <note /> </trans-unit> <trans-unit id="Canceled"> <source>Canceled.</source> <target state="translated">취소되었습니다.</target> <note /> </trans-unit> <trans-unit id="No_information_found"> <source>No information found.</source> <target state="translated">정보를 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="No_usages_found"> <source>No usages found.</source> <target state="translated">사용법을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Implements_"> <source>Implements</source> <target state="translated">구현</target> <note /> </trans-unit> <trans-unit id="Implemented_By"> <source>Implemented By</source> <target state="translated">구현자</target> <note /> </trans-unit> <trans-unit id="Overrides_"> <source>Overrides</source> <target state="translated">재정의</target> <note /> </trans-unit> <trans-unit id="Overridden_By"> <source>Overridden By</source> <target state="translated">재정의 수행자</target> <note /> </trans-unit> <trans-unit id="Directly_Called_In"> <source>Directly Called In</source> <target state="translated">직접 호출됨</target> <note /> </trans-unit> <trans-unit id="Indirectly_Called_In"> <source>Indirectly Called In</source> <target state="translated">간접적으로 호출됨</target> <note /> </trans-unit> <trans-unit id="Called_In"> <source>Called In</source> <target state="translated">호출됨</target> <note /> </trans-unit> <trans-unit id="Referenced_In"> <source>Referenced In</source> <target state="translated">참조됨</target> <note /> </trans-unit> <trans-unit id="No_references_found"> <source>No references found.</source> <target state="translated">참조를 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="No_derived_types_found"> <source>No derived types found.</source> <target state="translated">파생 형식을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="No_implementations_found"> <source>No implementations found.</source> <target state="translated">구현을 찾을 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="_0_Line_1"> <source>{0} - (Line {1})</source> <target state="translated">{0} - (줄 {1})</target> <note /> </trans-unit> <trans-unit id="Class_Parts"> <source>Class Parts</source> <target state="translated">클래스 파트</target> <note /> </trans-unit> <trans-unit id="Struct_Parts"> <source>Struct Parts</source> <target state="translated">구조체 파트</target> <note /> </trans-unit> <trans-unit id="Interface_Parts"> <source>Interface Parts</source> <target state="translated">인터페이스 파트</target> <note /> </trans-unit> <trans-unit id="Type_Parts"> <source>Type Parts</source> <target state="translated">형식 파트</target> <note /> </trans-unit> <trans-unit id="Inherits_"> <source>Inherits</source> <target state="translated">상속</target> <note /> </trans-unit> <trans-unit id="Inherited_By"> <source>Inherited By</source> <target state="translated">상속 대상</target> <note /> </trans-unit> <trans-unit id="Already_tracking_document_with_identical_key"> <source>Already tracking document with identical key</source> <target state="translated">동일한 키로 이미 문서를 추적하는 중</target> <note /> </trans-unit> <trans-unit id="analyzer_Prefer_auto_properties"> <source>Prefer auto properties</source> <target state="translated">자동 속성 선호</target> <note /> </trans-unit> <trans-unit id="document_is_not_currently_being_tracked"> <source>document is not currently being tracked</source> <target state="translated">문서를 현재 추적하고 있지 않습니다.</target> <note /> </trans-unit> <trans-unit id="Computing_Rename_information"> <source>Computing Rename information...</source> <target state="translated">이름 바꾸기 정보 계산 중...</target> <note /> </trans-unit> <trans-unit id="Updating_files"> <source>Updating files...</source> <target state="translated">파일 업데이트 중...</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_cancelled_or_is_not_valid"> <source>Rename operation was cancelled or is not valid</source> <target state="translated">이름 바꾸기 작업이 취소되었거나 잘못되었습니다.</target> <note /> </trans-unit> <trans-unit id="Rename_Symbol"> <source>Rename Symbol</source> <target state="translated">기호 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Text_Buffer_Change"> <source>Text Buffer Change</source> <target state="translated">텍스트 버퍼 변경</target> <note /> </trans-unit> <trans-unit id="Rename_operation_was_not_properly_completed_Some_file_might_not_have_been_updated"> <source>Rename operation was not properly completed. Some file might not have been updated.</source> <target state="translated">이름 바꾸기 작업이 제대로 완료되지 않았습니다. 일부 파일이 업데이트되지 않았을 수 있습니다.</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1"> <source>Rename '{0}' to '{1}'</source> <target state="translated">'{1}'(으)로 '{0}' 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Preview_Warning"> <source>Preview Warning</source> <target state="translated">경고 미리 보기</target> <note /> </trans-unit> <trans-unit id="external"> <source>(external)</source> <target state="translated">(외부)</target> <note /> </trans-unit> <trans-unit id="Automatic_Line_Ender"> <source>Automatic Line Ender</source> <target state="translated">자동 줄 끝내기</target> <note /> </trans-unit> <trans-unit id="Automatically_completing"> <source>Automatically completing...</source> <target state="translated">자동 완성 중...</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion"> <source>Automatic Pair Completion</source> <target state="translated">자동 쌍 완성</target> <note /> </trans-unit> <trans-unit id="An_active_inline_rename_session_is_still_active_Complete_it_before_starting_a_new_one"> <source>An active inline rename session is still active. Complete it before starting a new one.</source> <target state="translated">활성 인라인 이름 바꾸기 세션이 여전히 활성화되어 있습니다. 새 세션을 시작하기 전에 완료하세요.</target> <note /> </trans-unit> <trans-unit id="The_buffer_is_not_part_of_a_workspace"> <source>The buffer is not part of a workspace.</source> <target state="translated">버퍼는 작업 영역의 일부가 아닙니다.</target> <note /> </trans-unit> <trans-unit id="The_token_is_not_contained_in_the_workspace"> <source>The token is not contained in the workspace.</source> <target state="translated">토큰이 작업 영역에 포함되어 있지 않습니다.</target> <note /> </trans-unit> <trans-unit id="You_must_rename_an_identifier"> <source>You must rename an identifier.</source> <target state="translated">식별자의 이름을 바꿔야 합니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_this_element"> <source>You cannot rename this element.</source> <target state="translated">이 요소의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Please_resolve_errors_in_your_code_before_renaming_this_element"> <source>Please resolve errors in your code before renaming this element.</source> <target state="translated">이 요소의 이름을 바꾸기 전에 코드 오류를 해결하세요.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_operators"> <source>You cannot rename operators.</source> <target state="translated">연산자의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_that_are_defined_in_metadata"> <source>You cannot rename elements that are defined in metadata.</source> <target state="translated">메타데이터에서 정의된 요소의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="You_cannot_rename_elements_from_previous_submissions"> <source>You cannot rename elements from previous submissions.</source> <target state="translated">이전 전송 요소의 이름을 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Navigation_Bars"> <source>Navigation Bars</source> <target state="translated">탐색 모음</target> <note /> </trans-unit> <trans-unit id="Refreshing_navigation_bars"> <source>Refreshing navigation bars...</source> <target state="translated">탐색 모음을 새로 고치는 중...</target> <note /> </trans-unit> <trans-unit id="Format_Token"> <source>Format Token</source> <target state="translated">형식 토큰</target> <note /> </trans-unit> <trans-unit id="Smart_Indenting"> <source>Smart Indenting</source> <target state="translated">스마트 들여쓰기</target> <note /> </trans-unit> <trans-unit id="Find_References"> <source>Find References</source> <target state="translated">참조 찾기</target> <note /> </trans-unit> <trans-unit id="Finding_references"> <source>Finding references...</source> <target state="translated">참조를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_references_of_0"> <source>Finding references of "{0}"...</source> <target state="translated">"{0}"의 참조를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Comment_Selection"> <source>Comment Selection</source> <target state="translated">선택 영역을 주석으로 처리</target> <note /> </trans-unit> <trans-unit id="Uncomment_Selection"> <source>Uncomment Selection</source> <target state="translated">선택 영역의 주석 처리 제거</target> <note /> </trans-unit> <trans-unit id="Commenting_currently_selected_text"> <source>Commenting currently selected text...</source> <target state="translated">현재 선택한 텍스트를 주석으로 처리하는 중...</target> <note /> </trans-unit> <trans-unit id="Uncommenting_currently_selected_text"> <source>Uncommenting currently selected text...</source> <target state="translated">현재 선택한 텍스트의 주석 처리를 제거하는 중...</target> <note /> </trans-unit> <trans-unit id="Insert_new_line"> <source>Insert new line</source> <target state="translated">새 줄 삽입</target> <note /> </trans-unit> <trans-unit id="Documentation_Comment"> <source>Documentation Comment</source> <target state="translated">문서 주석</target> <note /> </trans-unit> <trans-unit id="Inserting_documentation_comment"> <source>Inserting documentation comment...</source> <target state="translated">문서 주석 삽입 중...</target> <note /> </trans-unit> <trans-unit id="Extract_Method"> <source>Extract Method</source> <target state="translated">메서드 추출</target> <note /> </trans-unit> <trans-unit id="Applying_Extract_Method_refactoring"> <source>Applying "Extract Method" refactoring...</source> <target state="translated">"메서드 추출" 리팩토링 적용 중...</target> <note /> </trans-unit> <trans-unit id="Format_Document"> <source>Format Document</source> <target state="translated">문서 서식</target> <note /> </trans-unit> <trans-unit id="Formatting_document"> <source>Formatting document...</source> <target state="translated">문서 서식을 지정하는 중...</target> <note /> </trans-unit> <trans-unit id="Formatting"> <source>Formatting</source> <target state="translated">서식</target> <note /> </trans-unit> <trans-unit id="Format_Selection"> <source>Format Selection</source> <target state="translated">선택 영역 서식</target> <note /> </trans-unit> <trans-unit id="Formatting_currently_selected_text"> <source>Formatting currently selected text...</source> <target state="translated">현재 선택한 텍스트의 서식을 지정하는 중...</target> <note /> </trans-unit> <trans-unit id="Cannot_navigate_to_the_symbol_under_the_caret"> <source>Cannot navigate to the symbol under the caret.</source> <target state="translated">캐럿에서 기호를 탐색할 수 없습니다.</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="Navigating_to_definition"> <source>Navigating to definition...</source> <target state="translated">정의를 탐색하는 중...</target> <note /> </trans-unit> <trans-unit id="Organize_Document"> <source>Organize Document</source> <target state="translated">문서 구성</target> <note /> </trans-unit> <trans-unit id="Organizing_document"> <source>Organizing document...</source> <target state="translated">문서 구성 중...</target> <note /> </trans-unit> <trans-unit id="Highlighted_Definition"> <source>Highlighted Definition</source> <target state="translated">강조 표시된 정의</target> <note /> </trans-unit> <trans-unit id="The_new_name_is_not_a_valid_identifier"> <source>The new name is not a valid identifier.</source> <target state="translated">새 이름이 유효한 식별자가 아닙니다.</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Fixup"> <source>Inline Rename Fixup</source> <target state="translated">인라인 이름 바꾸기 픽스업</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Resolved_Conflict"> <source>Inline Rename Resolved Conflict</source> <target state="translated">인라인 이름 바꾸기의 충돌이 해결됨</target> <note /> </trans-unit> <trans-unit id="Inline_Rename"> <source>Inline Rename</source> <target state="translated">인라인 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Rename"> <source>Rename</source> <target state="translated">이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Start_Rename"> <source>Start Rename</source> <target state="translated">이름 바꾸기 시작</target> <note /> </trans-unit> <trans-unit id="Display_conflict_resolutions"> <source>Display conflict resolutions</source> <target state="translated">충돌 해결 표시</target> <note /> </trans-unit> <trans-unit id="Finding_token_to_rename"> <source>Finding token to rename...</source> <target state="translated">이름을 바꿀 토큰을 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Conflict"> <source>Conflict</source> <target state="translated">충돌</target> <note /> </trans-unit> <trans-unit id="Text_Navigation"> <source>Text Navigation</source> <target state="translated">텍스트 탐색</target> <note /> </trans-unit> <trans-unit id="Finding_word_extent"> <source>Finding word extent...</source> <target state="translated">단어 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_enclosing_span"> <source>Finding enclosing span...</source> <target state="translated">바깥쪽 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_next_sibling"> <source>Finding span of next sibling...</source> <target state="translated">다음 형제의 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Finding_span_of_previous_sibling"> <source>Finding span of previous sibling...</source> <target state="translated">이전 형제의 범위를 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Rename_colon_0"> <source>Rename: {0}</source> <target state="translated">이름 바꾸기: {0}</target> <note /> </trans-unit> <trans-unit id="Light_bulb_session_is_already_dismissed"> <source>Light bulb session is already dismissed.</source> <target state="translated">전구 세션이 이미 해제되었습니다.</target> <note /> </trans-unit> <trans-unit id="Automatic_Pair_Completion_End_Point_Marker_Color"> <source>Automatic Pair Completion End Point Marker Color</source> <target state="translated">자동 쌍 완성 끝점 표식 색</target> <note /> </trans-unit> <trans-unit id="Renaming_anonymous_type_members_is_not_yet_supported"> <source>Renaming anonymous type members is not yet supported.</source> <target state="translated">익명 형식의 멤버 이름은 아직 바꿀 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Engine_must_be_attached_to_an_Interactive_Window"> <source>Engine must be attached to an Interactive Window.</source> <target state="translated">엔진은 대화형 창에 연결되어 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Changes_the_current_prompt_settings"> <source>Changes the current prompt settings.</source> <target state="translated">현재 프롬프트 설정을 변경합니다.</target> <note /> </trans-unit> <trans-unit id="Unexpected_text_colon_0"> <source>Unexpected text: '{0}'</source> <target state="translated">예기치 않은 텍스트: '{0}'</target> <note /> </trans-unit> <trans-unit id="The_triggerSpan_is_not_included_in_the_given_workspace"> <source>The triggerSpan is not included in the given workspace.</source> <target state="translated">triggerSpan이 지정한 작업 영역에 포함되어 있지 않습니다.</target> <note /> </trans-unit> <trans-unit id="This_session_has_already_been_dismissed"> <source>This session has already been dismissed.</source> <target state="translated">이 세션은 이미 해제되었습니다.</target> <note /> </trans-unit> <trans-unit id="The_transaction_is_already_complete"> <source>The transaction is already complete.</source> <target state="translated">트랜잭션이 이미 완료되었습니다.</target> <note /> </trans-unit> <trans-unit id="Not_a_source_error_line_column_unavailable"> <source>Not a source error, line/column unavailable</source> <target state="translated">원본 오류가 아닙니다. 줄/열을 사용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Can_t_compare_positions_from_different_text_snapshots"> <source>Can't compare positions from different text snapshots</source> <target state="translated">다른 텍스트 스냅샷에서 위치를 비교할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Entity_Reference"> <source>XML Doc Comments - Entity Reference</source> <target state="translated">XML 문서 주석 - 엔터티 참조</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Name"> <source>XML Doc Comments - Name</source> <target state="translated">XML 문서 주석 - 이름</target> <note /> </trans-unit> <trans-unit id="XML_Doc_Comments_Processing_Instruction"> <source>XML Doc Comments - Processing Instruction</source> <target state="translated">XML 문서 주석 - 처리 명령</target> <note /> </trans-unit> <trans-unit id="Active_Statement"> <source>Active Statement</source> <target state="translated">활성 문</target> <note /> </trans-unit> <trans-unit id="Loading_Peek_information"> <source>Loading Peek information...</source> <target state="translated">정보 피킹을 로드하는 중...</target> <note /> </trans-unit> <trans-unit id="Peek"> <source>Peek</source> <target state="translated">피킹</target> <note /> </trans-unit> <trans-unit id="Apply1"> <source>_Apply</source> <target state="translated">적용(_A)</target> <note /> </trans-unit> <trans-unit id="Include_overload_s"> <source>Include _overload(s)</source> <target state="translated">오버로드 포함(_O)</target> <note /> </trans-unit> <trans-unit id="Include_comments"> <source>Include _comments</source> <target state="translated">주석 포함(_C)</target> <note /> </trans-unit> <trans-unit id="Include_strings"> <source>Include _strings</source> <target state="translated">문자열 포함(_S)</target> <note /> </trans-unit> <trans-unit id="Apply2"> <source>Apply</source> <target state="translated">적용</target> <note /> </trans-unit> <trans-unit id="Change_Signature"> <source>Change Signature</source> <target state="translated">시그니처 변경</target> <note /> </trans-unit> <trans-unit id="Preview_Changes_0"> <source>Preview Changes - {0}</source> <target state="translated">변경 내용 미리 보기 - {0}</target> <note /> </trans-unit> <trans-unit id="Preview_Code_Changes_colon"> <source>Preview Code Changes:</source> <target state="translated">코드 변경 내용 미리 보기:</target> <note /> </trans-unit> <trans-unit id="Preview_Changes"> <source>Preview Changes</source> <target state="translated">변경 내용 미리 보기</target> <note /> </trans-unit> <trans-unit id="Format_Paste"> <source>Format Paste</source> <target state="translated">서식 붙여넣기</target> <note /> </trans-unit> <trans-unit id="Formatting_pasted_text"> <source>Formatting pasted text...</source> <target state="translated">붙여넣은 텍스트의 서식을 지정하는 중...</target> <note /> </trans-unit> <trans-unit id="The_definition_of_the_object_is_hidden"> <source>The definition of the object is hidden.</source> <target state="translated">개체의 정의가 숨겨집니다.</target> <note /> </trans-unit> <trans-unit id="Automatic_Formatting"> <source>Automatic Formatting</source> <target state="translated">자동 서식</target> <note /> </trans-unit> <trans-unit id="We_can_fix_the_error_by_not_making_struct_out_ref_parameter_s_Do_you_want_to_proceed"> <source>We can fix the error by not making struct "out/ref" parameter(s). Do you want to proceed?</source> <target state="translated">구조체 "out/ref" 매개 변수를 만들지 않는 방법으로 오류를 수정할 수 있습니다. 계속하시겠습니까?</target> <note /> </trans-unit> <trans-unit id="Change_Signature_colon"> <source>Change Signature:</source> <target state="translated">시그니처 변경:</target> <note /> </trans-unit> <trans-unit id="Rename_0_to_1_colon"> <source>Rename '{0}' to '{1}':</source> <target state="translated">'{0}'에서 '{1}'(으)로 이름 바꾸기:</target> <note /> </trans-unit> <trans-unit id="Encapsulate_Field_colon"> <source>Encapsulate Field:</source> <target state="translated">필드 캡슐화:</target> <note /> </trans-unit> <trans-unit id="Call_Hierarchy"> <source>Call Hierarchy</source> <target state="translated">호출 계층 구조</target> <note /> </trans-unit> <trans-unit id="Calls_To_0"> <source>Calls To '{0}'</source> <target state="translated">'{0}'에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Calls_To_Base_Member_0"> <source>Calls To Base Member '{0}'</source> <target state="translated">'{0}' 기본 멤버에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Calls_To_Interface_Implementation_0"> <source>Calls To Interface Implementation '{0}'</source> <target state="translated">'{0}' 인터페이스 구현에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Computing_Call_Hierarchy_Information"> <source>Computing Call Hierarchy Information</source> <target state="translated">호출 계층 구조 정보 계산 중</target> <note /> </trans-unit> <trans-unit id="Implements_0"> <source>Implements '{0}'</source> <target state="translated">'{0}' 구현</target> <note /> </trans-unit> <trans-unit id="Initializers"> <source>Initializers</source> <target state="translated">이니셜라이저</target> <note /> </trans-unit> <trans-unit id="References_To_Field_0"> <source>References To Field '{0}'</source> <target state="translated">'{0}' 필드에 대한 참조</target> <note /> </trans-unit> <trans-unit id="Calls_To_Overrides"> <source>Calls To Overrides</source> <target state="translated">재정의에 대한 호출</target> <note /> </trans-unit> <trans-unit id="Preview_changes1"> <source>_Preview changes</source> <target state="translated">변경 사항 미리 보기(_P)</target> <note /> </trans-unit> <trans-unit id="Apply3"> <source>Apply</source> <target state="translated">적용</target> <note /> </trans-unit> <trans-unit id="Cancel"> <source>Cancel</source> <target state="translated">취소</target> <note /> </trans-unit> <trans-unit id="Changes"> <source>Changes</source> <target state="translated">변경 내용</target> <note /> </trans-unit> <trans-unit id="Preview_changes2"> <source>Preview changes</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="IntelliSense_Commit_Formatting"> <source>IntelliSense Commit Formatting</source> <target state="translated">IntelliSense 커밋 서식</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking"> <source>Rename Tracking</source> <target state="translated">추적 이름 바꾸기</target> <note /> </trans-unit> <trans-unit id="Removing_0_from_1_with_content_colon"> <source>Removing '{0}' from '{1}' with content:</source> <target state="translated">다음 내용과 함께 '{1}'에서 '{0}'을(를) 제거 중:</target> <note /> </trans-unit> <trans-unit id="_0_does_not_support_the_1_operation_However_it_may_contain_nested_2_s_see_2_3_that_support_this_operation"> <source>'{0}' does not support the '{1}' operation. However, it may contain nested '{2}'s (see '{2}.{3}') that support this operation.</source> <target state="translated">'{0}'은(는) '{1}' 작업을 지원하지 않습니다. 하지만 이 작업을 지원하는 중첩 '{2}'을(를) 포함할 수 있습니다('{2}.{3}' 참조).</target> <note /> </trans-unit> <trans-unit id="Brace_Completion"> <source>Brace Completion</source> <target state="translated">중괄호 완성</target> <note /> </trans-unit> <trans-unit id="Cannot_apply_operation_while_a_rename_session_is_active"> <source>Cannot apply operation while a rename session is active.</source> <target state="translated">이름 바꾸기 세션이 활성인 동안에는 작업을 적용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="The_rename_tracking_session_was_cancelled_and_is_no_longer_available"> <source>The rename tracking session was cancelled and is no longer available.</source> <target state="translated">이름 바꾸기 추적 세션이 취소되었고 더 이상 사용할 수 없습니다.</target> <note /> </trans-unit> <trans-unit id="Highlighted_Written_Reference"> <source>Highlighted Written Reference</source> <target state="translated">강조 표시되어 작성된 참조</target> <note /> </trans-unit> <trans-unit id="Cursor_must_be_on_a_member_name"> <source>Cursor must be on a member name.</source> <target state="translated">커서는 멤버 이름에 있어야 합니다.</target> <note /> </trans-unit> <trans-unit id="Brace_Matching"> <source>Brace Matching</source> <target state="translated">중괄호 일치</target> <note /> </trans-unit> <trans-unit id="Locating_implementations"> <source>Locating implementations...</source> <target state="translated">구현을 찾는 중...</target> <note /> </trans-unit> <trans-unit id="Go_To_Implementation"> <source>Go To Implementation</source> <target state="translated">구현으로 이동</target> <note /> </trans-unit> <trans-unit id="The_symbol_has_no_implementations"> <source>The symbol has no implementations.</source> <target state="translated">기호에 구현이 없습니다.</target> <note /> </trans-unit> <trans-unit id="New_name_colon_0"> <source>New name: {0}</source> <target state="translated">새 이름: {0}</target> <note /> </trans-unit> <trans-unit id="Modify_any_highlighted_location_to_begin_renaming"> <source>Modify any highlighted location to begin renaming.</source> <target state="translated">이름 변경을 시작할 강조 표시된 위치를 수정합니다.</target> <note /> </trans-unit> <trans-unit id="Paste"> <source>Paste</source> <target state="translated">붙여넣기</target> <note /> </trans-unit> <trans-unit id="Navigating"> <source>Navigating...</source> <target state="translated">탐색하는 중...</target> <note /> </trans-unit> <trans-unit id="Suggestion_ellipses"> <source>Suggestion ellipses (…)</source> <target state="translated">제안 줄임표(…)</target> <note /> </trans-unit> <trans-unit id="_0_references"> <source>'{0}' references</source> <target state="translated">'{0}' 참조</target> <note /> </trans-unit> <trans-unit id="_0_implementations"> <source>'{0}' implementations</source> <target state="translated">'{0}' 구현</target> <note /> </trans-unit> <trans-unit id="_0_declarations"> <source>'{0}' declarations</source> <target state="translated">'{0}' 선언</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Conflict"> <source>Inline Rename Conflict</source> <target state="translated">인라인 이름 바꾸기 충돌</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Background_and_Border"> <source>Inline Rename Field Background and Border</source> <target state="translated">인라인 이름 바꾸기 필드 배경 및 테두리</target> <note /> </trans-unit> <trans-unit id="Inline_Rename_Field_Text"> <source>Inline Rename Field Text</source> <target state="translated">인라인 이름 바꾸기 필드 텍스트</target> <note /> </trans-unit> <trans-unit id="Block_Comment_Editing"> <source>Block Comment Editing</source> <target state="translated">주석 편집 차단</target> <note /> </trans-unit> <trans-unit id="Comment_Uncomment_Selection"> <source>Comment/Uncomment Selection</source> <target state="translated">선택 영역 주석 처리/주석 처리 제거</target> <note /> </trans-unit> <trans-unit id="Code_Completion"> <source>Code Completion</source> <target state="translated">코드 완성</target> <note /> </trans-unit> <trans-unit id="Execute_In_Interactive"> <source>Execute In Interactive</source> <target state="translated">대화형으로 실행</target> <note /> </trans-unit> <trans-unit id="Extract_Interface"> <source>Extract Interface</source> <target state="translated">인터페이스 추출</target> <note /> </trans-unit> <trans-unit id="Go_To_Adjacent_Member"> <source>Go To Adjacent Member</source> <target state="translated">인접 멤버로 이동</target> <note /> </trans-unit> <trans-unit id="Interactive"> <source>Interactive</source> <target state="translated">대화형</target> <note /> </trans-unit> <trans-unit id="Paste_in_Interactive"> <source>Paste in Interactive</source> <target state="translated">대화형으로 붙여넣기</target> <note /> </trans-unit> <trans-unit id="Navigate_To_Highlight_Reference"> <source>Navigate To Highlighted Reference</source> <target state="translated">강조 표시 참조로 이동</target> <note /> </trans-unit> <trans-unit id="Outlining"> <source>Outlining</source> <target state="translated">개요</target> <note /> </trans-unit> <trans-unit id="Rename_Tracking_Cancellation"> <source>Rename Tracking Cancellation</source> <target state="translated">추적 이름 바꾸기 취소</target> <note /> </trans-unit> <trans-unit id="Signature_Help"> <source>Signature Help</source> <target state="translated">시그니처 도움말</target> <note /> </trans-unit> <trans-unit id="Smart_Token_Formatter"> <source>Smart Token Formatter</source> <target state="translated">스마트 토큰 포맷터</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test/Diagnostics/AnalyzerLoadFailureTests.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 enable using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class AnalyzerLoadFailureTests { [Theory] [CombinatorialData] public void CanCreateDiagnosticForAnalyzerLoadFailure( AnalyzerLoadFailureEventArgs.FailureErrorCode errorCode, [CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic, null)] string? languageName) { // One potential value is None, which isn't actually a valid enum value to test. if (errorCode == AnalyzerLoadFailureEventArgs.FailureErrorCode.None) { return; } var expectsTypeName = errorCode is AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer or AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework; const string analyzerTypeName = "AnalyzerTypeName"; var eventArgs = new AnalyzerLoadFailureEventArgs( errorCode, message: errorCode.ToString(), typeNameOpt: expectsTypeName ? analyzerTypeName : null); // Ensure CreateAnalyzerLoadFailureDiagnostic doesn't fail when called. We don't assert much about the resulting // diagnostic -- this is primarly to ensure we don't forget to update it if a new error code is added. var diagnostic = AnalyzerHelper.CreateAnalyzerLoadFailureDiagnostic(eventArgs, "Analyzer.dll", null, languageName); Assert.Equal(languageName, diagnostic.Language); if (expectsTypeName) { Assert.Contains(analyzerTypeName, diagnostic.Message); } else { Assert.DoesNotContain(analyzerTypeName, diagnostic.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 enable using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { public class AnalyzerLoadFailureTests { [Theory] [CombinatorialData] public void CanCreateDiagnosticForAnalyzerLoadFailure( AnalyzerLoadFailureEventArgs.FailureErrorCode errorCode, [CombinatorialValues(LanguageNames.CSharp, LanguageNames.VisualBasic, null)] string? languageName) { // One potential value is None, which isn't actually a valid enum value to test. if (errorCode == AnalyzerLoadFailureEventArgs.FailureErrorCode.None) { return; } var expectsTypeName = errorCode is AnalyzerLoadFailureEventArgs.FailureErrorCode.UnableToCreateAnalyzer or AnalyzerLoadFailureEventArgs.FailureErrorCode.ReferencesFramework; const string analyzerTypeName = "AnalyzerTypeName"; var eventArgs = new AnalyzerLoadFailureEventArgs( errorCode, message: errorCode.ToString(), typeNameOpt: expectsTypeName ? analyzerTypeName : null); // Ensure CreateAnalyzerLoadFailureDiagnostic doesn't fail when called. We don't assert much about the resulting // diagnostic -- this is primarly to ensure we don't forget to update it if a new error code is added. var diagnostic = AnalyzerHelper.CreateAnalyzerLoadFailureDiagnostic(eventArgs, "Analyzer.dll", null, languageName); Assert.Equal(languageName, diagnostic.Language); if (expectsTypeName) { Assert.Contains(analyzerTypeName, diagnostic.Message); } else { Assert.DoesNotContain(analyzerTypeName, diagnostic.Message); } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_InterpolatedString.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class LocalRewriter Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode Debug.Assert(node.Type.SpecialType = SpecialType.System_String) Dim factory = New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) ' We lower an interpolated string into an invocation of String.Format or System.Runtime.CompilerServices.FormattableStringFactory.Create. ' For example, we translate the expression: ' ' $"Jenny, don't change your number: {phoneNumber:###-####}." ' ' into ' ' String.Format("Jenny, don't change your number: {0:###-####}.", phoneNumber) ' ' TODO: A number of optimizations would be beneficial in the generated code. ' ' (1) If there is no width or format, and the argument is a value type, call .ToString() ' on it directly so that we avoid the boxing overhead. ' ' (2) For the built-in types, we can use .ToString(string format) for some format strings. ' Detect those cases that can be handled that way and take advantage of them. If node.IsEmpty Then Return factory.StringLiteral(ConstantValue.Create(String.Empty)) ElseIf Not node.HasInterpolations Then ' We have to process all of the escape sequences in the string. Dim valueWithEscapes = DirectCast(node.Contents(0), BoundLiteral).Value.StringValue Return factory.StringLiteral(ConstantValue.Create(valueWithEscapes.Replace("{{", "{").Replace("}}", "}"))) Else Return InvokeInterpolatedStringFactory(node, node.Type, "Format", node.Type, factory) End If End Function Private Function RewriteInterpolatedStringConversion(conversion As BoundConversion) As BoundExpression Debug.Assert((conversion.ConversionKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString) Dim targetType = conversion.Type Dim node = DirectCast(conversion.Operand, BoundInterpolatedStringExpression) Dim binder = node.Binder Debug.Assert(targetType.Equals(binder.Compilation.GetWellKnownType(WellKnownType.System_FormattableString)) OrElse targetType.Equals(binder.Compilation.GetWellKnownType(WellKnownType.System_IFormattable))) ' We lower an interpolated string into an invocation of System.Runtime.CompilerServices.FormattableStringFactory.Create. ' For example, we translate the expression: ' ' $"Jenny, don't change your number: {phoneNumber:###-####}." ' ' into ' ' FormattableStringFactory.Create("Jenny, don't change your number: {0:###-####}.", phoneNumber) ' ' TODO: A number of optimizations would be beneficial in the generated code. ' ' (1) If there is no width or format, and the argument is a value type, call .ToString() ' on it directly so that we avoid the boxing overhead. ' ' (2) For the built-in types, we can use .ToString(string format) for some format strings. ' Detect those cases that can be handled that way and take advantage of them. Return InvokeInterpolatedStringFactory(node, binder.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, conversion.Syntax, _diagnostics), "Create", conversion.Type, New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics)) End Function Private Function InvokeInterpolatedStringFactory(node As BoundInterpolatedStringExpression, factoryType As TypeSymbol, factoryMethodName As String, targetType As TypeSymbol, factory As SyntheticBoundNodeFactory) As BoundExpression Dim hasErrors As Boolean = False If factoryType.IsErrorType() Then GoTo ReturnBadExpression End If Dim binder = node.Binder Dim lookup = LookupResult.GetInstance() Dim useSiteInfo = GetNewCompoundUseSiteInfo() binder.LookupMember(lookup, factoryType, factoryMethodName, 0, LookupOptions.MustNotBeInstance Or LookupOptions.MethodsOnly Or LookupOptions.AllMethodsOfAnyArity, useSiteInfo) _diagnostics.Add(node, useSiteInfo) If lookup.Kind = LookupResultKind.Inaccessible Then hasErrors = True ElseIf Not lookup.IsGood Then lookup.Free() GoTo ReturnBadExpression End If Dim methodGroup = New BoundMethodGroup(node.Syntax, Nothing, lookup.Symbols.ToDowncastedImmutable(Of MethodSymbol), lookup.Kind, Nothing, QualificationKind.QualifiedViaTypeName).MakeCompilerGenerated() lookup.Free() Dim formatStringBuilderHandle = PooledStringBuilder.GetInstance() Dim arguments = ArrayBuilder(Of BoundExpression).GetInstance() Dim interpolationOrdinal = -1 arguments.Add(Nothing) ' Placeholder for format string. For Each item In node.Contents Select Case item.Kind Case BoundKind.Literal formatStringBuilderHandle.Builder.Append(DirectCast(item, BoundLiteral).Value.StringValue) Case BoundKind.Interpolation interpolationOrdinal += 1 Dim interpolation = DirectCast(item, BoundInterpolation) With formatStringBuilderHandle.Builder .Append("{"c) .Append(interpolationOrdinal.ToString(Globalization.CultureInfo.InvariantCulture)) If interpolation.AlignmentOpt IsNot Nothing Then Debug.Assert(interpolation.AlignmentOpt.IsConstant AndAlso interpolation.AlignmentOpt.ConstantValueOpt.IsIntegral) .Append(","c) .Append(interpolation.AlignmentOpt.ConstantValueOpt.Int64Value.ToString(Globalization.CultureInfo.InvariantCulture)) End If If interpolation.FormatStringOpt IsNot Nothing Then .Append(":") .Append(interpolation.FormatStringOpt.Value.StringValue) End If .Append("}"c) End With arguments.Add(interpolation.Expression) Case Else Throw ExceptionUtilities.Unreachable() End Select Next arguments(0) = factory.StringLiteral(ConstantValue.Create(formatStringBuilderHandle.ToStringAndFree())).MakeCompilerGenerated() Dim result As BoundExpression = binder.MakeRValue(binder.BindInvocationExpression(node.Syntax, node.Syntax, TypeCharacter.None, methodGroup, arguments.ToImmutableAndFree(), Nothing, _diagnostics, callerInfoOpt:=Nothing, forceExpandedForm:=True), _diagnostics).MakeCompilerGenerated() If Not result.Type.Equals(targetType) Then result = binder.ApplyImplicitConversion(node.Syntax, targetType, result, _diagnostics).MakeCompilerGenerated() End If If hasErrors OrElse result.HasErrors Then GoTo ReturnBadExpression End If result = VisitExpression(result) Return result ReturnBadExpression: ReportDiagnostic(node, ErrorFactory.ErrorInfo(ERRID.ERR_InterpolatedStringFactoryError, factoryType.Name, factoryMethodName), _diagnostics) Return factory.Convert(targetType, factory.BadExpression(DirectCast(MyBase.VisitInterpolatedStringExpression(node), BoundExpression))) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class LocalRewriter Public Overrides Function VisitInterpolatedStringExpression(node As BoundInterpolatedStringExpression) As BoundNode Debug.Assert(node.Type.SpecialType = SpecialType.System_String) Dim factory = New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics) ' We lower an interpolated string into an invocation of String.Format or System.Runtime.CompilerServices.FormattableStringFactory.Create. ' For example, we translate the expression: ' ' $"Jenny, don't change your number: {phoneNumber:###-####}." ' ' into ' ' String.Format("Jenny, don't change your number: {0:###-####}.", phoneNumber) ' ' TODO: A number of optimizations would be beneficial in the generated code. ' ' (1) If there is no width or format, and the argument is a value type, call .ToString() ' on it directly so that we avoid the boxing overhead. ' ' (2) For the built-in types, we can use .ToString(string format) for some format strings. ' Detect those cases that can be handled that way and take advantage of them. If node.IsEmpty Then Return factory.StringLiteral(ConstantValue.Create(String.Empty)) ElseIf Not node.HasInterpolations Then ' We have to process all of the escape sequences in the string. Dim valueWithEscapes = DirectCast(node.Contents(0), BoundLiteral).Value.StringValue Return factory.StringLiteral(ConstantValue.Create(valueWithEscapes.Replace("{{", "{").Replace("}}", "}"))) Else Return InvokeInterpolatedStringFactory(node, node.Type, "Format", node.Type, factory) End If End Function Private Function RewriteInterpolatedStringConversion(conversion As BoundConversion) As BoundExpression Debug.Assert((conversion.ConversionKind And ConversionKind.InterpolatedString) = ConversionKind.InterpolatedString) Dim targetType = conversion.Type Dim node = DirectCast(conversion.Operand, BoundInterpolatedStringExpression) Dim binder = node.Binder Debug.Assert(targetType.Equals(binder.Compilation.GetWellKnownType(WellKnownType.System_FormattableString)) OrElse targetType.Equals(binder.Compilation.GetWellKnownType(WellKnownType.System_IFormattable))) ' We lower an interpolated string into an invocation of System.Runtime.CompilerServices.FormattableStringFactory.Create. ' For example, we translate the expression: ' ' $"Jenny, don't change your number: {phoneNumber:###-####}." ' ' into ' ' FormattableStringFactory.Create("Jenny, don't change your number: {0:###-####}.", phoneNumber) ' ' TODO: A number of optimizations would be beneficial in the generated code. ' ' (1) If there is no width or format, and the argument is a value type, call .ToString() ' on it directly so that we avoid the boxing overhead. ' ' (2) For the built-in types, we can use .ToString(string format) for some format strings. ' Detect those cases that can be handled that way and take advantage of them. Return InvokeInterpolatedStringFactory(node, binder.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_FormattableStringFactory, conversion.Syntax, _diagnostics), "Create", conversion.Type, New SyntheticBoundNodeFactory(_topMethod, _currentMethodOrLambda, node.Syntax, _compilationState, _diagnostics)) End Function Private Function InvokeInterpolatedStringFactory(node As BoundInterpolatedStringExpression, factoryType As TypeSymbol, factoryMethodName As String, targetType As TypeSymbol, factory As SyntheticBoundNodeFactory) As BoundExpression Dim hasErrors As Boolean = False If factoryType.IsErrorType() Then GoTo ReturnBadExpression End If Dim binder = node.Binder Dim lookup = LookupResult.GetInstance() Dim useSiteInfo = GetNewCompoundUseSiteInfo() binder.LookupMember(lookup, factoryType, factoryMethodName, 0, LookupOptions.MustNotBeInstance Or LookupOptions.MethodsOnly Or LookupOptions.AllMethodsOfAnyArity, useSiteInfo) _diagnostics.Add(node, useSiteInfo) If lookup.Kind = LookupResultKind.Inaccessible Then hasErrors = True ElseIf Not lookup.IsGood Then lookup.Free() GoTo ReturnBadExpression End If Dim methodGroup = New BoundMethodGroup(node.Syntax, Nothing, lookup.Symbols.ToDowncastedImmutable(Of MethodSymbol), lookup.Kind, Nothing, QualificationKind.QualifiedViaTypeName).MakeCompilerGenerated() lookup.Free() Dim formatStringBuilderHandle = PooledStringBuilder.GetInstance() Dim arguments = ArrayBuilder(Of BoundExpression).GetInstance() Dim interpolationOrdinal = -1 arguments.Add(Nothing) ' Placeholder for format string. For Each item In node.Contents Select Case item.Kind Case BoundKind.Literal formatStringBuilderHandle.Builder.Append(DirectCast(item, BoundLiteral).Value.StringValue) Case BoundKind.Interpolation interpolationOrdinal += 1 Dim interpolation = DirectCast(item, BoundInterpolation) With formatStringBuilderHandle.Builder .Append("{"c) .Append(interpolationOrdinal.ToString(Globalization.CultureInfo.InvariantCulture)) If interpolation.AlignmentOpt IsNot Nothing Then Debug.Assert(interpolation.AlignmentOpt.IsConstant AndAlso interpolation.AlignmentOpt.ConstantValueOpt.IsIntegral) .Append(","c) .Append(interpolation.AlignmentOpt.ConstantValueOpt.Int64Value.ToString(Globalization.CultureInfo.InvariantCulture)) End If If interpolation.FormatStringOpt IsNot Nothing Then .Append(":") .Append(interpolation.FormatStringOpt.Value.StringValue) End If .Append("}"c) End With arguments.Add(interpolation.Expression) Case Else Throw ExceptionUtilities.Unreachable() End Select Next arguments(0) = factory.StringLiteral(ConstantValue.Create(formatStringBuilderHandle.ToStringAndFree())).MakeCompilerGenerated() Dim result As BoundExpression = binder.MakeRValue(binder.BindInvocationExpression(node.Syntax, node.Syntax, TypeCharacter.None, methodGroup, arguments.ToImmutableAndFree(), Nothing, _diagnostics, callerInfoOpt:=Nothing, forceExpandedForm:=True), _diagnostics).MakeCompilerGenerated() If Not result.Type.Equals(targetType) Then result = binder.ApplyImplicitConversion(node.Syntax, targetType, result, _diagnostics).MakeCompilerGenerated() End If If hasErrors OrElse result.HasErrors Then GoTo ReturnBadExpression End If result = VisitExpression(result) Return result ReturnBadExpression: ReportDiagnostic(node, ErrorFactory.ErrorInfo(ERRID.ERR_InterpolatedStringFactoryError, factoryType.Name, factoryMethodName), _diagnostics) Return factory.Convert(targetType, factory.BadExpression(DirectCast(MyBase.VisitInterpolatedStringExpression(node), BoundExpression))) End Function End Class End Namespace
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/ReassignedVariable/CSharpReassignedVariableService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ReassignedVariable; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ReassignedVariable { [ExportLanguageService(typeof(IReassignedVariableService), LanguageNames.CSharp), Shared] internal class CSharpReassignedVariableService : AbstractReassignedVariableService< ParameterSyntax, VariableDeclaratorSyntax, SingleVariableDesignationSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpReassignedVariableService() { } protected override SyntaxToken GetIdentifierOfVariable(VariableDeclaratorSyntax variable) => variable.Identifier; protected override SyntaxToken GetIdentifierOfSingleVariableDesignation(SingleVariableDesignationSyntax variable) => variable.Identifier; protected override bool HasInitializer(SyntaxNode variable) => (variable as VariableDeclaratorSyntax)?.Initializer != null; protected override SyntaxNode GetMemberBlock(SyntaxNode methodOrPropertyDeclaration) => methodOrPropertyDeclaration; protected override SyntaxNode GetParentScope(SyntaxNode localDeclaration) { var current = localDeclaration; while (current != null) { if (current is BlockSyntax or SwitchSectionSyntax or ArrowExpressionClauseSyntax or AnonymousMethodExpressionSyntax or MemberDeclarationSyntax) break; current = current.Parent; } Contract.ThrowIfNull(current, "Couldn't find a suitable parent of this local declaration"); return current is GlobalStatementSyntax ? current.GetRequiredParent() : current; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.ReassignedVariable; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ReassignedVariable { [ExportLanguageService(typeof(IReassignedVariableService), LanguageNames.CSharp), Shared] internal class CSharpReassignedVariableService : AbstractReassignedVariableService< ParameterSyntax, VariableDeclaratorSyntax, SingleVariableDesignationSyntax, IdentifierNameSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpReassignedVariableService() { } protected override SyntaxToken GetIdentifierOfVariable(VariableDeclaratorSyntax variable) => variable.Identifier; protected override SyntaxToken GetIdentifierOfSingleVariableDesignation(SingleVariableDesignationSyntax variable) => variable.Identifier; protected override bool HasInitializer(SyntaxNode variable) => (variable as VariableDeclaratorSyntax)?.Initializer != null; protected override SyntaxNode GetMemberBlock(SyntaxNode methodOrPropertyDeclaration) => methodOrPropertyDeclaration; protected override SyntaxNode GetParentScope(SyntaxNode localDeclaration) { var current = localDeclaration; while (current != null) { if (current is BlockSyntax or SwitchSectionSyntax or ArrowExpressionClauseSyntax or AnonymousMethodExpressionSyntax or MemberDeclarationSyntax) break; current = current.Parent; } Contract.ThrowIfNull(current, "Couldn't find a suitable parent of this local declaration"); return current is GlobalStatementSyntax ? current.GetRequiredParent() : current; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./.git/refs/remotes/origin/HEAD
ref: refs/remotes/origin/main
ref: refs/remotes/origin/main
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Wrapped/WrappedFieldSymbol.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 System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field that is based on another field. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedFieldSymbol : FieldSymbol { /// <summary> /// The underlying FieldSymbol. /// </summary> protected readonly FieldSymbol _underlyingField; public WrappedFieldSymbol(FieldSymbol underlyingField) { Debug.Assert((object)underlyingField != null); _underlyingField = underlyingField; } public FieldSymbol UnderlyingField { get { return _underlyingField; } } public override bool IsImplicitlyDeclared { get { return _underlyingField.IsImplicitlyDeclared; } } public override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return _underlyingField.FlowAnalysisAnnotations; } } public override Accessibility DeclaredAccessibility { get { return _underlyingField.DeclaredAccessibility; } } public override string Name { get { return _underlyingField.Name; } } internal override bool HasSpecialName { get { return _underlyingField.HasSpecialName; } } internal override bool HasRuntimeSpecialName { get { return _underlyingField.HasRuntimeSpecialName; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingField.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } internal override bool IsNotSerialized { get { return _underlyingField.IsNotSerialized; } } internal override bool HasPointerType => _underlyingField.HasPointerType; internal override bool IsMarshalledExplicitly { get { return _underlyingField.IsMarshalledExplicitly; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return _underlyingField.MarshallingInformation; } } internal override ImmutableArray<byte> MarshallingDescriptor { get { return _underlyingField.MarshallingDescriptor; } } public override bool IsFixedSizeBuffer { get { return _underlyingField.IsFixedSizeBuffer; } } internal override int? TypeLayoutOffset { get { return _underlyingField.TypeLayoutOffset; } } public override bool IsReadOnly { get { return _underlyingField.IsReadOnly; } } public override bool IsVolatile { get { return _underlyingField.IsVolatile; } } public override bool IsConst { get { return _underlyingField.IsConst; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { return _underlyingField.ObsoleteAttributeData; } } public override object ConstantValue { get { return _underlyingField.ConstantValue; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { return _underlyingField.GetConstantValue(inProgress, earlyDecodingWellKnownAttributes); } public override ImmutableArray<Location> Locations { get { return _underlyingField.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingField.DeclaringSyntaxReferences; } } public override bool IsStatic { get { return _underlyingField.IsStatic; } } } }
// Licensed to the .NET Foundation under one or more 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 System.Globalization; using System.Threading; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a field that is based on another field. /// When inheriting from this class, one shouldn't assume that /// the default behavior it has is appropriate for every case. /// That behavior should be carefully reviewed and derived type /// should override behavior as appropriate. /// </summary> internal abstract class WrappedFieldSymbol : FieldSymbol { /// <summary> /// The underlying FieldSymbol. /// </summary> protected readonly FieldSymbol _underlyingField; public WrappedFieldSymbol(FieldSymbol underlyingField) { Debug.Assert((object)underlyingField != null); _underlyingField = underlyingField; } public FieldSymbol UnderlyingField { get { return _underlyingField; } } public override bool IsImplicitlyDeclared { get { return _underlyingField.IsImplicitlyDeclared; } } public override FlowAnalysisAnnotations FlowAnalysisAnnotations { get { return _underlyingField.FlowAnalysisAnnotations; } } public override Accessibility DeclaredAccessibility { get { return _underlyingField.DeclaredAccessibility; } } public override string Name { get { return _underlyingField.Name; } } internal override bool HasSpecialName { get { return _underlyingField.HasSpecialName; } } internal override bool HasRuntimeSpecialName { get { return _underlyingField.HasRuntimeSpecialName; } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return _underlyingField.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken); } internal override bool IsNotSerialized { get { return _underlyingField.IsNotSerialized; } } internal override bool HasPointerType => _underlyingField.HasPointerType; internal override bool IsMarshalledExplicitly { get { return _underlyingField.IsMarshalledExplicitly; } } internal override MarshalPseudoCustomAttributeData MarshallingInformation { get { return _underlyingField.MarshallingInformation; } } internal override ImmutableArray<byte> MarshallingDescriptor { get { return _underlyingField.MarshallingDescriptor; } } public override bool IsFixedSizeBuffer { get { return _underlyingField.IsFixedSizeBuffer; } } internal override int? TypeLayoutOffset { get { return _underlyingField.TypeLayoutOffset; } } public override bool IsReadOnly { get { return _underlyingField.IsReadOnly; } } public override bool IsVolatile { get { return _underlyingField.IsVolatile; } } public override bool IsConst { get { return _underlyingField.IsConst; } } internal override ObsoleteAttributeData ObsoleteAttributeData { get { return _underlyingField.ObsoleteAttributeData; } } public override object ConstantValue { get { return _underlyingField.ConstantValue; } } internal override ConstantValue GetConstantValue(ConstantFieldsInProgress inProgress, bool earlyDecodingWellKnownAttributes) { return _underlyingField.GetConstantValue(inProgress, earlyDecodingWellKnownAttributes); } public override ImmutableArray<Location> Locations { get { return _underlyingField.Locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return _underlyingField.DeclaringSyntaxReferences; } } public override bool IsStatic { get { return _underlyingField.IsStatic; } } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Utilities/SyntaxKindSet.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Formatting; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal class SyntaxKindSet { public static readonly ISet<SyntaxKind> AllTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AbstractKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.RefKeyword }; public static readonly ISet<SyntaxKind> AllMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AbstractKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.VolatileKeyword, }; public static readonly ISet<SyntaxKind> AllGlobalMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; public static readonly ISet<SyntaxKind> AllLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AsyncKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.ExternKeyword, SyntaxKind.StaticKeyword }; public static readonly ISet<SyntaxKind> AllTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, SyntaxKind.EnumDeclaration, }; public static readonly ISet<SyntaxKind> ClassInterfaceStructRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, }; public static readonly ISet<SyntaxKind> ClassInterfaceRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, }; public static readonly ISet<SyntaxKind> ClassRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, }; public static readonly ISet<SyntaxKind> ClassStructRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, }; public static readonly ISet<SyntaxKind> StructOnlyTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, }; public static readonly ISet<SyntaxKind> InterfaceOnlyTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Formatting; namespace Microsoft.CodeAnalysis.CSharp.Utilities { internal class SyntaxKindSet { public static readonly ISet<SyntaxKind> AllTypeModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AbstractKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.RefKeyword }; public static readonly ISet<SyntaxKind> AllMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AbstractKeyword, SyntaxKind.AsyncKeyword, SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.SealedKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.VolatileKeyword, }; public static readonly ISet<SyntaxKind> AllGlobalMemberModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ExternKeyword, SyntaxKind.InternalKeyword, SyntaxKind.NewKeyword, SyntaxKind.OverrideKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ReadOnlyKeyword, SyntaxKind.StaticKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.VolatileKeyword, }; public static readonly ISet<SyntaxKind> AllLocalFunctionModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.AsyncKeyword, SyntaxKind.UnsafeKeyword, SyntaxKind.ExternKeyword, SyntaxKind.StaticKeyword }; public static readonly ISet<SyntaxKind> AllTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, SyntaxKind.EnumDeclaration, }; public static readonly ISet<SyntaxKind> ClassInterfaceStructRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, }; public static readonly ISet<SyntaxKind> ClassInterfaceRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, }; public static readonly ISet<SyntaxKind> ClassRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, }; public static readonly ISet<SyntaxKind> ClassStructRecordTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.ClassDeclaration, SyntaxKind.RecordDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, }; public static readonly ISet<SyntaxKind> StructOnlyTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.StructDeclaration, SyntaxKind.RecordStructDeclaration, }; public static readonly ISet<SyntaxKind> InterfaceOnlyTypeDeclarations = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InterfaceDeclaration, }; } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Tags/IImageIdService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Core.Imaging; namespace Microsoft.CodeAnalysis.Editor.Tags { /// <summary> /// Extensibility point for hosts to display <see cref="ImageId"/>s for items with Tags. /// </summary> internal interface IImageIdService { bool TryGetImageId(ImmutableArray<string> tags, out ImageId imageId); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.VisualStudio.Core.Imaging; namespace Microsoft.CodeAnalysis.Editor.Tags { /// <summary> /// Extensibility point for hosts to display <see cref="ImageId"/>s for items with Tags. /// </summary> internal interface IImageIdService { bool TryGetImageId(ImmutableArray<string> tags, out ImageId imageId); } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Implementation/InlineRename/CommandHandlers/AbstractRenameCommandHandler_ReturnHandler.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.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractRenameCommandHandler : ICommandHandler<ReturnKeyCommandArgs> { public CommandState GetCommandState(ReturnKeyCommandArgs args) => GetCommandState(); public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context) { if (_renameService.ActiveSession != null) { _renameService.ActiveSession.Commit(); SetFocusToTextView(args.TextView); return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractRenameCommandHandler : ICommandHandler<ReturnKeyCommandArgs> { public CommandState GetCommandState(ReturnKeyCommandArgs args) => GetCommandState(); public bool ExecuteCommand(ReturnKeyCommandArgs args, CommandExecutionContext context) { if (_renameService.ActiveSession != null) { _renameService.ActiveSession.Commit(); SetFocusToTextView(args.TextView); return true; } return false; } } }
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/NuGet/Microsoft.NETCore.Compilers/.gitattributes
# RunCsc/RunVbc are shell scripts and should always have unix line endings # These shell scripts are included in the toolset packages. Normally, the shell # scripts in our repo are only run by cloning onto a Linux/Mac machine, and git # automatically chooses LF as the line ending. # # However, right now the toolset packages must be built on Windows, and so the # files must be hard-coded to be cloned with LF tools/bincore/RunCsc text eol=lf tools/bincore/RunVbc text eol=lf
# RunCsc/RunVbc are shell scripts and should always have unix line endings # These shell scripts are included in the toolset packages. Normally, the shell # scripts in our repo are only run by cloning onto a Linux/Mac machine, and git # automatically chooses LF as the line ending. # # However, right now the toolset packages must be built on Windows, and so the # files must be hard-coded to be cloned with LF tools/bincore/RunCsc text eol=lf tools/bincore/RunVbc text eol=lf
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./eng/common/templates/steps/send-to-helix.yml
# Please remember to update the documentation if you make changes to these parameters! parameters: HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixConfiguration: '' # optional -- additional property attached to a job HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects WorkItemTimeout: '' # optional -- a timeout in TimeSpan.Parse-ready value (e.g. 00:02:00) for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload XUnitProjects: '' # optional -- semicolon delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting int) Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false steps: - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' displayName: ${{ parameters.DisplayNamePrefix }} (Windows) env: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixConfiguration: ${{ parameters.HelixConfiguration }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} WorkItemCommand: ${{ parameters.WorkItemCommand }} WorkItemTimeout: ${{ parameters.WorkItemTimeout }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} XUnitProjects: ${{ parameters.XUnitProjects }} XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} HelixBaseUri: ${{ parameters.HelixBaseUri }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} (Unix) env: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixConfiguration: ${{ parameters.HelixConfiguration }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} WorkItemCommand: ${{ parameters.WorkItemCommand }} WorkItemTimeout: ${{ parameters.WorkItemTimeout }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} XUnitProjects: ${{ parameters.XUnitProjects }} XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} HelixBaseUri: ${{ parameters.HelixBaseUri }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }}
# Please remember to update the documentation if you make changes to these parameters! parameters: HelixSource: 'pr/default' # required -- sources must start with pr/, official/, prodcon/, or agent/ HelixType: 'tests/default/' # required -- Helix telemetry which identifies what type of data this is; should include "test" for clarity and must end in '/' HelixBuild: $(Build.BuildNumber) # required -- the build number Helix will use to identify this -- automatically set to the AzDO build number HelixTargetQueues: '' # required -- semicolon delimited list of Helix queues to test on; see https://helix.dot.net/ for a list of queues HelixAccessToken: '' # required -- access token to make Helix API requests; should be provided by the appropriate variable group HelixConfiguration: '' # optional -- additional property attached to a job HelixPreCommands: '' # optional -- commands to run before Helix work item execution HelixPostCommands: '' # optional -- commands to run after Helix work item execution WorkItemDirectory: '' # optional -- a payload directory to zip up and send to Helix; requires WorkItemCommand; incompatible with XUnitProjects WorkItemCommand: '' # optional -- a command to execute on the payload; requires WorkItemDirectory; incompatible with XUnitProjects WorkItemTimeout: '' # optional -- a timeout in TimeSpan.Parse-ready value (e.g. 00:02:00) for the work item command; requires WorkItemDirectory; incompatible with XUnitProjects CorrelationPayloadDirectory: '' # optional -- a directory to zip up and send to Helix as a correlation payload XUnitProjects: '' # optional -- semicolon delimited list of XUnitProjects to parse and send to Helix; requires XUnitRuntimeTargetFramework, XUnitPublishTargetFramework, XUnitRunnerVersion, and IncludeDotNetCli=true XUnitWorkItemTimeout: '' # optional -- the workitem timeout in seconds for all workitems created from the xUnit projects specified by XUnitProjects XUnitPublishTargetFramework: '' # optional -- framework to use to publish your xUnit projects XUnitRuntimeTargetFramework: '' # optional -- framework to use for the xUnit console runner XUnitRunnerVersion: '' # optional -- version of the xUnit nuget package you wish to use on Helix; required for XUnitProjects IncludeDotNetCli: false # optional -- true will download a version of the .NET CLI onto the Helix machine as a correlation payload; requires DotNetCliPackageType and DotNetCliVersion DotNetCliPackageType: '' # optional -- either 'sdk', 'runtime' or 'aspnetcore-runtime'; determines whether the sdk or runtime will be sent to Helix; see https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json DotNetCliVersion: '' # optional -- version of the CLI to send to Helix; based on this: https://raw.githubusercontent.com/dotnet/core/main/release-notes/releases-index.json EnableXUnitReporter: false # optional -- true enables XUnit result reporting to Mission Control WaitForWorkItemCompletion: true # optional -- true will make the task wait until work items have been completed and fail the build if work items fail. False is "fire and forget." IsExternal: false # [DEPRECATED] -- doesn't do anything, jobs are external if HelixAccessToken is empty and Creator is set HelixBaseUri: 'https://helix.dot.net/' # optional -- sets the Helix API base URI (allows targeting int) Creator: '' # optional -- if the build is external, use this to specify who is sending the job DisplayNamePrefix: 'Run Tests' # optional -- rename the beginning of the displayName of the steps in AzDO condition: succeeded() # optional -- condition for step to execute; defaults to succeeded() continueOnError: false # optional -- determines whether to continue the build if the step errors; defaults to false steps: - powershell: 'powershell "$env:BUILD_SOURCESDIRECTORY\eng\common\msbuild.ps1 $env:BUILD_SOURCESDIRECTORY\eng\common\helixpublish.proj /restore /t:Test /bl:$env:BUILD_SOURCESDIRECTORY\artifacts\log\$env:BuildConfig\SendToHelix.binlog"' displayName: ${{ parameters.DisplayNamePrefix }} (Windows) env: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixConfiguration: ${{ parameters.HelixConfiguration }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} WorkItemCommand: ${{ parameters.WorkItemCommand }} WorkItemTimeout: ${{ parameters.WorkItemTimeout }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} XUnitProjects: ${{ parameters.XUnitProjects }} XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} HelixBaseUri: ${{ parameters.HelixBaseUri }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, eq(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }} - script: $BUILD_SOURCESDIRECTORY/eng/common/msbuild.sh $BUILD_SOURCESDIRECTORY/eng/common/helixpublish.proj /restore /t:Test /bl:$BUILD_SOURCESDIRECTORY/artifacts/log/$BuildConfig/SendToHelix.binlog displayName: ${{ parameters.DisplayNamePrefix }} (Unix) env: BuildConfig: $(_BuildConfig) HelixSource: ${{ parameters.HelixSource }} HelixType: ${{ parameters.HelixType }} HelixBuild: ${{ parameters.HelixBuild }} HelixConfiguration: ${{ parameters.HelixConfiguration }} HelixTargetQueues: ${{ parameters.HelixTargetQueues }} HelixAccessToken: ${{ parameters.HelixAccessToken }} HelixPreCommands: ${{ parameters.HelixPreCommands }} HelixPostCommands: ${{ parameters.HelixPostCommands }} WorkItemDirectory: ${{ parameters.WorkItemDirectory }} WorkItemCommand: ${{ parameters.WorkItemCommand }} WorkItemTimeout: ${{ parameters.WorkItemTimeout }} CorrelationPayloadDirectory: ${{ parameters.CorrelationPayloadDirectory }} XUnitProjects: ${{ parameters.XUnitProjects }} XUnitWorkItemTimeout: ${{ parameters.XUnitWorkItemTimeout }} XUnitPublishTargetFramework: ${{ parameters.XUnitPublishTargetFramework }} XUnitRuntimeTargetFramework: ${{ parameters.XUnitRuntimeTargetFramework }} XUnitRunnerVersion: ${{ parameters.XUnitRunnerVersion }} IncludeDotNetCli: ${{ parameters.IncludeDotNetCli }} DotNetCliPackageType: ${{ parameters.DotNetCliPackageType }} DotNetCliVersion: ${{ parameters.DotNetCliVersion }} EnableXUnitReporter: ${{ parameters.EnableXUnitReporter }} WaitForWorkItemCompletion: ${{ parameters.WaitForWorkItemCompletion }} HelixBaseUri: ${{ parameters.HelixBaseUri }} Creator: ${{ parameters.Creator }} SYSTEM_ACCESSTOKEN: $(System.AccessToken) condition: and(${{ parameters.condition }}, ne(variables['Agent.Os'], 'Windows_NT')) continueOnError: ${{ parameters.continueOnError }}
-1
dotnet/roslyn
54,989
Fix 'add extern alias' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T20:17:20Z
2021-07-20T23:56:59Z
56ff80826007fb803fd46e7d6e7c319c738f55f0
6c7e5b2437b149e8d8ca42aa5e79e721060b3dae
Fix 'add extern alias' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Emit/NoPia/CommonEmbeddedParameter.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.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition { public readonly CommonEmbeddedMember ContainingPropertyOrMethod; public readonly TParameterSymbol UnderlyingParameter; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) { this.ContainingPropertyOrMethod = containingPropertyOrMethod; this.UnderlyingParameter = underlyingParameter; } protected TEmbeddedTypesManager TypeManager { get { return ContainingPropertyOrMethod.TypeManager; } } protected abstract bool HasDefaultValue { get; } protected abstract MetadataConstant GetDefaultValue(EmitContext context); protected abstract bool IsIn { get; } protected abstract bool IsOut { get; } protected abstract bool IsOptional { get; } protected abstract bool IsMarshalledExplicitly { get; } protected abstract Cci.IMarshallingInformation MarshallingInformation { get; } protected abstract ImmutableArray<byte> MarshallingDescriptor { get; } protected abstract string Name { get; } protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; } protected abstract ushort Index { get; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) { return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description); } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute)) { if (attrData.CommonConstructorArguments.Length == 0) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (attrData.CommonConstructorArguments.Length == 5) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute( signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } } } return builder.ToImmutableAndFree(); } bool Cci.IParameterDefinition.HasDefaultValue { get { return HasDefaultValue; } } MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context) { return GetDefaultValue(context); } bool Cci.IParameterDefinition.IsIn { get { return IsIn; } } bool Cci.IParameterDefinition.IsOut { get { return IsOut; } } bool Cci.IParameterDefinition.IsOptional { get { return IsOptional; } } bool Cci.IParameterDefinition.IsMarshalledExplicitly { get { return IsMarshalledExplicitly; } } Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation { get { return MarshallingInformation; } } ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor { get { return MarshallingDescriptor; } } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return Name; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return UnderlyingParameterTypeInformation.CustomModifiers; } } bool Cci.IParameterTypeInformation.IsByReference { get { return UnderlyingParameterTypeInformation.IsByReference; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return UnderlyingParameterTypeInformation.RefCustomModifiers; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return UnderlyingParameterTypeInformation.GetType(context); } ushort Cci.IParameterListEntry.Index { get { return Index; } } /// <remarks> /// This is only used for testing. /// </remarks> public override string ToString() { return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit.NoPia { internal abstract partial class EmbeddedTypesManager< TPEModuleBuilder, TModuleCompilationState, TEmbeddedTypesManager, TSyntaxNode, TAttributeData, TSymbol, TAssemblySymbol, TNamedTypeSymbol, TFieldSymbol, TMethodSymbol, TEventSymbol, TPropertySymbol, TParameterSymbol, TTypeParameterSymbol, TEmbeddedType, TEmbeddedField, TEmbeddedMethod, TEmbeddedEvent, TEmbeddedProperty, TEmbeddedParameter, TEmbeddedTypeParameter> { internal abstract class CommonEmbeddedParameter : Cci.IParameterDefinition { public readonly CommonEmbeddedMember ContainingPropertyOrMethod; public readonly TParameterSymbol UnderlyingParameter; private ImmutableArray<TAttributeData> _lazyAttributes; protected CommonEmbeddedParameter(CommonEmbeddedMember containingPropertyOrMethod, TParameterSymbol underlyingParameter) { this.ContainingPropertyOrMethod = containingPropertyOrMethod; this.UnderlyingParameter = underlyingParameter; } protected TEmbeddedTypesManager TypeManager { get { return ContainingPropertyOrMethod.TypeManager; } } protected abstract bool HasDefaultValue { get; } protected abstract MetadataConstant GetDefaultValue(EmitContext context); protected abstract bool IsIn { get; } protected abstract bool IsOut { get; } protected abstract bool IsOptional { get; } protected abstract bool IsMarshalledExplicitly { get; } protected abstract Cci.IMarshallingInformation MarshallingInformation { get; } protected abstract ImmutableArray<byte> MarshallingDescriptor { get; } protected abstract string Name { get; } protected abstract Cci.IParameterTypeInformation UnderlyingParameterTypeInformation { get; } protected abstract ushort Index { get; } protected abstract IEnumerable<TAttributeData> GetCustomAttributesToEmit(TPEModuleBuilder moduleBuilder); private bool IsTargetAttribute(TAttributeData attrData, AttributeDescription description) { return TypeManager.IsTargetAttribute(UnderlyingParameter, attrData, description); } private ImmutableArray<TAttributeData> GetAttributes(TPEModuleBuilder moduleBuilder, TSyntaxNode syntaxNodeOpt, DiagnosticBag diagnostics) { var builder = ArrayBuilder<TAttributeData>.GetInstance(); // Copy some of the attributes. // Note, when porting attributes, we are not using constructors from original symbol. // The constructors might be missing (for example, in metadata case) and doing lookup // will ensure that we report appropriate errors. foreach (var attrData in GetCustomAttributesToEmit(moduleBuilder)) { if (IsTargetAttribute(attrData, AttributeDescription.ParamArrayAttribute)) { if (attrData.CommonConstructorArguments.Length == 0) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DateTimeConstantAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } else { int signatureIndex = TypeManager.GetTargetAttributeSignatureIndex(UnderlyingParameter, attrData, AttributeDescription.DecimalConstantAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (attrData.CommonConstructorArguments.Length == 5) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute( signatureIndex == 0 ? WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor : WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctorByteByteInt32Int32Int32, attrData, syntaxNodeOpt, diagnostics)); } } else if (IsTargetAttribute(attrData, AttributeDescription.DefaultParameterValueAttribute)) { if (attrData.CommonConstructorArguments.Length == 1) { builder.AddOptional(TypeManager.CreateSynthesizedAttribute(WellKnownMember.System_Runtime_InteropServices_DefaultParameterValueAttribute__ctor, attrData, syntaxNodeOpt, diagnostics)); } } } } return builder.ToImmutableAndFree(); } bool Cci.IParameterDefinition.HasDefaultValue { get { return HasDefaultValue; } } MetadataConstant Cci.IParameterDefinition.GetDefaultValue(EmitContext context) { return GetDefaultValue(context); } bool Cci.IParameterDefinition.IsIn { get { return IsIn; } } bool Cci.IParameterDefinition.IsOut { get { return IsOut; } } bool Cci.IParameterDefinition.IsOptional { get { return IsOptional; } } bool Cci.IParameterDefinition.IsMarshalledExplicitly { get { return IsMarshalledExplicitly; } } Cci.IMarshallingInformation Cci.IParameterDefinition.MarshallingInformation { get { return MarshallingInformation; } } ImmutableArray<byte> Cci.IParameterDefinition.MarshallingDescriptor { get { return MarshallingDescriptor; } } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { if (_lazyAttributes.IsDefault) { var diagnostics = DiagnosticBag.GetInstance(); var attributes = GetAttributes((TPEModuleBuilder)context.Module, (TSyntaxNode)context.SyntaxNode, diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyAttributes, attributes)) { // Save any diagnostics that we encountered. context.Diagnostics.AddRange(diagnostics); } diagnostics.Free(); } return _lazyAttributes; } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { throw ExceptionUtilities.Unreachable; } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return this; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return Name; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.CustomModifiers { get { return UnderlyingParameterTypeInformation.CustomModifiers; } } bool Cci.IParameterTypeInformation.IsByReference { get { return UnderlyingParameterTypeInformation.IsByReference; } } ImmutableArray<Cci.ICustomModifier> Cci.IParameterTypeInformation.RefCustomModifiers { get { return UnderlyingParameterTypeInformation.RefCustomModifiers; } } Cci.ITypeReference Cci.IParameterTypeInformation.GetType(EmitContext context) { return UnderlyingParameterTypeInformation.GetType(context); } ushort Cci.IParameterListEntry.Index { get { return Index; } } /// <remarks> /// This is only used for testing. /// </remarks> public override string ToString() { return ((ISymbol)UnderlyingParameter).ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat); } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./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.Experiments; 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); protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestExperimentationService)); [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(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.Anonymous_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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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 SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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.Experiments; 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); protected override TestComposition GetComposition() => base.GetComposition().AddParts(typeof(TestExperimentationService)); [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(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.Anonymous_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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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() { SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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 SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, 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
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename Partial Public Class RenameEngineTests <[UseExportProvider]> Public Class CSharpConflicts Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <WorkItem(773543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773543")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithRollBacksInsideLambdas_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C { class D { public int x = 1; } Action&lt;int> a = (int [|$$x|]) => // Rename x to y { var {|Conflict:y|} = new D(); Console.{|Conflict:WriteLine|}({|Conflict:x|}); }; } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(773534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773534")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithRollBacksInsideLambdas_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; struct y { public int x; } class C { class D { public int x = 1; } Action&lt;y> a = (y [|$$x|]) => // Rename x to y { var {|Conflict:y|} = new D(); Console.WriteLine(y.x); Console.WriteLine({|Conflict:x|}.{|Conflict:x|}); }; } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(773435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773435")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithInvocationOnDelegateInstance(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public delegate void Foo(int x); public void FooMeth(int x) { } public void Sub() { Foo {|Conflict:x|} = new Foo(FooMeth); int [|$$z|] = 1; // Rename z to x int y = {|Conflict:z|}; x({|Conflict:z|}); // Renamed to x(x) } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(782020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782020")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithSameClassInOneNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using K = N.{|Conflict:C|}; // No change, show compiler error namespace N { class {|Conflict:C|} { } } namespace N { class {|Conflict:$$D|} // Rename D to C { } } </Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameCrossAssembly(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class D Public Sub Boo() Dim x = New {|Conflict:$$C|}() End Sub End Class </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1"> <Document> public class [|C|] { public static void Foo() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="D") result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideLambdaBody(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Proaasgram { object z; public void masdain(string[] args) { Func&lt;int, bool> sx = (int [|$$x|]) => { {|resolve:z|} = null; if (true) { bool y = foo([|x|]); } return true; }; } public bool foo(int bar) { return true; } public bool foo(object bar) { return true; } } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideExpressionBodiedLambda(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; public class B { public readonly int z = 0; public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|}; } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideExpressionBodiedLambda2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; public class B { public static readonly int z = 0; public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|}; } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideMethodBody(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; public class B { public readonly int z = 0; public int Y(int [|$$y|]) { [|y|] = 0; return {|resolve:z|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}(y => {|resolve2:Inner|}(x => { var z = 5; z.{|resolve0:Ex|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="L") Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.L();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => { var z = 5; z.{|resolve0:Ex|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="L") Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.L();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => { var z = 5; z.{|resolve0:D|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$D|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Ex") Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.Ex();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_4(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}(y => {|resolve2:Inner|}(x => { var z = 5; z.{|resolve0:D|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$D|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Ex") Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.Ex();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_5(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}(y => {|resolve2:Inner|}(x => { var z = 5; z.{|resolve0:D|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$D|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Ex") Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code> z.Ex();</code>.Value + vbCrLf + <code> x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithInstanceField1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { int foo; void Blah(int [|$$bar|]) { {|stmt2:foo|} = {|stmt1:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithInstanceField2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { int foo; void Blah(int [|$$bar|]) { {|resolved:foo|} = 23; {|resolved2:foo|} = {|stmt1:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { int @if; void Blah(int {|Escape1:$$bar|}) { {|Resolve:@if|} = 23; {|Resolve2:@if|} = {|Escape2:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="if") result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithStaticField(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { static int foo; void Blah(int [|$$bar|]) { {|Resolved:foo|} = 23; {|Resolved2:foo|} = {|stmt1:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithFieldFromAnotherLanguage(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <ProjectReference>VisualBasicAssembly</ProjectReference> <Document> class Foo : FooBase { void Blah(int bar) { {|Resolve:$$foo|} = bar; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document> Public Class FooBase Protected [|foo|] As Integer End Class </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <WorkItem(539745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539745")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingTypeDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="6"> <Document><![CDATA[ namespace N1 { using static C<int>; class Program { public void Goo(int i) { {|ReplacementCInt:Foo|}(i, i); } } } namespace N2 { using static C<string>; class Program { public void Goo(string s) { {|ReplacementCString:Foo|}(s, s); } } } static class C<T> { public static void [|$$Foo|](T i, T j) { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToInvalidIdentifier(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Invalid:$$Foo|} { {|Invalid:Foo|} foo; } </Document> </Project> </Workspace>, host:=host, renameTo:="`") result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict) result.AssertReplacementTextInvalid() End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToInvalidIdentifier2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Invalid:$$Foo|} { {|Invalid:Foo|} foo; } </Document> </Project> </Workspace>, host:=host, renameTo:="!") result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict) result.AssertReplacementTextInvalid() End Using End Sub <Theory> <WorkItem(539636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539636")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToConflictingMethodInvocation(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void F() { } class Blah { void [|$$M|]() { {|Replacement:F|}(); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToConflictingMethodInvocation2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void M() { int foo; {|Replacement:Bar|}(); } void [|$$Bar|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingTypeToConflictingMemberAndParentTypeName(host As RenameTestHost) ' It's important that we see conflicts for both simultaneously, so I do a single ' test for both cases. Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Conflict:Foo|} { class [|$$Bar|] { int {|Conflict:Foo|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingMemberToNameConflictingWithParent(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Conflict:Foo|} { int [|$$Bar|]; } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(540199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540199")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingMemberToInvalidIdentifierName(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Invalid:$$Foo|} { } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo@") result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MinimalQualificationOfBaseType1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class X { protected class [|$$A|] { } } class Y : X { private class C : {|Resolve:A|} { } private class B { } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MinimalQualificationOfBaseType2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class X { protected class A { } } class Y : X { private class C : {|Resolve:A|} { } private class [|$$B|] { } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeIfKeywordWhenDoingTypeNameQualification(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class Foo { static void {|Escape:Method$$|}() { } static void Test() { int @if; {|Replacement:Method|}(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="if") result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeUnboundGenericTypesInTypeOfContext(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>; class A<T> { public class B<S> { } } class Program { static void Main() { var type = typeof({|stmt1:C|}.B<>); } class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeUnboundGenericTypesInTypeOfContext2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>; class A<T> { public class B<S> { public class E { } } } class Program { static void Main() { var type = typeof({|Replacement:C|}.B<>.E); } class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeUnboundGenericTypesInTypeOfContext3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>; class A<T> { public class B<S> { public class E { } } } class Program { static void Main() { var type = typeof({|Replacement:C|}.B<>.E); } class [|D$$|] { public class B<S> { public class E { } } } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")> Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int[]>; class A<T> { } class Program { {|Resolve:C|} x; class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")> Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int*>; class A<T> { } class Program { {|Resolve:C|} x; class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")> Public Sub ReplaceAliasWithNestedGenericType(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>.E; class A<T> { public class E { } } class B { {|Resolve:C|} x; class [|D$$|] { } // Rename D to C } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory()> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Sub RewriteConflictingExtensionMethodCallSite(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { C Bar(int tag) { return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2); } } static class E { public static C [|$$Foo|](this C x, int tag) { return new C(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this, 1), 2);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <WorkItem(528902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528902")> <WorkItem(645152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645152")> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$Bar|](int tag) { this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2); } } static class E { public static C Foo(this C x, int tag) { return x; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this, 1), 2);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <WorkItem(542821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542821")> Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$Bar|]<T>() { {|Replacement:this.{|Resolved:Foo|}<int>()|}; } } static class E { public static void Foo<T>(this C x) { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")> Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$Bar|]<T>(T y) { {|Replacement:this.{|Resolved:Foo|}(42)|}; } } static class E { public static void Foo<T>(this C x, T y) { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DoNotDetectQueryContinuationNamedTheSame(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { static void Main(string[] args) { var temp = from {|stmt1:$$x|} in "abc" select {|stmt1:x|} into y select y; } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") ' This may feel strange, but the "into" effectively splits scopes ' into two. There are no errors here. result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameHandlesUsingWithoutDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.IO; class Program { public static void Main(string[] args) { Stream {|stmt1:$$s|} = new Stream(); using ({|stmt2:s|}) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameHandlesForWithoutDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public static void Main(string[] args) { int {|stmt1:$$i|}; for ({|stmt2:i|} = 0; ; ) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAttributeSuffix(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [{|Special:Something|}()] class Foo{ } public class [|$$SomethingAttribute|] : Attribute { public [|SomethingAttribute|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="SpecialAttribute") result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAddAttributeSuffix(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [[|Something|]()] class Foo{ } public class [|$$SomethingAttribute|] : Attribute { public [|SomethingAttribute|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="Special") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameKeepAttributeSuffixOnUsages(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [[|SomethingAttribute|]()] class Foo { } public class [|$$SomethingAttribute|] : Attribute { public [|SomethingAttribute|] { } } </Document> </Project> </Workspace>, host:=host, renameTo:="FooAttribute") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameToConflictWithValue(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class C { public int TestProperty { set { int [|$$x|]; [|x|] = {|Conflict:value|}; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="value") ' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict) ' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543482")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAttributeWithConflictingUse(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class C { [Main()] static void test() { } } class MainAttribute : System.Attribute { static void Main() { } } class [|$$Main|] : System.Attribute { } </Document> </Project> </Workspace>, host:=host, renameTo:="FooAttribute") End Using End Sub <Theory> <WorkItem(542649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542649")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub QualifyTypeWithGlobalWhenConflicting(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class A { } class B { {|Resolve:A|} x; class [|$$C|] { } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub End Class <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameSymbolDoesNotConflictWithNestedLocals(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { void Foo() { { int x; } {|Stmt1:Bar|}(); } void [|$$Bar|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("Stmt1", "x();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameSymbolConflictWithLocals(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { void Foo() { int x; {|Stmt1:Bar|}(); } void [|$$Bar|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(528738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528738")> Public Sub RenameAliasToCatchConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using [|$$A|] = X.Something; using {|Conflict:B|} = X.SomethingElse; namespace X { class Something { } class SomethingElse { } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAttributeToCreateConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [{|Escape:Main|}] class Some { } class SpecialAttribute : Attribute { } class [|$$Main|] : Attribute // Rename 'Main' to 'Special' { } </Document> </Project> </Workspace>, host:=host, renameTo:="Special") result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameUsingToKeyword(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; using [|$$S|] = System.Collections; [A] class A : {|Resolve:Attribute|} { } class B { [|S|].ArrayList a; } </Document> </Project> </Workspace>, host:=host, renameTo:="Attribute") result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(16809, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/16809")> <WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")> Public Sub RenameInNestedClasses(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; namespace N { class A<T> { public virtual void Foo(T x) { } class B<S> : A<B<S>> { class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A { public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory()> <WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")> <WorkItem(531433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531433")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAndEscapeContextualKeywordsInCSharp(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System.Linq; class [|t$$o|] // Rename 'to' to 'from' { object q = from x in "" select new {|resolved:to|}(); } </Document> </Project> </Workspace>, host:=host, renameTo:="from") result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(522774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522774")> Public Sub RenameCrefWithConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; using F = N; namespace N { interface I { void Foo(); } } class C { class E : {|Resolve:F|}.I { /// <summary> /// This is a function <see cref="{|Resolve:F|}.I.Foo"/> /// </summary> public void Foo() { } } class [|$$K|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameClassContainingAlias(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; using C = A<int,int>; class A<T,U> { public class B<S> { } } class [|$$B|] { {|Resolve:C|}.B<int> cb; } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameFunctionWithOverloadConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Bar { void Foo(int x) { } void [|Boo|](object x) { } void Some() { Foo(1); {|Resolve:$$Boo|}(1); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameActionWithFunctionConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class Program { static void doer(int x) { Console.WriteLine("Hey"); } static void Main(string[] args) { Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer {|stmt2:doer|}(3); } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="doer") result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552522")> Public Sub RenameFunctionNameToDelegateTypeConflict1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { static void [|Foo|]() { } class B { delegate void Del(); void Boo() { Del d = new Del({|Stmt1:Foo|}); {|Stmt2:$$Foo|}(); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Del") result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")> Public Sub RenameFunctionNameToDelegateTypeConflict2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { static void [|$$Foo|]() { } class B { delegate void Del(); void Bar() { } void Boo() { Del d = new Del({|Stmt1:Foo|}); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameFunctionNameToDelegateTypeConflict3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { delegate void Del(Del a); static void [|Bar|](Del a) { } class B { Del Boo = new Del({|decl1:Bar|}); void Foo() { Boo({|Stmt2:Bar|}); {|Stmt3:$$Bar|}(Boo); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Boo") result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")> Public Sub RenameFunctionNameToDelegateTypeConflict4(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { static void Foo(int i) { } static void Foo(string s) { } class B { delegate void Del(string s); void [|$$Bar|](string s) { } void Boo() { Del d = new Del({|stmt1:Foo|}); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")> Public Sub RenameActionTypeConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class A { static Action<int> [|$$Baz|] = (int x) => { }; class B { Action<int> Bar = (int x) => { }; void Foo() { {|Stmt1:Baz|}(3); } } }]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")> Public Sub RenameConflictAttribute1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ [{|escape:Bar|}] class Bar : System.Attribute { } class [|$$FooAttribute|] : System.Attribute { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="BarAttribute") result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameConflictAttribute2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [{|Resolve:B|}] class [|$$BAttribute|] : Attribute { } class AAttributeAttribute : Attribute { } </Document> </Project> </Workspace>, host:=host, renameTo:="AAttribute") result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(576573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576573")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug576573_ConflictAttributeWithNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; namespace X { class BAttribute : System.Attribute { } namespace Y.[|$$Z|] { [{|Resolve:B|}] class Foo { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="BAttribute") result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(579602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579602")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug579602_RenameFunctionWithDynamicParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { class B { public void [|Boo|](int d) { } //Line 1 } void Bar() { B b = new B(); dynamic d = 1.5f; b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub IdentifyConflictsWithVar(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class [|$$vor|] { static void Main(string[] args) { {|conflict:var|} x = 23; } } </Document> </Project> </Workspace>, host:=host, renameTo:="v\u0061r") result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(633180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633180")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(635622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635622")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ExpandingDynamicAddsObjectCast(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar static void Bar(dynamic x, Action y) { } static void Main() { {|resolve:Bar|}(1, Console.WriteLine); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameNamespaceConflictsAndResolves(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; namespace N { class C { {|resolve:N|}.C x; /// &lt;see cref="{|resolve:N|}.C"/&gt; void Sub() { } } namespace [|$$K|] // Rename K to N { class C { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameUnnecessaryExpansion(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> namespace N { using K = {|stmt1:N|}.C; class C { } class [|$$D|] // Rename D to N { class C { [|D|] x; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(768910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768910")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInCrefPreservesWhitespaceTrivia(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ public class A { public class B { public class C { } /// <summary> /// <see cref=" {|Resolve:D|}"/> /// </summary> public static void [|$$foo|]() // Rename foo to D { } } public class D { } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="D") result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub #Region "Type Argument Expand/Reduce for Generic Method Calls - 639136" <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { static void F&lt;T&gt;(Func&lt;int, T&gt; x) { } static void [|$$B|](Func&lt;int, int&gt; x) { } // Rename Bar to Foo static void Main() { {|stmt1:F|}(a => a); } } </Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <WorkItem(725934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/725934")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_This(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { void TestMethod() { int x = 1; Func&lt;int&gt; y = delegate { return {|stmt1:Foo|}(x); }; } int Foo&lt;T&gt;(T x) { return 1; } int [|$$Bar|](int x) { return 1; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_Nested(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void [|$$Foo|]<T>(T x) { } public static void Bar(int x) { } class D { void Bar<T>(T x) { } void Bar(int x) { } void sub() { {|stmt1:Foo|}(1); } } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ReferenceType(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public int Foo<T>(T x) { return 1; } public int [|$$Bar|](string x) {return 1; } // Rename Bar to Foo public void Test() { string one = "1"; {|stmt1:Foo|}(one); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void Foo<T>(T x) { } public static void [|$$Bar|](D<int> x) { } // Rename Bar to Foo public void Sub() { D<int> x = new D<int>(); {|stmt1:Foo|}(x); } } class D<T> {} ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System.Linq.Expressions; class C { public static int Foo<T>(T x) { return 1; } public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; } Expression<Func<int, int>> x = (y) => Foo(1); public void sub() { {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void [|$$Foo|]<S>(S x) { } public void Bar(int[] x) { } public void Sub() { var x = new int[] { 1, 2, 3 }; {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<S>(S x) { } public void [|$$Bar|](int[,] x) { } public void Sub() { var x = new int[,] { { 1, 2 }, { 2, 3 } }; {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } public void Sub(int x) { } public void Test() { Sub({|stmt1:Foo|}(1)); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public C(int x) { } public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } public void Test() { C c = new C({|stmt1:Foo|}(1)); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_CalledOnObject(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } // Rename Bar to Foo public void Test() { C c = new C(); c.{|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { delegate int FooDel<T>(T x); public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } // Rename Bar to Foo public void Test() { FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|}); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { delegate int FooDel(int x); public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } // Rename Bar to Foo public void Test() { FooDel foodel = new FooDel({|stmt1:Foo|}); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<T, S>(T x, S y) { } public void [|$$Bar|]<U, P>(U[] x, P y) { } public void Sub() { int[] x; {|stmt1:Foo|}(x, new C()); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <WorkItem(730781, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730781")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<T>(T x) { } } class D : C { public void [|$$Bar|](int x) { } public void Sub() { {|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(728653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728653")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameGenericInvocationWithDynamicArgument(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void F<T>(T s) { } public void [|$$Bar|](int s) { } // Rename Bar to F public void sub() { dynamic x = 1; {|stmt1:F|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(728646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728646")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ExpandInvocationInStaticMemberAccess(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void Foo<T>(T x) { } public static void [|$$Bar|](int x) { } // Rename Bar to Foo public void Sub() { } } class D { public void Sub() { C.{|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(728628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728628")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RecursiveTypeParameterExpansionFail(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C<T> { public static void Foo<T>(T x) { } public static void [|$$Bar|](C<int> x) { } // Rename Bar to Foo public void Sub() { C<int> x = new C<int>(); {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(728575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728575")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void Zoo<T>(T x) { } /// <summary> /// <see cref="{|cref1:Zoo|}"/> /// </summary> /// <param name="x"></param> public void [|$$Too|](int x) { } // Rename to Zoo } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Zoo") result.AssertLabeledSpansAre("cref1", "Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_GenericBase(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C<T> { public static void Foo<T>(T x) { } public static void [|$$Bar|](int x) { } // Rename Bar to Foo } class D : C<int> { public void Test() { {|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <WpfTheory(Skip:="Story 736967"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_InErrorCode(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<T>(T y,out T x) { x = y; } public void [|$$Bar|](int y, out int x) // Rename Bar to Foo { x = 1; } public void Test() { int y = 1; int x; {|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T> } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub #End Region <WorkItem(1016652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016652")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; // rename INamespaceSymbol to ISymbol public interface {|unresolved1:$$INamespaceSymbol|} { } public interface {|DeclConflict:ISymbol|} { } public interface IReferenceFinder { } internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder where TSymbol : {|unresolved2:INamespaceSymbol|} { }]]></Document> </Project> </Workspace>, host:=host, renameTo:="ISymbol") result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { static void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } int zoo; } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } static int zoo; } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } int zoo; } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { int zoo; void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } void nameof(int x) { } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameComplexifiesInLambdaBodyExpression(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { static int [|$$M|](int b) => 5; static int N(long b) => 5; System.Func<int, int> a = d => {|resolved:N|}(1); System.Func<int> b = () => {|resolved:N|}(1); }]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameComplexifiesInExpressionBodiedMembers(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { int f = new C().{|resolved1:N|}(0); int [|$$M|](int b) => {|resolved2:N|}(0); int N(long b) => [|M|](0); int P => {|resolved2:N|}(0); }]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndInterface1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:C|} { } interface [|$$I|] { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndInterface2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class [|$$C|] { } interface {|conflict:I|} { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="I") result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndNamespace1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:$$C|} { } namespace N { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndNamespace2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:C|} { } namespace [|$$N|] { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestNoConflictBetweenTwoNamespaces(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ namespace [|$$N1|][ { } namespace N2 { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N2") End Using End Sub <WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class C { void M1(Action [|callback$$|]) { [|callback|](); } void M2(Func<bool> callback) { callback(); } void M3() { Action callback = () => { }; callback(); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="callback2") End Using End Sub <WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class C { void M() { int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a. Action {|conflict:a|} = () => { }; {|conflict:a|}(); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="a") result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { static void [|T|]$$(int x) { } [System.Obsolete(nameof(Test))] static void Test() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="Test") End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Test() { int [|T$$|]; var x = nameof({|conflict:Test|}); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Test") result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void [|$$M|](int x) { } void M() { var x = nameof(M); } } </Document> </Project> </Workspace>, host:=host, renameTo:="X") End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void [|X$$|]() { } void M() { var x = nameof(T); } } </Document> </Project> </Workspace>, host:=host, renameTo:="T") End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Program { static void M() { var [|Consol$$|] = 7; var x = nameof({|conflict:Console|}); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Console") result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|conflict:C$$|} { } </Document> </Project> </Workspace>, host:=host, renameTo:="C.D") result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode(host As RenameTestHost) Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }" Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|conflict:C$$|} { } </Document> </Project> </Workspace>, host:=host, renameTo:=renameTo) result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DeclarationConflictInFileWithoutReferences_SameProject(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { internal void [|A$$|]() { } internal void {|conflict:B|}() { } } </Document> <Document FilePath="Test2.cs"> class Program2 { void M() { Program p = null; p.{|conflict:A|}(); p.{|conflict:B|}(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1"> <Document FilePath="Test1.cs"> public class Program { public void [|A$$|]() { } public void {|conflict:B|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2"> <ProjectReference>CSAssembly1</ProjectReference> <Document FilePath="Test2.cs"> class Program2 { void M() { Program p = null; p.{|conflict:A|}(); p.{|conflict:B|}(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")> <WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test1.cs"> partial class C { private static void [|$$M|]() { {|conflict:M|}(); } } </Document> <Document FilePath="Test2.cs"> partial class C { private static void {|conflict:Method|}() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="Method") result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInsideNameOf1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int field; static void Main(string[] args) { // Rename "local" to "field" int [|$$local|]; nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field } } </Document> </Project> </Workspace>, host:=host, renameTo:="field") result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInsideNameOf2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int field; static void Main(string[] args) { // Rename "local" to "field" int [|$$local|]; nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field } } </Document> </Project> </Workspace>, host:=host, renameTo:="field") result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInsideNameOf3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static int field; static void Main(string[] args) { // Rename "local" to "field" int [|$$local|]; Program.nameof({|Conflict:field|}); // Should also expand to Program.field } static void nameof(string s) { } } </Document> </Project> </Workspace>, host:=host, renameTo:="field") result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")> Public Sub RenameTypeParameterInPartialClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class C&lt;[|$$T|]&gt; {} partial class C&lt;[|T|]&gt; {} </Document> </Project> </Workspace>, host:=host, renameTo:="T2") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")> Public Sub RenameMethodToConflictWithTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class C&lt;{|Conflict:T|}&gt; { void [|$$M|]() { } } partial class C&lt;{|Conflict:T|}&gt; {} </Document> </Project> </Workspace>, host:=host, renameTo:="T") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(10469, "https://github.com/dotnet/roslyn/issues/10469")> Public Sub RenameTypeToCurrent(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class {|current:$$C|} { } </Document> </Project> </Workspace>, host:=host, renameTo:="Current") result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(16567, "https://github.com/dotnet/roslyn/issues/16567")> Public Sub RenameMethodToFinalizeWithDestructorPresent(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { ~{|Conflict:C|}() { } void $$[|M|]() { int x = 7; int y = ~x; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Finalize") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(5872, "https://github.com/dotnet/roslyn/issues/5872")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameToVar(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $${|Conflict:X|} { {|Conflict:X|}() { var a = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="var") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenRenamingPropertySetterLikeMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int MyProperty { get; {|conflict:set|}; } private void {|conflict:$$_set_MyProperty|}(int value) => throw null; } </Document> </Project> </Workspace>, host:=host, renameTo:="set_MyProperty") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenRenamingPropertyInitterLikeMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int MyProperty { get; {|conflict:init|}; } private void {|conflict:$$_set_MyProperty|}(int value) => throw null; } </Document> </Project> </Workspace>, host:=host, renameTo:="set_MyProperty") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenRenamingPropertyGetterLikeMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int MyProperty { {|conflict:get|}; set; } private int {|conflict:$$_get_MyProperty|}() => throw null; } </Document> </Project> </Workspace>, host:=host, renameTo:="get_MyProperty") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using 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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename Partial Public Class RenameEngineTests <[UseExportProvider]> Public Class CSharpConflicts Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <WorkItem(773543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773543")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithRollBacksInsideLambdas_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class C { class D { public int x = 1; } Action&lt;int> a = (int [|$$x|]) => // Rename x to y { var {|Conflict:y|} = new D(); Console.{|Conflict:WriteLine|}({|Conflict:x|}); }; } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(773534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773534")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithRollBacksInsideLambdas_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; struct y { public int x; } class C { class D { public int x = 1; } Action&lt;y> a = (y [|$$x|]) => // Rename x to y { var {|Conflict:y|} = new D(); Console.WriteLine(y.x); Console.WriteLine({|Conflict:x|}.{|Conflict:x|}); }; } </Document> </Project> </Workspace>, host:=host, renameTo:="y") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(773435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773435")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithInvocationOnDelegateInstance(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public delegate void Foo(int x); public void FooMeth(int x) { } public void Sub() { Foo {|Conflict:x|} = new Foo(FooMeth); int [|$$z|] = 1; // Rename z to x int y = {|Conflict:z|}; x({|Conflict:z|}); // Renamed to x(x) } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(782020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782020")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameWithSameClassInOneNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using K = N.{|Conflict:C|}; // No change, show compiler error namespace N { class {|Conflict:C|} { } } namespace N { class {|Conflict:$$D|} // Rename D to C { } } </Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub BreakingRenameCrossAssembly(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1"> <ProjectReference>CSAssembly1</ProjectReference> <Document> Class D Public Sub Boo() Dim x = New {|Conflict:$$C|}() End Sub End Class </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1"> <Document> public class [|C|] { public static void Foo() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="D") result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideLambdaBody(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Proaasgram { object z; public void masdain(string[] args) { Func&lt;int, bool> sx = (int [|$$x|]) => { {|resolve:z|} = null; if (true) { bool y = foo([|x|]); } return true; }; } public bool foo(int bar) { return true; } public bool foo(object bar) { return true; } } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideExpressionBodiedLambda(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; public class B { public readonly int z = 0; public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|}; } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideExpressionBodiedLambda2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; public class B { public static readonly int z = 0; public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|}; } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInsideMethodBody(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; public class B { public readonly int z = 0; public int Y(int [|$$y|]) { [|y|] = 0; return {|resolve:z|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="z") result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}(y => {|resolve2:Inner|}(x => { var z = 5; z.{|resolve0:Ex|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="L") Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.L();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => { var z = 5; z.{|resolve0:Ex|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="L") Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.L();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => { var z = 5; z.{|resolve0:D|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$D|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Ex") Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.Ex();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_4(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}(y => {|resolve2:Inner|}(x => { var z = 5; z.{|resolve0:D|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$D|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Ex") Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code>z.Ex();</code>.Value + vbCrLf + <code>x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictResolutionInInvocationWithLambda_5(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolve1:Outer|}(y => {|resolve2:Inner|}(x => { var z = 5; z.{|resolve0:D|}(); x.Ex(); }, y), 0); } } static class E { public static void [|$$D|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Ex") Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf + <code> var z = 5;</code>.Value + vbCrLf + <code> z.Ex();</code>.Value + vbCrLf + <code> x.Ex();</code>.Value + vbCrLf + <code> }, y), 0);</code>.Value result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithInstanceField1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { int foo; void Blah(int [|$$bar|]) { {|stmt2:foo|} = {|stmt1:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithInstanceField2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { int foo; void Blah(int [|$$bar|]) { {|resolved:foo|} = 23; {|resolved2:foo|} = {|stmt1:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { int @if; void Blah(int {|Escape1:$$bar|}) { {|Resolve:@if|} = 23; {|Resolve2:@if|} = {|Escape2:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="if") result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithStaticField(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { static int foo; void Blah(int [|$$bar|]) { {|Resolved:foo|} = 23; {|Resolved2:foo|} = {|stmt1:bar|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ParameterConflictingWithFieldFromAnotherLanguage(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <ProjectReference>VisualBasicAssembly</ProjectReference> <Document> class Foo : FooBase { void Blah(int bar) { {|Resolve:$$foo|} = bar; } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document> Public Class FooBase Protected [|foo|] As Integer End Class </Document> </Project> </Workspace>, host:=host, renameTo:="bar") result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <WorkItem(539745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539745")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictingTypeDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="6"> <Document><![CDATA[ namespace N1 { using static C<int>; class Program { public void Goo(int i) { {|ReplacementCInt:Foo|}(i, i); } } } namespace N2 { using static C<string>; class Program { public void Goo(string s) { {|ReplacementCString:Foo|}(s, s); } } } static class C<T> { public static void [|$$Foo|](T i, T j) { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="Goo") result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToInvalidIdentifier(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Invalid:$$Foo|} { {|Invalid:Foo|} foo; } </Document> </Project> </Workspace>, host:=host, renameTo:="`") result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict) result.AssertReplacementTextInvalid() End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToInvalidIdentifier2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Invalid:$$Foo|} { {|Invalid:Foo|} foo; } </Document> </Project> </Workspace>, host:=host, renameTo:="!") result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict) result.AssertReplacementTextInvalid() End Using End Sub <Theory> <WorkItem(539636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539636")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToConflictingMethodInvocation(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static void F() { } class Blah { void [|$$M|]() { {|Replacement:F|}(); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingToConflictingMethodInvocation2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void M() { int foo; {|Replacement:Bar|}(); } void [|$$Bar|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="foo") result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingTypeToConflictingMemberAndParentTypeName(host As RenameTestHost) ' It's important that we see conflicts for both simultaneously, so I do a single ' test for both cases. Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Conflict:Foo|} { class [|$$Bar|] { int {|Conflict:Foo|}; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingMemberToNameConflictingWithParent(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Conflict:Foo|} { int [|$$Bar|]; } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(540199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540199")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingMemberToInvalidIdentifierName(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|Invalid:$$Foo|} { } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo@") result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MinimalQualificationOfBaseType1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class X { protected class [|$$A|] { } } class Y : X { private class C : {|Resolve:A|} { } private class B { } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MinimalQualificationOfBaseType2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class X { protected class A { } } class Y : X { private class C : {|Resolve:A|} { } private class [|$$B|] { } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeIfKeywordWhenDoingTypeNameQualification(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> static class Foo { static void {|Escape:Method$$|}() { } static void Test() { int @if; {|Replacement:Method|}(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="if") result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeUnboundGenericTypesInTypeOfContext(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>; class A<T> { public class B<S> { } } class Program { static void Main() { var type = typeof({|stmt1:C|}.B<>); } class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeUnboundGenericTypesInTypeOfContext2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>; class A<T> { public class B<S> { public class E { } } } class Program { static void Main() { var type = typeof({|Replacement:C|}.B<>.E); } class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")> Public Sub EscapeUnboundGenericTypesInTypeOfContext3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>; class A<T> { public class B<S> { public class E { } } } class Program { static void Main() { var type = typeof({|Replacement:C|}.B<>.E); } class [|D$$|] { public class B<S> { public class E { } } } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")> Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int[]>; class A<T> { } class Program { {|Resolve:C|} x; class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")> Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int*>; class A<T> { } class Program { {|Resolve:C|} x; class [|D$$|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")> Public Sub ReplaceAliasWithNestedGenericType(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using C = A<int>.E; class A<T> { public class E { } } class B { {|Resolve:C|} x; class [|D$$|] { } // Rename D to C } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory()> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Sub RewriteConflictingExtensionMethodCallSite(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { C Bar(int tag) { return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2); } } static class E { public static C [|$$Foo|](this C x, int tag) { return new C(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this, 1), 2);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <WorkItem(528902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528902")> <WorkItem(645152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645152")> <WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")> Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$Bar|](int tag) { this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2); } } static class E { public static C Foo(this C x, int tag) { return x; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this, 1), 2);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <WorkItem(542821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542821")> Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$Bar|]<T>() { {|Replacement:this.{|Resolved:Foo|}<int>()|}; } } static class E { public static void Foo<T>(this C x) { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")> <WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")> Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$Bar|]<T>(T y) { {|Replacement:this.{|Resolved:Foo|}(42)|}; } } static class E { public static void Foo<T>(this C x, T y) { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DoNotDetectQueryContinuationNamedTheSame(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { static void Main(string[] args) { var temp = from {|stmt1:$$x|} in "abc" select {|stmt1:x|} into y select y; } } </Document> </Project> </Workspace>, host:=host, renameTo:="y") ' This may feel strange, but the "into" effectively splits scopes ' into two. There are no errors here. result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameHandlesUsingWithoutDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.IO; class Program { public static void Main(string[] args) { Stream {|stmt1:$$s|} = new Stream(); using ({|stmt2:s|}) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameHandlesForWithoutDeclaration(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public static void Main(string[] args) { int {|stmt1:$$i|}; for ({|stmt2:i|} = 0; ; ) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAttributeSuffix(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [{|Special:Something|}()] class Foo{ } public class [|$$SomethingAttribute|] : Attribute { public [|SomethingAttribute|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="SpecialAttribute") result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAddAttributeSuffix(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [[|Something|]()] class Foo{ } public class [|$$SomethingAttribute|] : Attribute { public [|SomethingAttribute|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="Special") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameKeepAttributeSuffixOnUsages(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [[|SomethingAttribute|]()] class Foo { } public class [|$$SomethingAttribute|] : Attribute { public [|SomethingAttribute|] { } } </Document> </Project> </Workspace>, host:=host, renameTo:="FooAttribute") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameToConflictWithValue(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class C { public int TestProperty { set { int [|$$x|]; [|x|] = {|Conflict:value|}; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="value") ' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict) ' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <WorkItem(543482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543482")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAttributeWithConflictingUse(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class C { [Main()] static void test() { } } class MainAttribute : System.Attribute { static void Main() { } } class [|$$Main|] : System.Attribute { } </Document> </Project> </Workspace>, host:=host, renameTo:="FooAttribute") End Using End Sub <Theory> <WorkItem(542649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542649")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub QualifyTypeWithGlobalWhenConflicting(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class A { } class B { {|Resolve:A|} x; class [|$$C|] { } } </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub End Class <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameSymbolDoesNotConflictWithNestedLocals(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { void Foo() { { int x; } {|Stmt1:Bar|}(); } void [|$$Bar|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("Stmt1", "x();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameSymbolConflictWithLocals(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { void Foo() { int x; {|Stmt1:Bar|}(); } void [|$$Bar|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="x") result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(528738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528738")> Public Sub RenameAliasToCatchConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using [|$$A|] = X.Something; using {|Conflict:B|} = X.SomethingElse; namespace X { class Something { } class SomethingElse { } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAttributeToCreateConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [{|Escape:Main|}] class Some { } class SpecialAttribute : Attribute { } class [|$$Main|] : Attribute // Rename 'Main' to 'Special' { } </Document> </Project> </Workspace>, host:=host, renameTo:="Special") result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameUsingToKeyword(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; using [|$$S|] = System.Collections; [A] class A : {|Resolve:Attribute|} { } class B { [|S|].ArrayList a; } </Document> </Project> </Workspace>, host:=host, renameTo:="Attribute") result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(16809, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/16809")> <WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")> Public Sub RenameInNestedClasses(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; namespace N { class A<T> { public virtual void Foo(T x) { } class B<S> : A<B<S>> { class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A { public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { } } } } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="A") result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory()> <WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")> <WorkItem(531433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531433")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameAndEscapeContextualKeywordsInCSharp(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System.Linq; class [|t$$o|] // Rename 'to' to 'from' { object q = from x in "" select new {|resolved:to|}(); } </Document> </Project> </Workspace>, host:=host, renameTo:="from") result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(522774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522774")> Public Sub RenameCrefWithConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; using F = N; namespace N { interface I { void Foo(); } } class C { class E : {|Resolve:F|}.I { /// <summary> /// This is a function <see cref="{|Resolve:F|}.I.Foo"/> /// </summary> public void Foo() { } } class [|$$K|] { } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameClassContainingAlias(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; using C = A<int,int>; class A<T,U> { public class B<S> { } } class [|$$B|] { {|Resolve:C|}.B<int> cb; } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameFunctionWithOverloadConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> class Bar { void Foo(int x) { } void [|Boo|](object x) { } void Some() { Foo(1); {|Resolve:$$Boo|}(1); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameActionWithFunctionConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class Program { static void doer(int x) { Console.WriteLine("Hey"); } static void Main(string[] args) { Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer {|stmt2:doer|}(3); } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="doer") result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552522")> Public Sub RenameFunctionNameToDelegateTypeConflict1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { static void [|Foo|]() { } class B { delegate void Del(); void Boo() { Del d = new Del({|Stmt1:Foo|}); {|Stmt2:$$Foo|}(); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Del") result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")> Public Sub RenameFunctionNameToDelegateTypeConflict2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { static void [|$$Foo|]() { } class B { delegate void Del(); void Bar() { } void Boo() { Del d = new Del({|Stmt1:Foo|}); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameFunctionNameToDelegateTypeConflict3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { delegate void Del(Del a); static void [|Bar|](Del a) { } class B { Del Boo = new Del({|decl1:Bar|}); void Foo() { Boo({|Stmt2:Bar|}); {|Stmt3:$$Bar|}(Boo); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Boo") result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")> Public Sub RenameFunctionNameToDelegateTypeConflict4(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { static void Foo(int i) { } static void Foo(string s) { } class B { delegate void Del(string s); void [|$$Bar|](string s) { } void Boo() { Del d = new Del({|stmt1:Foo|}); } } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")> Public Sub RenameActionTypeConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class A { static Action<int> [|$$Baz|] = (int x) => { }; class B { Action<int> Bar = (int x) => { }; void Foo() { {|Stmt1:Baz|}(3); } } }]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")> Public Sub RenameConflictAttribute1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ [{|escape:Bar|}] class Bar : System.Attribute { } class [|$$FooAttribute|] : System.Attribute { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="BarAttribute") result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameConflictAttribute2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; [{|Resolve:B|}] class [|$$BAttribute|] : Attribute { } class AAttributeAttribute : Attribute { } </Document> </Project> </Workspace>, host:=host, renameTo:="AAttribute") result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(576573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576573")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug576573_ConflictAttributeWithNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; namespace X { class BAttribute : System.Attribute { } namespace Y.[|$$Z|] { [{|Resolve:B|}] class Foo { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="BAttribute") result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(579602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579602")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug579602_RenameFunctionWithDynamicParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class A { class B { public void [|Boo|](int d) { } //Line 1 } void Bar() { B b = new B(); dynamic d = 1.5f; b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict) End Using End Sub <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub IdentifyConflictsWithVar(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class [|$$vor|] { static void Main(string[] args) { {|conflict:var|} x = 23; } } </Document> </Project> </Workspace>, host:=host, renameTo:="v\u0061r") result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(633180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633180")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; static class C { static void Ex(this string x) { } static void Outer(Action&lt;string> x, object y) { Console.WriteLine(1); } static void Outer(Action&lt;int> x, int y) { Console.WriteLine(2); } static void Inner(Action&lt;string> x, string y) { } static void Inner(Action&lt;string> x, int y) { } static void Inner(Action&lt;int> x, int y) { } static void Main() { {|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0); } } static class E { public static void [|$$Ex|](this int x) { } // Rename Ex to Foo } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(635622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635622")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ExpandingDynamicAddsObjectCast(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar static void Bar(dynamic x, Action y) { } static void Main() { {|resolve:Bar|}(1, Console.WriteLine); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameNamespaceConflictsAndResolves(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; namespace N { class C { {|resolve:N|}.C x; /// &lt;see cref="{|resolve:N|}.C"/&gt; void Sub() { } } namespace [|$$K|] // Rename K to N { class C { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameUnnecessaryExpansion(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> namespace N { using K = {|stmt1:N|}.C; class C { } class [|$$D|] // Rename D to N { class C { [|D|] x; } } } </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(768910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768910")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInCrefPreservesWhitespaceTrivia(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ public class A { public class B { public class C { } /// <summary> /// <see cref=" {|Resolve:D|}"/> /// </summary> public static void [|$$foo|]() // Rename foo to D { } } public class D { } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="D") result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub #Region "Type Argument Expand/Reduce for Generic Method Calls - 639136" <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { static void F&lt;T&gt;(Func&lt;int, T&gt; x) { } static void [|$$B|](Func&lt;int, int&gt; x) { } // Rename Bar to Foo static void Main() { {|stmt1:F|}(a => a); } } </Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <WorkItem(725934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/725934")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_This(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"> using System; class C { void TestMethod() { int x = 1; Func&lt;int&gt; y = delegate { return {|stmt1:Foo|}(x); }; } int Foo&lt;T&gt;(T x) { return 1; } int [|$$Bar|](int x) { return 1; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_Nested(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void [|$$Foo|]<T>(T x) { } public static void Bar(int x) { } class D { void Bar<T>(T x) { } void Bar(int x) { } void sub() { {|stmt1:Foo|}(1); } } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ReferenceType(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public int Foo<T>(T x) { return 1; } public int [|$$Bar|](string x) {return 1; } // Rename Bar to Foo public void Test() { string one = "1"; {|stmt1:Foo|}(one); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void Foo<T>(T x) { } public static void [|$$Bar|](D<int> x) { } // Rename Bar to Foo public void Sub() { D<int> x = new D<int>(); {|stmt1:Foo|}(x); } } class D<T> {} ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System.Linq.Expressions; class C { public static int Foo<T>(T x) { return 1; } public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; } Expression<Func<int, int>> x = (y) => Foo(1); public void sub() { {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void [|$$Foo|]<S>(S x) { } public void Bar(int[] x) { } public void Sub() { var x = new int[] { 1, 2, 3 }; {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<S>(S x) { } public void [|$$Bar|](int[,] x) { } public void Sub() { var x = new int[,] { { 1, 2 }, { 2, 3 } }; {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } public void Sub(int x) { } public void Test() { Sub({|stmt1:Foo|}(1)); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public C(int x) { } public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } public void Test() { C c = new C({|stmt1:Foo|}(1)); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_CalledOnObject(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } // Rename Bar to Foo public void Test() { C c = new C(); c.{|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { delegate int FooDel<T>(T x); public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } // Rename Bar to Foo public void Test() { FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|}); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { delegate int FooDel(int x); public int Foo<T>(T x) { return 1; } public int [|$$Bar|](int x) {return 1; } // Rename Bar to Foo public void Test() { FooDel foodel = new FooDel({|stmt1:Foo|}); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<T, S>(T x, S y) { } public void [|$$Bar|]<U, P>(U[] x, P y) { } public void Sub() { int[] x; {|stmt1:Foo|}(x, new C()); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <WorkItem(730781, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730781")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<T>(T x) { } } class D : C { public void [|$$Bar|](int x) { } public void Sub() { {|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(728653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728653")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameGenericInvocationWithDynamicArgument(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void F<T>(T s) { } public void [|$$Bar|](int s) { } // Rename Bar to F public void sub() { dynamic x = 1; {|stmt1:F|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="F") result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(728646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728646")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ExpandInvocationInStaticMemberAccess(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void Foo<T>(T x) { } public static void [|$$Bar|](int x) { } // Rename Bar to Foo public void Sub() { } } class D { public void Sub() { C.{|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(728628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728628")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RecursiveTypeParameterExpansionFail(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C<T> { public static void Foo<T>(T x) { } public static void [|$$Bar|](C<int> x) { } // Rename Bar to Foo public void Sub() { C<int> x = new C<int>(); {|stmt1:Foo|}(x); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(728575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728575")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public static void Zoo<T>(T x) { } /// <summary> /// <see cref="{|cref1:Zoo|}"/> /// </summary> /// <param name="x"></param> public void [|$$Too|](int x) { } // Rename to Zoo } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Zoo") result.AssertLabeledSpansAre("cref1", "Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_GenericBase(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C<T> { public static void Foo<T>(T x) { } public static void [|$$Bar|](int x) { } // Rename Bar to Foo } class D : C<int> { public void Test() { {|stmt1:Foo|}(1); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")> <WpfTheory(Skip:="Story 736967"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub GenericNameTypeInferenceExpansion_InErrorCode(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { public void Foo<T>(T y,out T x) { x = y; } public void [|$$Bar|](int y, out int x) // Rename Bar to Foo { x = 1; } public void Test() { int y = 1; int x; {|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T> } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub #End Region <WorkItem(1016652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016652")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; // rename INamespaceSymbol to ISymbol public interface {|unresolved1:$$INamespaceSymbol|} { } public interface {|DeclConflict:ISymbol|} { } public interface IReferenceFinder { } internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder where TSymbol : {|unresolved2:INamespaceSymbol|} { }]]></Document> </Project> </Workspace>, host:=host, renameTo:="ISymbol") result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { static void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } int zoo; } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } static int zoo; } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } int zoo; } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { int zoo; void F(int [|$$z|]) { string x = nameof({|ref:zoo|}); } void nameof(int x) { } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="zoo") result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameComplexifiesInLambdaBodyExpression(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { static int [|$$M|](int b) => 5; static int N(long b) => 5; System.Func<int, int> a = d => {|resolved:N|}(1); System.Func<int> b = () => {|resolved:N|}(1); }]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameComplexifiesInExpressionBodiedMembers(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class C { int f = new C().{|resolved1:N|}(0); int [|$$M|](int b) => {|resolved2:N|}(0); int N(long b) => [|M|](0); int P => {|resolved2:N|}(0); }]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndInterface1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:C|} { } interface [|$$I|] { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndInterface2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class [|$$C|] { } interface {|conflict:I|} { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="I") result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndNamespace1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:$$C|} { } namespace N { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndNamespace1_FileScopedNamespace(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:$$C|} { } namespace N; ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N") result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictBetweenClassAndNamespace2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ class {|conflict:C|} { } namespace [|$$N|] { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="C") result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict) End Using End Sub <WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestNoConflictBetweenTwoNamespaces(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ namespace [|$$N1|][ { } namespace N2 { } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="N2") End Using End Sub <WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class C { void M1(Action [|callback$$|]) { [|callback|](); } void M2(Func<bool> callback) { callback(); } void M3() { Action callback = () => { }; callback(); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="callback2") End Using End Sub <WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test.cs"><![CDATA[ using System; class C { void M() { int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a. Action {|conflict:a|} = () => { }; {|conflict:a|}(); } } ]]> </Document> </Project> </Workspace>, host:=host, renameTo:="a") result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { static void [|T|]$$(int x) { } [System.Obsolete(nameof(Test))] static void Test() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="Test") End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void Test() { int [|T$$|]; var x = nameof({|conflict:Test|}); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Test") result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void [|$$M|](int x) { } void M() { var x = nameof(M); } } </Document> </Project> </Workspace>, host:=host, renameTo:="X") End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void [|X$$|]() { } void M() { var x = nameof(T); } } </Document> </Project> </Workspace>, host:=host, renameTo:="T") End Using End Sub <WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Program { static void M() { var [|Consol$$|] = 7; var x = nameof({|conflict:Console|}); } } </Document> </Project> </Workspace>, host:=host, renameTo:="Console") result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|conflict:C$$|} { } </Document> </Project> </Workspace>, host:=host, renameTo:="C.D") result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode(host As RenameTestHost) Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }" Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|conflict:C$$|} { } </Document> </Project> </Workspace>, host:=host, renameTo:=renameTo) result.AssertReplacementTextInvalid() result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DeclarationConflictInFileWithoutReferences_SameProject(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test1.cs"> class Program { internal void [|A$$|]() { } internal void {|conflict:B|}() { } } </Document> <Document FilePath="Test2.cs"> class Program2 { void M() { Program p = null; p.{|conflict:A|}(); p.{|conflict:B|}(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1"> <Document FilePath="Test1.cs"> public class Program { public void [|A$$|]() { } public void {|conflict:B|}() { } } </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2"> <ProjectReference>CSAssembly1</ProjectReference> <Document FilePath="Test2.cs"> class Program2 { void M() { Program p = null; p.{|conflict:A|}(); p.{|conflict:B|}(); } } </Document> </Project> </Workspace>, host:=host, renameTo:="B") result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")> <WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")> <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test1.cs"> partial class C { private static void [|$$M|]() { {|conflict:M|}(); } } </Document> <Document FilePath="Test2.cs"> partial class C { private static void {|conflict:Method|}() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="Method") result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInsideNameOf1(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int field; static void Main(string[] args) { // Rename "local" to "field" int [|$$local|]; nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field } } </Document> </Project> </Workspace>, host:=host, renameTo:="field") result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInsideNameOf2(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int field; static void Main(string[] args) { // Rename "local" to "field" int [|$$local|]; nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field } } </Document> </Project> </Workspace>, host:=host, renameTo:="field") result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInsideNameOf3(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { static int field; static void Main(string[] args) { // Rename "local" to "field" int [|$$local|]; Program.nameof({|Conflict:field|}); // Should also expand to Program.field } static void nameof(string s) { } } </Document> </Project> </Workspace>, host:=host, renameTo:="field") result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")> Public Sub RenameTypeParameterInPartialClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class C&lt;[|$$T|]&gt; {} partial class C&lt;[|T|]&gt; {} </Document> </Project> </Workspace>, host:=host, renameTo:="T2") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")> Public Sub RenameMethodToConflictWithTypeParameter(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class C&lt;{|Conflict:T|}&gt; { void [|$$M|]() { } } partial class C&lt;{|Conflict:T|}&gt; {} </Document> </Project> </Workspace>, host:=host, renameTo:="T") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(10469, "https://github.com/dotnet/roslyn/issues/10469")> Public Sub RenameTypeToCurrent(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class {|current:$$C|} { } </Document> </Project> </Workspace>, host:=host, renameTo:="Current") result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict) End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(16567, "https://github.com/dotnet/roslyn/issues/16567")> Public Sub RenameMethodToFinalizeWithDestructorPresent(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { ~{|Conflict:C|}() { } void $$[|M|]() { int x = 7; int y = ~x; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Finalize") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(5872, "https://github.com/dotnet/roslyn/issues/5872")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameToVar(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $${|Conflict:X|} { {|Conflict:X|}() { var a = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="var") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenRenamingPropertySetterLikeMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int MyProperty { get; {|conflict:set|}; } private void {|conflict:$$_set_MyProperty|}(int value) => throw null; } </Document> </Project> </Workspace>, host:=host, renameTo:="set_MyProperty") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenRenamingPropertyInitterLikeMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int MyProperty { get; {|conflict:init|}; } private void {|conflict:$$_set_MyProperty|}(int value) => throw null; } </Document> </Project> </Workspace>, host:=host, renameTo:="set_MyProperty") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WpfTheory> <WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictWhenRenamingPropertyGetterLikeMethod(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public int MyProperty { {|conflict:get|}; set; } private int {|conflict:$$_get_MyProperty|}() => throw null; } </Document> </Project> </Workspace>, host:=host, renameTo:="get_MyProperty") result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub End Class End Namespace
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/CodeGeneration/NamespaceGenerator.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.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default), BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class NamespaceGenerator { public static BaseNamespaceDeclarationSyntax AddNamespaceTo( ICodeGenerationService service, BaseNamespaceDeclarationSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } public static CompilationUnitSyntax AddNamespaceTo( ICodeGenerationService service, CompilationUnitSyntax destination, INamespaceSymbol @namespace, CodeGenerationOptions options, IList<bool> availableIndices, CancellationToken cancellationToken) { var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken); if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration) throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination); var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices); return destination.WithMembers(members); } internal static SyntaxNode GenerateNamespaceDeclaration( ICodeGenerationService service, INamespaceSymbol @namespace, CodeGenerationOptions options, CancellationToken cancellationToken) { options ??= CodeGenerationOptions.Default; GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace); var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options); declaration = options.GenerateMembers ? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken) : declaration; return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration( ICodeGenerationService service, SyntaxNode declaration, IList<ISymbol> newMembers, CodeGenerationOptions options, CancellationToken cancellationToken) { declaration = RemoveAllMembers(declaration); declaration = service.AddMembers(declaration, newMembers, options, cancellationToken); return AddFormatterAndCodeGeneratorAnnotationsTo(declaration); } private static SyntaxNode GenerateNamespaceDeclarationWorker( string name, INamespaceSymbol innermostNamespace) { var usings = GenerateUsingDirectives(innermostNamespace); // If they're just generating the empty namespace then make that into compilation unit. if (name == string.Empty) { return SyntaxFactory.CompilationUnit().WithUsings(usings); } return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings); } private static SyntaxNode GetDeclarationSyntaxWithoutMembers( INamespaceSymbol @namespace, INamespaceSymbol innermostNamespace, string name, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options); if (reusableSyntax == null) { return GenerateNamespaceDeclarationWorker(name, innermostNamespace); } return RemoveAllMembers(reusableSyntax); } private static SyntaxNode RemoveAllMembers(SyntaxNode declaration) => declaration switch { CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default), BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default), _ => declaration, }; private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace) { var usingDirectives = CodeGenerationNamespaceInfo.GetImports(innermostNamespace) .Select(GenerateUsingDirective) .WhereNotNull() .ToList(); return usingDirectives.ToSyntaxList(); } private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol) { if (symbol is IAliasSymbol alias) { var name = GenerateName(alias.Target); if (name != null) { return SyntaxFactory.UsingDirective( SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()), name); } } else if (symbol is INamespaceOrTypeSymbol namespaceOrType) { var name = GenerateName(namespaceOrType); if (name != null) { return SyntaxFactory.UsingDirective(name); } } return null; } private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol) { if (symbol is ITypeSymbol type) { return type.GenerateTypeSyntax() as NameSyntax; } else { return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } } } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.Rewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports { internal partial class CSharpOrganizeImportsService { private class Rewriter : CSharpSyntaxRewriter { private readonly bool _placeSystemNamespaceFirst; private readonly bool _separateGroups; public readonly IList<TextChange> TextChanges = new List<TextChange>(); public Rewriter(bool placeSystemNamespaceFirst, bool separateGroups) { _placeSystemNamespaceFirst = placeSystemNamespaceFirst; _separateGroups = separateGroups; } public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!; UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node)); public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node)); private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node) { Contract.ThrowIfNull(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { if (list.Count > 0) this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); } private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode => string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode => TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports { internal partial class CSharpOrganizeImportsService { private class Rewriter : CSharpSyntaxRewriter { private readonly bool _placeSystemNamespaceFirst; private readonly bool _separateGroups; public readonly IList<TextChange> TextChanges = new List<TextChange>(); public Rewriter(bool placeSystemNamespaceFirst, bool separateGroups) { _placeSystemNamespaceFirst = placeSystemNamespaceFirst; _separateGroups = separateGroups; } public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node) { node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!; UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node)); public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node)); private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node) { Contract.ThrowIfNull(node); UsingsAndExternAliasesOrganizer.Organize( node.Externs, node.Usings, _placeSystemNamespaceFirst, _separateGroups, out var organizedExternAliasList, out var organizedUsingList); var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList); if (node != result) { AddTextChange(node.Externs, organizedExternAliasList); AddTextChange(node.Usings, organizedUsingList); } return result; } private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode { if (list.Count > 0) this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList))); } private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode => string.Join(string.Empty, organizedList.Select(t => t.ToFullString())); private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode => TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End); } } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Recommendations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Recommendations { internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext> { public CSharpRecommendationServiceRunner( CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) : base(context, filterOutOfScopeLocals, cancellationToken) { } public override RecommendedSymbols GetRecommendedSymbols() { if (_context.IsInNonUserCode || _context.IsPreProcessorDirectiveContext) { return default; } if (!_context.IsRightOfNameSeparator) return new RecommendedSymbols(GetSymbolsForCurrentContext()); return GetSymbolsOffOfContainer(); } public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType) { if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax)) { var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters; if (parameters.Count > ordinalInLambda) { var parameter = parameters[ordinalInLambda]; if (parameter.Type != null) { explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type; return explicitLambdaParameterType != null; } } } // Non-parenthesized lambdas cannot explicitly specify the type of the single parameter explicitLambdaParameterType = null; return false; } private ImmutableArray<ISymbol> GetSymbolsForCurrentContext() { if (_context.IsGlobalStatementContext) { // Script and interactive return GetSymbolsForGlobalStatementContext(); } else if (_context.IsAnyExpressionContext || _context.IsStatementContext || _context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken)) { // GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as // as cast. The user might be trying to type a parenthesized expression, so even though a cast // is a type-only context, we'll show all symbols anyway. return GetSymbolsForExpressionOrStatementContext(); } else if (_context.IsTypeContext || _context.IsNamespaceContext) { return GetSymbolsForTypeOrNamespaceContext(); } else if (_context.IsLabelContext) { return GetSymbolsForLabelContext(); } else if (_context.IsTypeArgumentOfConstraintContext) { return GetSymbolsForTypeArgumentOfConstraintClause(); } else if (_context.IsDestructorTypeContext) { var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken); return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol); } else if (_context.IsNamespaceDeclarationNameContext) { return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>(); } return ImmutableArray<ISymbol>.Empty; } private RecommendedSymbols GetSymbolsOffOfContainer() { // Ensure that we have the correct token in A.B| case var node = _context.TargetToken.GetRequiredParent(); return node switch { MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess => GetSymbolsOffOfExpression(memberAccess.Expression), MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess => GetSymbolsOffOfDereferencedExpression(memberAccess.Expression), // This code should be executing only if the cursor is between two dots in a dotdot token. RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand), QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left), AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias), MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression), _ => default, }; } private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext() { var syntaxTree = _context.SyntaxTree; var position = _context.Position; var token = _context.LeftToken; // The following code is a hack to get around a binding problem when asking binding // questions immediately after a using directive. This is special-cased in the binder // factory to ensure that using directives are not within scope inside other using // directives. That generally works fine for .cs, but it's a problem for interactive // code in this case: // // using System; // | if (token.Kind() == SyntaxKind.SemicolonToken && token.Parent.IsKind(SyntaxKind.UsingDirective) && position >= token.Span.End) { var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken); if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token) { token = token.GetNextToken(includeZeroWidth: true); } } var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart); return symbols; } private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause() { var enclosingSymbol = _context.LeftToken.GetRequiredParent() .AncestorsAndSelf() .Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken)) .WhereNotNull() .FirstOrDefault(); var symbols = enclosingSymbol != null ? enclosingSymbol.GetTypeArguments() : ImmutableArray<ITypeSymbol>.Empty; return ImmutableArray<ISymbol>.CastUp(symbols); } private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias) { var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken); if (aliasSymbol == null) return default; return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes( alias.SpanStart, aliasSymbol.Target)); } private ImmutableArray<ISymbol> GetSymbolsForLabelContext() { var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart); // Exclude labels (other than 'default') that come from case switch statements return allLabels .WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken) .IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel)); } private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext() { var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart); if (_context.TargetToken.IsUsingKeywordInUsingDirective()) { return symbols.WhereAsArray(s => s.IsNamespace()); } if (_context.TargetToken.IsStaticKeywordInUsingDirective()) { return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()); } return symbols; } private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext() { // Check if we're in an interesting situation like this: // // i // <-- here // I = 0; // The problem is that "i I = 0" causes a local to be in scope called "I". So, later when // we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that // name). If this is the case, we do not want to filter out inaccessible locals. var filterOutOfScopeLocals = _filterOutOfScopeLocals; if (filterOutOfScopeLocals) filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type); var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext() ? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart) : _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart); // Filter out any extension methods that might be imported by a using static directive. // But include extension methods declared in the context's type or it's parents var contextOuterTypes = _context.GetOuterTypes(_cancellationToken); var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); symbols = symbols.WhereAsArray(symbol => !symbol.IsExtensionMethod() || Equals(contextEnclosingNamedType, symbol.ContainingType) || contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType))); // The symbols may include local variables that are declared later in the method and // should not be included in the completion list, so remove those. Filter them away, // unless we're in the debugger, where we show all locals in scope. if (filterOutOfScopeLocals) { symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position)); } return symbols; } private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name) { // Using an is pattern on an enum is a qualified name, but normal symbol processing works fine if (_context.IsEnumTypeMemberAccessContext) return GetSymbolsOffOfExpression(name); if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container)) return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false); // We're in a name-only context, since if we were an expression we'd be a // MemberAccessExpressionSyntax. Thus, let's do other namespaces and types. nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken); if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol) return default; if (_context.IsNameOfContext) return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol)); var symbols = _context.SemanticModel.LookupNamespacesAndTypes( position: name.SpanStart, container: symbol); if (_context.IsNamespaceDeclarationNameContext) { var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>(); return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax))); } // Filter the types when in a using directive, but not an alias. // // Cases: // using | -- Show namespaces // using A.| -- Show namespaces // using static | -- Show namespace and types // using A = B.| -- Show namespace and types var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>(); if (usingDirective != null && usingDirective.Alias == null) { return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType()) : symbols.WhereAsArray(s => s.IsNamespace())); } return new RecommendedSymbols(symbols); } /// <summary> /// DeterminesCheck if we're in an interesting situation like this: /// <code> /// int i = 5; /// i. // -- here /// List ml = new List(); /// </code> /// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is /// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't /// part of a local declaration's type. /// <para/> /// Another interesting case is something like: /// <code> /// stringList. /// await Test2(); /// </code> /// Here "stringList.await" is thought of as the return type of a local function. /// </summary> private bool ShouldBeTreatedAsTypeInsteadOfExpression( ExpressionSyntax name, out SymbolInfo leftHandBinding, out ITypeSymbol? container) { if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) || name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) || name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type)) { leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression); container = _context.SemanticModel.GetSpeculativeTypeInfo( name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type; return true; } leftHandBinding = default; container = null; return false; } private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression) { if (originalExpression == null) return default; // In case of 'await x$$', we want to move to 'x' to get it's members. // To run GetSymbolInfo, we also need to get rid of parenthesis. var expression = originalExpression is AwaitExpressionSyntax awaitExpression ? awaitExpression.Expression.WalkDownParentheses() : originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); // Check for the Color Color case. if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken)) { var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace); var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false); result = new RecommendedSymbols( result.NamedSymbols.Concat(typeMembers.NamedSymbols), result.UnnamedSymbols); } return result; } private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression) { var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; if (container is IPointerTypeSymbol pointerType) { container = pointerType.PointedAtType; } return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false); } private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression) { // Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly, // a member access off of a conditional receiver of nullable type binds to the unwrapped nullable // type. This is not exposed via the binding information for the LHS, so repeat this work here. var expression = originalExpression.WalkDownParentheses(); var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken); var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type; // If the thing on the left is a type, namespace, or alias, we shouldn't show anything in // IntelliSense. if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias)) return default; return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true); } private RecommendedSymbols GetSymbolsOffOfBoundExpression( ExpressionSyntax originalExpression, ExpressionSyntax expression, SymbolInfo leftHandBinding, ITypeSymbol? containerType, bool unwrapNullable) { var abstractsOnly = false; var excludeInstance = false; var excludeStatic = true; ISymbol? containerSymbol = containerType; var symbol = leftHandBinding.GetAnySymbol(); if (symbol != null) { // If the thing on the left is a lambda expression, we shouldn't show anything. if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction }) return default; var originalExpressionKind = originalExpression.Kind(); // If the thing on the left is a type, namespace or alias and the original // expression was parenthesized, we shouldn't show anything in IntelliSense. if (originalExpressionKind is SyntaxKind.ParenthesizedExpression && symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias) { return default; } // If the thing on the left is a method name identifier, we shouldn't show anything. if (symbol.Kind is SymbolKind.Method && originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName) { return default; } // If the thing on the left is an event that can't be used as a field, we shouldn't show anything if (symbol is IEventSymbol ev && !_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev)) { return default; } if (symbol is IAliasSymbol alias) symbol = alias.Target; if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter) { // For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around. // We only want statics and not instance members. excludeInstance = true; excludeStatic = false; abstractsOnly = symbol.Kind == SymbolKind.TypeParameter; containerSymbol = symbol; } // Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to // lookup symbols off of as we have a lot of special logic for determining member symbols of lambda // parameters. // // If it is a this/base parameter and we're in a static context, we shouldn't show anything if (symbol is IParameterSymbol parameter) { if (parameter.IsThis && expression.IsInStaticContext()) return default; containerSymbol = symbol; } } else if (containerType != null) { // Otherwise, if it wasn't a symbol on the left, but it was something that had a type, // then include instance members for it. excludeStatic = true; } if (containerSymbol == null) return default; Debug.Assert(!excludeInstance || !excludeStatic); Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance)); // nameof(X.| // Show static and instance members. if (_context.IsNameOfContext) { excludeInstance = false; excludeStatic = false; } var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType); var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable); // If we're showing instance members, don't include nested types var namedSymbols = excludeStatic ? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol)) : (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols); // if we're dotting off an instance, then add potential operators/indexers/conversions that may be // applicable to it as well. var unnamedSymbols = _context.IsNameOfContext || excludeInstance ? default : GetUnnamedSymbols(originalExpression); return new RecommendedSymbols(namedSymbols, unnamedSymbols); } private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression) { var semanticModel = _context.SemanticModel; var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression); if (container == null) return ImmutableArray<ISymbol>.Empty; // In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not // `int?`. However, we want to think of the constructed type as that's the type of the overall expression // that will be casted. if (originalExpression.GetRootConditionalAccessExpression() != null) container = TryMakeNullable(semanticModel.Compilation, container); using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols); AddIndexers(container, symbols); AddOperators(container, symbols); AddConversions(container, symbols); return symbols.ToImmutable(); } private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression) { return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container) ? container : semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type; } private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols) { var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken); if (containingType == null) return; foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType)) { if (member.IsIndexer) symbols.Add(member); } } } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Rename.ConflictEngine; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Rename { [ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared] internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpRenameConflictLanguageService() { } #region "Annotation" public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters) { var renameAnnotationRewriter = new RenameRewriter(parameters); return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!; } private class RenameRewriter : CSharpSyntaxRewriter { private readonly DocumentId _documentId; private readonly RenameAnnotation _renameRenamableSymbolDeclaration; private readonly Solution _solution; private readonly string _replacementText; private readonly string _originalText; private readonly ICollection<string> _possibleNameConflicts; private readonly Dictionary<TextSpan, RenameLocation> _renameLocations; private readonly ISet<TextSpan> _conflictLocations; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; private readonly ISymbol _renamedSymbol; private readonly IAliasSymbol? _aliasSymbol; private readonly Location? _renamableDeclarationLocation; private readonly RenamedSpansTracker _renameSpansTracker; private readonly bool _isVerbatim; private readonly bool _replacementTextValid; private readonly ISimplificationService _simplificationService; private readonly ISemanticFactsService _semanticFactsService; private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new(); private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new(); private readonly AnnotationTable<RenameAnnotation> _renameAnnotations; /// <summary> /// Flag indicating if we should perform a rename inside string literals. /// </summary> private readonly bool _isRenamingInStrings; /// <summary> /// Flag indicating if we should perform a rename inside comment trivia. /// </summary> private readonly bool _isRenamingInComments; /// <summary> /// A map from spans of tokens needing rename within strings or comments to an optional /// set of specific sub-spans within the token span that /// have <see cref="_originalText"/> matches and should be renamed. /// If this sorted set is null, it indicates that sub-spans to rename within the token span /// are not available, and a regex match should be performed to rename /// all <see cref="_originalText"/> matches within the span. /// </summary> private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans; public bool AnnotateForComplexification { get { return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans; } } private int _skipRenameForComplexification; private bool _isProcessingComplexifiedSpans; private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans; private SemanticModel? _speculativeModel; private int _isProcessingTrivia; private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan) { newSpan = new TextSpan(oldSpan.Start, newSpan.Length); if (!_isProcessingComplexifiedSpans) { _renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan); } else { RoslynDebug.Assert(_modifiedSubSpans != null); _modifiedSubSpans.Add((oldSpan, newSpan)); } } public RenameRewriter(RenameRewriterParameters parameters) : base(visitIntoStructuredTrivia: true) { _documentId = parameters.Document.Id; _renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation; _solution = parameters.OriginalSolution; _replacementText = parameters.ReplacementText; _originalText = parameters.OriginalText; _possibleNameConflicts = parameters.PossibleNameConflicts; _renameLocations = parameters.RenameLocations; _conflictLocations = parameters.ConflictLocationSpans; _cancellationToken = parameters.CancellationToken; _semanticModel = parameters.SemanticModel; _renamedSymbol = parameters.RenameSymbol; _replacementTextValid = parameters.ReplacementTextValid; _renameSpansTracker = parameters.RenameSpansTracker; _isRenamingInStrings = parameters.OptionSet.RenameInStrings; _isRenamingInComments = parameters.OptionSet.RenameInComments; _stringAndCommentTextSpans = parameters.StringAndCommentTextSpans; _renameAnnotations = parameters.RenameAnnotations; _aliasSymbol = _renamedSymbol as IAliasSymbol; _renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree); _isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal); _simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>(); _semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>(); } public override SyntaxNode? Visit(SyntaxNode? node) { if (node == null) { return node; } var isInConflictLambdaBody = false; var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax); if (lambdas.Count() != 0) { foreach (var lambda in lambdas) { if (_conflictLocations.Any(cf => cf.Contains(lambda.Span))) { isInConflictLambdaBody = true; break; } } } var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody); SyntaxNode result; // in case the current node was identified as being a complexification target of // a previous node, we'll handle it accordingly. if (shouldComplexifyNode) { _skipRenameForComplexification++; result = base.Visit(node)!; _skipRenameForComplexification--; result = Complexify(node, result); } else { result = base.Visit(node)!; } return result; } private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody) { return !isInConflictLambdaBody && _skipRenameForComplexification == 0 && !_isProcessingComplexifiedSpans && _conflictLocations.Contains(node.Span) && (node is AttributeSyntax || node is AttributeArgumentSyntax || node is ConstructorInitializerSyntax || node is ExpressionSyntax || node is FieldDeclarationSyntax || node is StatementSyntax || node is CrefSyntax || node is XmlNameAttributeSyntax || node is TypeConstraintSyntax || node is BaseTypeSyntax); } public override SyntaxToken VisitToken(SyntaxToken token) { var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span); _isProcessingTrivia += shouldCheckTrivia ? 1 : 0; var newToken = base.VisitToken(token); _isProcessingTrivia -= shouldCheckTrivia ? 1 : 0; // Handle Alias annotations newToken = UpdateAliasAnnotation(newToken); // Rename matches in strings and comments newToken = RenameWithinToken(token, newToken); // We don't want to annotate XmlName with RenameActionAnnotation if (newToken.Parent.IsKind(SyntaxKind.XmlName)) { return newToken; } var isRenameLocation = IsRenameLocation(token); // if this is a reference location, or the identifier token's name could possibly // be a conflict, we need to process this token var isOldText = token.ValueText == _originalText; var tokenNeedsConflictCheck = isRenameLocation || token.ValueText == _replacementText || isOldText || _possibleNameConflicts.Contains(token.ValueText) || IsPossiblyDestructorConflict(token) || IsPropertyAccessorNameConflict(token); if (tokenNeedsConflictCheck) { newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken); if (!_isProcessingComplexifiedSpans) { _invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>()); } } return newToken; } private bool IsPropertyAccessorNameConflict(SyntaxToken token) => IsGetPropertyAccessorNameConflict(token) || IsSetPropertyAccessorNameConflict(token) || IsInitPropertyAccessorNameConflict(token); private bool IsGetPropertyAccessorNameConflict(SyntaxToken token) => token.IsKind(SyntaxKind.GetKeyword) && IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax); private bool IsSetPropertyAccessorNameConflict(SyntaxToken token) => token.IsKind(SyntaxKind.SetKeyword) && IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax); private bool IsInitPropertyAccessorNameConflict(SyntaxToken token) => token.IsKind(SyntaxKind.InitKeyword) // using "set" here is intentional. The compiler generates set_PropName for both set and init accessors. && IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax); private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor) => accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration && _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal); private bool IsPossiblyDestructorConflict(SyntaxToken token) { return _replacementText == "Finalize" && token.IsKind(SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.DestructorDeclaration); } private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode) { _isProcessingComplexifiedSpans = true; _modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>(); var annotation = new SyntaxAnnotation(); newNode = newNode.WithAdditionalAnnotations(annotation); var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode); newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First(); _speculativeModel = GetSemanticModelForNode(newNode, _semanticModel); RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?"); var oldSpan = originalNode.Span; var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0; newNode = _simplificationService.Expand(newNode, _speculativeModel, annotationForReplacedAliasIdentifier: null, expandInsideNode: null, expandParameter: expandParameter, cancellationToken: _cancellationToken); speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode); newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First(); _speculativeModel = GetSemanticModelForNode(newNode, _semanticModel); newNode = base.Visit(newNode)!; var newSpan = newNode.Span; newNode = newNode.WithoutAnnotations(annotation); newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan }); _renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans); _modifiedSubSpans = null; _isProcessingComplexifiedSpans = false; _speculativeModel = null; return newNode; } private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText) { try { if (_isProcessingComplexifiedSpans) { // Rename Token if (isRenameLocation) { var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault(); if (annotation != null) { newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix); AddModifiedSpan(annotation.OriginalSpan, newToken.Span); } else { newToken = RenameToken(token, newToken, prefix: null, suffix: null); } } return newToken; } var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken); string? suffix = null; var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor ? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1) : null; if (symbols.Length == 1) { var symbol = symbols[0]; if (symbol.IsConstructor()) { symbol = symbol.ContainingSymbol; } var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false); symbol = sourceDefinition ?? symbol; if (symbol is INamedTypeSymbol namedTypeSymbol) { if (namedTypeSymbol.IsImplicitlyDeclared && namedTypeSymbol.IsDelegateType() && namedTypeSymbol.AssociatedSymbol != null) { suffix = "EventHandler"; } } // This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace // conflict is not shown for the namespace so we are tracking this token if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword)) { return newToken; } } // Rename Token if (isRenameLocation && !this.AnnotateForComplexification) { var oldSpan = token.Span; newToken = RenameToken(token, newToken, prefix, suffix); AddModifiedSpan(oldSpan, newToken.Span); } var renameDeclarationLocations = await ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false); var isNamespaceDeclarationReference = false; if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword)) { isNamespaceDeclarationReference = true; } var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken); var renameAnnotation = new RenameActionAnnotation( token.Span, isRenameLocation, prefix, suffix, renameDeclarationLocations: renameDeclarationLocations, isOriginalTextLocation: isOldText, isNamespaceDeclarationReference: isNamespaceDeclarationReference, isInvocationExpression: false, isMemberGroupReference: isMemberGroupReference); newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span }); _annotatedIdentifierTokens.Add(token); if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation()) { newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration); } return newToken; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression) { var identifierToken = default(SyntaxToken); var expressionOfInvocation = invocationExpression.Expression; while (expressionOfInvocation != null) { switch (expressionOfInvocation.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier; break; case SyntaxKind.SimpleMemberAccessExpression: identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier; break; case SyntaxKind.QualifiedName: identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier; break; case SyntaxKind.AliasQualifiedName: identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier; break; case SyntaxKind.ParenthesizedExpression: expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression; continue; } break; } if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken)) { var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken); IEnumerable<ISymbol> symbols; if (symbolInfo.Symbol == null) { return null; } else { symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol); } var renameDeclarationLocations = ConflictResolver.CreateDeclarationLocationAnnotationsAsync( _solution, symbols, _cancellationToken) .WaitAndGetResult_CanCallOnBackground(_cancellationToken); var renameAnnotation = new RenameActionAnnotation( identifierToken.Span, isRenameLocation: false, prefix: null, suffix: null, renameDeclarationLocations: renameDeclarationLocations, isOriginalTextLocation: false, isNamespaceDeclarationReference: false, isInvocationExpression: true, isMemberGroupReference: false); return renameAnnotation; } return null; } public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) { var result = base.VisitInvocationExpression(node); RoslynDebug.AssertNotNull(result); if (_invocationExpressionsNeedingConflictChecks.Contains(node)) { var renameAnnotation = GetAnnotationForInvocationExpression(node); if (renameAnnotation != null) { result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation); } } return result; } private bool IsRenameLocation(SyntaxToken token) { if (!_isProcessingComplexifiedSpans) { return _renameLocations.ContainsKey(token.Span); } else { RoslynDebug.Assert(_speculativeModel != null); if (token.HasAnnotations(AliasAnnotation.Kind)) { return false; } if (token.HasAnnotations(RenameAnnotation.Kind)) { return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation; } if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName)) { var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol; if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable && (Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey()))) { return true; } } return false; } } private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken) { if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind)) { newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText); } return newToken; } private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix) { var parent = oldToken.Parent!; var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText; var oldIdentifier = newToken.ValueText; var isAttributeName = SyntaxFacts.IsAttributeName(parent); if (isAttributeName) { if (oldIdentifier != _renamedSymbol.Name) { if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix)) { currentNewIdentifier = withoutSuffix; } } } else { if (!string.IsNullOrEmpty(prefix)) { currentNewIdentifier = prefix + currentNewIdentifier; } if (!string.IsNullOrEmpty(suffix)) { currentNewIdentifier += suffix; } } // determine the canonical identifier name (unescaped, no unicode escaping, ...) var valueText = currentNewIdentifier; var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier); if (kind != SyntaxKind.None) { valueText = SyntaxFacts.GetText(kind); } else { var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier); if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName)) { valueText = identifierName.Identifier.ValueText; } } // TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well. // <param name="\u... is invalid. // if it's an attribute name we don't mess with the escaping because it might change overload resolution newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier()) ? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia)) : newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia)); if (_replacementTextValid) { if (newToken.IsVerbatimIdentifier()) { // a reference location should always be tried to be unescaped, whether it was escaped before rename // or the replacement itself is escaped. newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation); } else { newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent); } } return newToken; } private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral) { var originalString = newToken.ToString(); var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace); if (replacedString != originalString) { var oldSpan = oldToken.Span; newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia); AddModifiedSpan(oldSpan, newToken.Span); return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan })); } return newToken; } private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList) { return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) => { if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment()) { return RenameInCommentTrivia(newTrivia); } return newTrivia; }); } private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia) { var originalString = trivia.ToString(); var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText); if (replacedString != originalString) { var oldSpan = trivia.Span; var newTrivia = SyntaxFactory.Comment(replacedString); AddModifiedSpan(oldSpan, newTrivia.Span); return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan })); } return trivia; } private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken) { ImmutableSortedSet<TextSpan>? subSpansToReplace = null; if (_isProcessingComplexifiedSpans || (_isProcessingTrivia == 0 && !_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace))) { return newToken; } if (_isRenamingInStrings || subSpansToReplace?.Count > 0) { if (newToken.IsKind(SyntaxKind.StringLiteralToken)) { newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal); } else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken)) { newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) => SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia)); } } if (_isRenamingInComments) { if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken)) { newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral); } else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText) { var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia); newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span })); AddModifiedSpan(oldToken.Span, newToken.Span); } if (newToken.HasLeadingTrivia) { var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia); if (updatedToken != oldToken) { newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia); } } if (newToken.HasTrailingTrivia) { var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia); if (updatedToken != oldToken) { newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia); } } } return newToken; } } #endregion #region "Declaration Conflicts" public override bool LocalVariableConflict( SyntaxToken token, IEnumerable<ISymbol> newReferencedSymbols) { if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) && token.Parent.IsParentKind(SyntaxKind.InvocationExpression) && token.GetPreviousToken().Kind() != SyntaxKind.DotToken && token.GetNextToken().Kind() != SyntaxKind.DotToken) { var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (enclosingMemberDeclaration != null) { var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText]; if (locals.Length > 0) { // This unqualified invocation name matches the name of an existing local // or parameter. Report a conflict if the matching local/parameter is not // a delegate type. var relevantLocals = newReferencedSymbols .Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText); if (relevantLocals.Count() != 1) { return true; } var matchingLocal = relevantLocals.Single(); var invocationTargetsLocalOfDelegateType = (matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) || (matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType()); return !invocationTargetsLocalOfDelegateType; } } } return false; } public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync( string replacementText, ISymbol renamedSymbol, ISymbol renameSymbol, IEnumerable<ISymbol> referencedSymbols, Solution baseSolution, Solution newSolution, IDictionary<Location, Location> reverseMappedLocations, CancellationToken cancellationToken) { try { var conflicts = ArrayBuilder<Location>.GetInstance(); // If we're renaming a named type, we can conflict with members w/ our same name. Note: // this doesn't apply to enums. if (renamedSymbol.Kind == SymbolKind.NamedType && ((INamedTypeSymbol)renamedSymbol).TypeKind != TypeKind.Enum) { var namedType = (INamedTypeSymbol)renamedSymbol; AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations); } // If we're contained in a named type (we may be a named type ourself!) then we have a // conflict. NOTE(cyrusn): This does not apply to enums. if (renamedSymbol.ContainingSymbol is INamedTypeSymbol && renamedSymbol.ContainingType.Name == renamedSymbol.Name && renamedSymbol.ContainingType.TypeKind != TypeKind.Enum) { AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(renamedSymbol.ContainingType), reverseMappedLocations); } if (renamedSymbol.Kind == SymbolKind.Parameter || renamedSymbol.Kind == SymbolKind.Local || renamedSymbol.Kind == SymbolKind.RangeVariable) { var token = renamedSymbol.Locations.Single().FindToken(cancellationToken); var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); var visitor = new LocalConflictVisitor(token); visitor.Visit(memberDeclaration); conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()])); // If this is a parameter symbol for a partial method definition, be sure we visited // the implementation part's body. if (renamedSymbol is IParameterSymbol renamedParameterSymbol && renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.PartialImplementationPart != null) { var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal]; token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken); memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); visitor = new LocalConflictVisitor(token); visitor.Visit(memberDeclaration); conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()])); } } else if (renamedSymbol.Kind == SymbolKind.Label) { var token = renamedSymbol.Locations.Single().FindToken(cancellationToken); var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); var visitor = new LabelConflictVisitor(token); visitor.Visit(memberDeclaration); conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()])); } else if (renamedSymbol.Kind == SymbolKind.Method) { conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t])); // we allow renaming overrides of VB property accessors with parameters in C#. // VB has a special rule that properties are not allowed to have the same name as any of the parameters. // Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#. var properties = new List<ISymbol>(); foreach (var referencedSymbol in referencedSymbols) { var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync( referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false); if (property != null) { properties.Add(property); } } AddConflictingParametersOfProperties( properties.Distinct(), replacementText, conflicts); } else if (renamedSymbol.Kind == SymbolKind.Alias) { // in C# there can only be one using with the same alias name in the same block (top of file of namespace). // It's ok to redefine the alias in different blocks. var location = renamedSymbol.Locations.Single(); var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false); var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!; var namespaceDecl = token.Parent.GetAncestorsOrThis(n => n.Kind() == SyntaxKind.NamespaceDeclaration).FirstOrDefault(); SyntaxList<UsingDirectiveSyntax> usings; if (namespaceDecl != null) { usings = ((NamespaceDeclarationSyntax)namespaceDecl).Usings; } else { var compilationUnit = (CompilationUnitSyntax)token.Parent.GetAncestorsOrThis(n => n.Kind() == SyntaxKind.CompilationUnit).Single(); usings = compilationUnit.Usings; } foreach (var usingDirective in usings) { if (usingDirective.Alias != null && usingDirective != currentUsing) { if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText) { conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]); } } } } else if (renamedSymbol.Kind == SymbolKind.TypeParameter) { foreach (var location in renamedSymbol.Locations) { var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false); var currentTypeParameter = token.Parent!; foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters) { if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText) { conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]); } } } } // if the renamed symbol is a type member, it's name should not conflict with a type parameter if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol)) { var conflictingLocations = renamedSymbol.ContainingType.TypeParameters .Where(t => t.Name == renamedSymbol.Name) .SelectMany(t => t.Locations); foreach (var location in conflictingLocations) { var typeParameterToken = location.FindToken(cancellationToken); conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]); } } return conflicts.ToImmutableAndFree(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) { try { if (symbol.IsPropertyAccessor()) { var property = ((IMethodSymbol)symbol).AssociatedSymbol!; return property.Language == LanguageNames.VisualBasic ? property : null; } if (symbol.IsOverride && symbol.GetOverriddenMember() != null) { var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false); if (originalSourceSymbol != null) { return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false); } } return null; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static void AddSymbolSourceSpans( ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols, IDictionary<Location, Location> reverseMappedLocations) { foreach (var symbol in symbols) { foreach (var location in symbol.Locations) { // reverseMappedLocations may not contain the location if the location's token // does not contain the text of it's name (e.g. the getter of "int X { get; }" // does not contain the text "get_X" so conflicting renames to "get_X" will not // have added the getter to reverseMappedLocations). if (location.IsInSource && reverseMappedLocations.ContainsKey(location)) { conflicts.Add(reverseMappedLocations[location]); } } } } public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync( ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken) { // Handle renaming of symbols used for foreach var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property && string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0; implicitReferencesMightConflict = implicitReferencesMightConflict || (renameSymbol.Kind == SymbolKind.Method && (string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0)); // TODO: handle Dispose for using statement and Add methods for collection initializers. if (implicitReferencesMightConflict) { if (renamedSymbol.Name != renameSymbol.Name) { foreach (var implicitReferenceLocation in implicitReferenceLocations) { var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync( implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false); switch (token.Kind()) { case SyntaxKind.ForEachKeyword: return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation()); case SyntaxKind.AwaitKeyword: return ImmutableArray.Create(token.GetLocation()); } if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft)) { return ImmutableArray.Create(deconstructionLeft.GetLocation()); } } } } return ImmutableArray<Location>.Empty; } public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts( ISymbol renamedSymbol, SemanticModel semanticModel, Location originalDeclarationLocation, int newDeclarationLocationStartingPosition, CancellationToken cancellationToken) { // TODO: support other implicitly used methods like dispose if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0) { // TODO: partial methods currently only show the location where the rename happens as a conflict. // Consider showing both locations as a conflict. var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault(); if (baseType != null) { var implicitSymbols = semanticModel.LookupSymbols( newDeclarationLocationStartingPosition, baseType, renamedSymbol.Name) .Where(sym => !sym.Equals(renamedSymbol)); foreach (var symbol in implicitSymbols) { if (symbol.GetAllTypeArguments().Length != 0) { continue; } if (symbol.Kind == SymbolKind.Method) { var method = (IMethodSymbol)symbol; if (symbol.Name == "MoveNext") { if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean) { return ImmutableArray.Create(originalDeclarationLocation); } } else if (symbol.Name == "GetEnumerator") { // we are a bit pessimistic here. // To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach if (!method.ReturnsVoid && !method.Parameters.Any()) { return ImmutableArray.Create(originalDeclarationLocation); } } } else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current") { var property = (IPropertySymbol)symbol; if (!property.Parameters.Any() && !property.IsWriteOnly) { return ImmutableArray.Create(originalDeclarationLocation); } } } } } return ImmutableArray<Location>.Empty; } #endregion public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts) { if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9) { var conflict = replacementText.Substring(0, replacementText.Length - 9); if (!possibleNameConflicts.Contains(conflict)) { possibleNameConflicts.Add(conflict); } } if (symbol.Kind == SymbolKind.Property) { foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText }) { if (!possibleNameConflicts.Contains(conflict)) { possibleNameConflicts.Add(conflict); } } } // in C# we also need to add the valueText because it can be different from the text in source // e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for // v\u0061r and var or similar. var valueText = replacementText; var kind = SyntaxFacts.GetKeywordKind(replacementText); if (kind != SyntaxKind.None) { valueText = SyntaxFacts.GetText(kind); } else { var name = SyntaxFactory.ParseName(replacementText); if (name.Kind() == SyntaxKind.IdentifierName) { valueText = ((IdentifierNameSyntax)name).Identifier.ValueText; } } // this also covers the case of an escaped replacementText if (valueText != replacementText) { possibleNameConflicts.Add(valueText); } } /// <summary> /// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on. /// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing /// statement of this lambda. /// </summary> /// <param name="token">The token to get the complexification target for.</param> /// <returns></returns> public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token) => GetExpansionTarget(token); private static SyntaxNode? GetExpansionTarget(SyntaxToken token) { // get the directly enclosing statement var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault(); // System.Func<int, int> myFunc = arg => X; var possibleLambdaExpression = enclosingStatement == null ? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault() : null; if (possibleLambdaExpression != null) { var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression); if (lambdaExpression.Body is ExpressionSyntax) { return lambdaExpression.Body; } } // int M() => X; var possibleArrowExpressionClause = enclosingStatement == null ? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault() : null; if (possibleArrowExpressionClause != null) { return possibleArrowExpressionClause.Expression; } var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault(); if (enclosingNameMemberCrefOrnull != null) { if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax) { enclosingNameMemberCrefOrnull = null; } } var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault(); if (enclosingXmlNameAttr != null) { return null; } var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault(); if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax) { return enclosingInitializer.Value; } var attributeSyntax = token.GetAncestor<AttributeSyntax>(); if (attributeSyntax != null) { return attributeSyntax; } // there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault(); } #region "Helper Methods" public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService) { // Identifiers we never consider valid to rename to. switch (replacementText) { case "var": case "dynamic": case "unmanaged": case "notnull": return false; } var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal) ? replacementText : "@" + replacementText; // Make sure we got an identifier. if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier)) { // We still don't have an identifier, so let's fail return false; } return true; } /// <summary> /// Gets the semantic model for the given node. /// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel. /// Otherwise, returns a speculative model. /// The assumption for the later case is that span start position of the given node in it's syntax tree is same as /// the span start of the original node in the original syntax tree. /// </summary> public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel) { if (node.SyntaxTree == originalSemanticModel.SyntaxTree) { // This is possible if the previous rename phase didn't rewrite any nodes in this tree. return originalSemanticModel; } var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault(); if (nodeToSpeculate == null) { if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember)) { nodeToSpeculate = nameMember.Name; } else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref)) { nodeToSpeculate = qualifiedCref.Container; } else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint)) { nodeToSpeculate = typeConstraint.Type; } else if (node is BaseTypeSyntax baseType) { nodeToSpeculate = baseType.Type; } else { return null; } } var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); var position = nodeToSpeculate.SpanStart; return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext); } #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.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Simplification; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Rename.ConflictEngine; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Rename { [ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared] internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpRenameConflictLanguageService() { } #region "Annotation" public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters) { var renameAnnotationRewriter = new RenameRewriter(parameters); return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!; } private class RenameRewriter : CSharpSyntaxRewriter { private readonly DocumentId _documentId; private readonly RenameAnnotation _renameRenamableSymbolDeclaration; private readonly Solution _solution; private readonly string _replacementText; private readonly string _originalText; private readonly ICollection<string> _possibleNameConflicts; private readonly Dictionary<TextSpan, RenameLocation> _renameLocations; private readonly ISet<TextSpan> _conflictLocations; private readonly SemanticModel _semanticModel; private readonly CancellationToken _cancellationToken; private readonly ISymbol _renamedSymbol; private readonly IAliasSymbol? _aliasSymbol; private readonly Location? _renamableDeclarationLocation; private readonly RenamedSpansTracker _renameSpansTracker; private readonly bool _isVerbatim; private readonly bool _replacementTextValid; private readonly ISimplificationService _simplificationService; private readonly ISemanticFactsService _semanticFactsService; private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new(); private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new(); private readonly AnnotationTable<RenameAnnotation> _renameAnnotations; /// <summary> /// Flag indicating if we should perform a rename inside string literals. /// </summary> private readonly bool _isRenamingInStrings; /// <summary> /// Flag indicating if we should perform a rename inside comment trivia. /// </summary> private readonly bool _isRenamingInComments; /// <summary> /// A map from spans of tokens needing rename within strings or comments to an optional /// set of specific sub-spans within the token span that /// have <see cref="_originalText"/> matches and should be renamed. /// If this sorted set is null, it indicates that sub-spans to rename within the token span /// are not available, and a regex match should be performed to rename /// all <see cref="_originalText"/> matches within the span. /// </summary> private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans; public bool AnnotateForComplexification { get { return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans; } } private int _skipRenameForComplexification; private bool _isProcessingComplexifiedSpans; private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans; private SemanticModel? _speculativeModel; private int _isProcessingTrivia; private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan) { newSpan = new TextSpan(oldSpan.Start, newSpan.Length); if (!_isProcessingComplexifiedSpans) { _renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan); } else { RoslynDebug.Assert(_modifiedSubSpans != null); _modifiedSubSpans.Add((oldSpan, newSpan)); } } public RenameRewriter(RenameRewriterParameters parameters) : base(visitIntoStructuredTrivia: true) { _documentId = parameters.Document.Id; _renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation; _solution = parameters.OriginalSolution; _replacementText = parameters.ReplacementText; _originalText = parameters.OriginalText; _possibleNameConflicts = parameters.PossibleNameConflicts; _renameLocations = parameters.RenameLocations; _conflictLocations = parameters.ConflictLocationSpans; _cancellationToken = parameters.CancellationToken; _semanticModel = parameters.SemanticModel; _renamedSymbol = parameters.RenameSymbol; _replacementTextValid = parameters.ReplacementTextValid; _renameSpansTracker = parameters.RenameSpansTracker; _isRenamingInStrings = parameters.OptionSet.RenameInStrings; _isRenamingInComments = parameters.OptionSet.RenameInComments; _stringAndCommentTextSpans = parameters.StringAndCommentTextSpans; _renameAnnotations = parameters.RenameAnnotations; _aliasSymbol = _renamedSymbol as IAliasSymbol; _renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree); _isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal); _simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>(); _semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>(); } public override SyntaxNode? Visit(SyntaxNode? node) { if (node == null) { return node; } var isInConflictLambdaBody = false; var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax); if (lambdas.Count() != 0) { foreach (var lambda in lambdas) { if (_conflictLocations.Any(cf => cf.Contains(lambda.Span))) { isInConflictLambdaBody = true; break; } } } var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody); SyntaxNode result; // in case the current node was identified as being a complexification target of // a previous node, we'll handle it accordingly. if (shouldComplexifyNode) { _skipRenameForComplexification++; result = base.Visit(node)!; _skipRenameForComplexification--; result = Complexify(node, result); } else { result = base.Visit(node)!; } return result; } private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody) { return !isInConflictLambdaBody && _skipRenameForComplexification == 0 && !_isProcessingComplexifiedSpans && _conflictLocations.Contains(node.Span) && (node is AttributeSyntax || node is AttributeArgumentSyntax || node is ConstructorInitializerSyntax || node is ExpressionSyntax || node is FieldDeclarationSyntax || node is StatementSyntax || node is CrefSyntax || node is XmlNameAttributeSyntax || node is TypeConstraintSyntax || node is BaseTypeSyntax); } public override SyntaxToken VisitToken(SyntaxToken token) { var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span); _isProcessingTrivia += shouldCheckTrivia ? 1 : 0; var newToken = base.VisitToken(token); _isProcessingTrivia -= shouldCheckTrivia ? 1 : 0; // Handle Alias annotations newToken = UpdateAliasAnnotation(newToken); // Rename matches in strings and comments newToken = RenameWithinToken(token, newToken); // We don't want to annotate XmlName with RenameActionAnnotation if (newToken.Parent.IsKind(SyntaxKind.XmlName)) { return newToken; } var isRenameLocation = IsRenameLocation(token); // if this is a reference location, or the identifier token's name could possibly // be a conflict, we need to process this token var isOldText = token.ValueText == _originalText; var tokenNeedsConflictCheck = isRenameLocation || token.ValueText == _replacementText || isOldText || _possibleNameConflicts.Contains(token.ValueText) || IsPossiblyDestructorConflict(token) || IsPropertyAccessorNameConflict(token); if (tokenNeedsConflictCheck) { newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken); if (!_isProcessingComplexifiedSpans) { _invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>()); } } return newToken; } private bool IsPropertyAccessorNameConflict(SyntaxToken token) => IsGetPropertyAccessorNameConflict(token) || IsSetPropertyAccessorNameConflict(token) || IsInitPropertyAccessorNameConflict(token); private bool IsGetPropertyAccessorNameConflict(SyntaxToken token) => token.IsKind(SyntaxKind.GetKeyword) && IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax); private bool IsSetPropertyAccessorNameConflict(SyntaxToken token) => token.IsKind(SyntaxKind.SetKeyword) && IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax); private bool IsInitPropertyAccessorNameConflict(SyntaxToken token) => token.IsKind(SyntaxKind.InitKeyword) // using "set" here is intentional. The compiler generates set_PropName for both set and init accessors. && IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax); private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor) => accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration && _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal); private bool IsPossiblyDestructorConflict(SyntaxToken token) { return _replacementText == "Finalize" && token.IsKind(SyntaxKind.IdentifierToken) && token.Parent.IsKind(SyntaxKind.DestructorDeclaration); } private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode) { _isProcessingComplexifiedSpans = true; _modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>(); var annotation = new SyntaxAnnotation(); newNode = newNode.WithAdditionalAnnotations(annotation); var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode); newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First(); _speculativeModel = GetSemanticModelForNode(newNode, _semanticModel); RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?"); var oldSpan = originalNode.Span; var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0; newNode = _simplificationService.Expand(newNode, _speculativeModel, annotationForReplacedAliasIdentifier: null, expandInsideNode: null, expandParameter: expandParameter, cancellationToken: _cancellationToken); speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode); newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First(); _speculativeModel = GetSemanticModelForNode(newNode, _semanticModel); newNode = base.Visit(newNode)!; var newSpan = newNode.Span; newNode = newNode.WithoutAnnotations(annotation); newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan }); _renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans); _modifiedSubSpans = null; _isProcessingComplexifiedSpans = false; _speculativeModel = null; return newNode; } private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText) { try { if (_isProcessingComplexifiedSpans) { // Rename Token if (isRenameLocation) { var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault(); if (annotation != null) { newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix); AddModifiedSpan(annotation.OriginalSpan, newToken.Span); } else { newToken = RenameToken(token, newToken, prefix: null, suffix: null); } } return newToken; } var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken); string? suffix = null; var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor ? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1) : null; if (symbols.Length == 1) { var symbol = symbols[0]; if (symbol.IsConstructor()) { symbol = symbol.ContainingSymbol; } var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false); symbol = sourceDefinition ?? symbol; if (symbol is INamedTypeSymbol namedTypeSymbol) { if (namedTypeSymbol.IsImplicitlyDeclared && namedTypeSymbol.IsDelegateType() && namedTypeSymbol.AssociatedSymbol != null) { suffix = "EventHandler"; } } // This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace // conflict is not shown for the namespace so we are tracking this token if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword)) { return newToken; } } // Rename Token if (isRenameLocation && !this.AnnotateForComplexification) { var oldSpan = token.Span; newToken = RenameToken(token, newToken, prefix, suffix); AddModifiedSpan(oldSpan, newToken.Span); } var renameDeclarationLocations = await ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false); var isNamespaceDeclarationReference = false; if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword)) { isNamespaceDeclarationReference = true; } var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken); var renameAnnotation = new RenameActionAnnotation( token.Span, isRenameLocation, prefix, suffix, renameDeclarationLocations: renameDeclarationLocations, isOriginalTextLocation: isOldText, isNamespaceDeclarationReference: isNamespaceDeclarationReference, isInvocationExpression: false, isMemberGroupReference: isMemberGroupReference); newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span }); _annotatedIdentifierTokens.Add(token); if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation()) { newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration); } return newToken; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression) { var identifierToken = default(SyntaxToken); var expressionOfInvocation = invocationExpression.Expression; while (expressionOfInvocation != null) { switch (expressionOfInvocation.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier; break; case SyntaxKind.SimpleMemberAccessExpression: identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier; break; case SyntaxKind.QualifiedName: identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier; break; case SyntaxKind.AliasQualifiedName: identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier; break; case SyntaxKind.ParenthesizedExpression: expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression; continue; } break; } if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken)) { var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken); IEnumerable<ISymbol> symbols; if (symbolInfo.Symbol == null) { return null; } else { symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol); } var renameDeclarationLocations = ConflictResolver.CreateDeclarationLocationAnnotationsAsync( _solution, symbols, _cancellationToken) .WaitAndGetResult_CanCallOnBackground(_cancellationToken); var renameAnnotation = new RenameActionAnnotation( identifierToken.Span, isRenameLocation: false, prefix: null, suffix: null, renameDeclarationLocations: renameDeclarationLocations, isOriginalTextLocation: false, isNamespaceDeclarationReference: false, isInvocationExpression: true, isMemberGroupReference: false); return renameAnnotation; } return null; } public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node) { var result = base.VisitInvocationExpression(node); RoslynDebug.AssertNotNull(result); if (_invocationExpressionsNeedingConflictChecks.Contains(node)) { var renameAnnotation = GetAnnotationForInvocationExpression(node); if (renameAnnotation != null) { result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation); } } return result; } private bool IsRenameLocation(SyntaxToken token) { if (!_isProcessingComplexifiedSpans) { return _renameLocations.ContainsKey(token.Span); } else { RoslynDebug.Assert(_speculativeModel != null); if (token.HasAnnotations(AliasAnnotation.Kind)) { return false; } if (token.HasAnnotations(RenameAnnotation.Kind)) { return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation; } if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName)) { var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol; if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable && (Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey()))) { return true; } } return false; } } private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken) { if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind)) { newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText); } return newToken; } private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix) { var parent = oldToken.Parent!; var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText; var oldIdentifier = newToken.ValueText; var isAttributeName = SyntaxFacts.IsAttributeName(parent); if (isAttributeName) { if (oldIdentifier != _renamedSymbol.Name) { if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix)) { currentNewIdentifier = withoutSuffix; } } } else { if (!string.IsNullOrEmpty(prefix)) { currentNewIdentifier = prefix + currentNewIdentifier; } if (!string.IsNullOrEmpty(suffix)) { currentNewIdentifier += suffix; } } // determine the canonical identifier name (unescaped, no unicode escaping, ...) var valueText = currentNewIdentifier; var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier); if (kind != SyntaxKind.None) { valueText = SyntaxFacts.GetText(kind); } else { var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier); if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName)) { valueText = identifierName.Identifier.ValueText; } } // TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well. // <param name="\u... is invalid. // if it's an attribute name we don't mess with the escaping because it might change overload resolution newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier()) ? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia)) : newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia)); if (_replacementTextValid) { if (newToken.IsVerbatimIdentifier()) { // a reference location should always be tried to be unescaped, whether it was escaped before rename // or the replacement itself is escaped. newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation); } else { newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent); } } return newToken; } private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral) { var originalString = newToken.ToString(); var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace); if (replacedString != originalString) { var oldSpan = oldToken.Span; newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia); AddModifiedSpan(oldSpan, newToken.Span); return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan })); } return newToken; } private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList) { return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) => { if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment()) { return RenameInCommentTrivia(newTrivia); } return newTrivia; }); } private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia) { var originalString = trivia.ToString(); var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText); if (replacedString != originalString) { var oldSpan = trivia.Span; var newTrivia = SyntaxFactory.Comment(replacedString); AddModifiedSpan(oldSpan, newTrivia.Span); return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan })); } return trivia; } private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken) { ImmutableSortedSet<TextSpan>? subSpansToReplace = null; if (_isProcessingComplexifiedSpans || (_isProcessingTrivia == 0 && !_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace))) { return newToken; } if (_isRenamingInStrings || subSpansToReplace?.Count > 0) { if (newToken.IsKind(SyntaxKind.StringLiteralToken)) { newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal); } else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken)) { newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) => SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia)); } } if (_isRenamingInComments) { if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken)) { newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral); } else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText) { var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia); newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span })); AddModifiedSpan(oldToken.Span, newToken.Span); } if (newToken.HasLeadingTrivia) { var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia); if (updatedToken != oldToken) { newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia); } } if (newToken.HasTrailingTrivia) { var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia); if (updatedToken != oldToken) { newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia); } } } return newToken; } } #endregion #region "Declaration Conflicts" public override bool LocalVariableConflict( SyntaxToken token, IEnumerable<ISymbol> newReferencedSymbols) { if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) && token.Parent.IsParentKind(SyntaxKind.InvocationExpression) && token.GetPreviousToken().Kind() != SyntaxKind.DotToken && token.GetNextToken().Kind() != SyntaxKind.DotToken) { var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (enclosingMemberDeclaration != null) { var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText]; if (locals.Length > 0) { // This unqualified invocation name matches the name of an existing local // or parameter. Report a conflict if the matching local/parameter is not // a delegate type. var relevantLocals = newReferencedSymbols .Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText); if (relevantLocals.Count() != 1) { return true; } var matchingLocal = relevantLocals.Single(); var invocationTargetsLocalOfDelegateType = (matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) || (matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType()); return !invocationTargetsLocalOfDelegateType; } } } return false; } public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync( string replacementText, ISymbol renamedSymbol, ISymbol renameSymbol, IEnumerable<ISymbol> referencedSymbols, Solution baseSolution, Solution newSolution, IDictionary<Location, Location> reverseMappedLocations, CancellationToken cancellationToken) { try { using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts); // If we're renaming a named type, we can conflict with members w/ our same name. Note: // this doesn't apply to enums. if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType) AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations); // If we're contained in a named type (we may be a named type ourself!) then we have a // conflict. NOTE(cyrusn): This does not apply to enums. if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType && containingNamedType.Name == renamedSymbol.Name) { AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(containingNamedType), reverseMappedLocations); } if (renamedSymbol.Kind == SymbolKind.Parameter || renamedSymbol.Kind == SymbolKind.Local || renamedSymbol.Kind == SymbolKind.RangeVariable) { var token = renamedSymbol.Locations.Single().FindToken(cancellationToken); var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); var visitor = new LocalConflictVisitor(token); visitor.Visit(memberDeclaration); conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()])); // If this is a parameter symbol for a partial method definition, be sure we visited // the implementation part's body. if (renamedSymbol is IParameterSymbol renamedParameterSymbol && renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol && methodSymbol.PartialImplementationPart != null) { var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal]; token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken); memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); visitor = new LocalConflictVisitor(token); visitor.Visit(memberDeclaration); conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()])); } } else if (renamedSymbol.Kind == SymbolKind.Label) { var token = renamedSymbol.Locations.Single().FindToken(cancellationToken); var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>(); var visitor = new LabelConflictVisitor(token); visitor.Visit(memberDeclaration); conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()])); } else if (renamedSymbol.Kind == SymbolKind.Method) { conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t])); // we allow renaming overrides of VB property accessors with parameters in C#. // VB has a special rule that properties are not allowed to have the same name as any of the parameters. // Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#. var properties = new List<ISymbol>(); foreach (var referencedSymbol in referencedSymbols) { var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync( referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false); if (property != null) properties.Add(property); } AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts); } else if (renamedSymbol.Kind == SymbolKind.Alias) { // in C# there can only be one using with the same alias name in the same block (top of file of namespace). // It's ok to redefine the alias in different blocks. var location = renamedSymbol.Locations.Single(); var tree = location.SourceTree; Contract.ThrowIfNull(tree); var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false); var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!; var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault(); SyntaxList<UsingDirectiveSyntax> usings; if (namespaceDecl != null) { usings = namespaceDecl.Usings; } else { var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); usings = compilationUnit.Usings; } foreach (var usingDirective in usings) { if (usingDirective.Alias != null && usingDirective != currentUsing) { if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText) conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]); } } } else if (renamedSymbol.Kind == SymbolKind.TypeParameter) { foreach (var location in renamedSymbol.Locations) { var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false); var currentTypeParameter = token.Parent!; foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters) { if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText) conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]); } } } // if the renamed symbol is a type member, it's name should not conflict with a type parameter if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol)) { var conflictingLocations = renamedSymbol.ContainingType.TypeParameters .Where(t => t.Name == renamedSymbol.Name) .SelectMany(t => t.Locations); foreach (var location in conflictingLocations) { var typeParameterToken = location.FindToken(cancellationToken); conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]); } } return conflicts.ToImmutable(); } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) { try { if (symbol.IsPropertyAccessor()) { var property = ((IMethodSymbol)symbol).AssociatedSymbol!; return property.Language == LanguageNames.VisualBasic ? property : null; } if (symbol.IsOverride && symbol.GetOverriddenMember() != null) { var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false); if (originalSourceSymbol != null) { return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false); } } return null; } catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken)) { throw ExceptionUtilities.Unreachable; } } private static void AddSymbolSourceSpans( ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols, IDictionary<Location, Location> reverseMappedLocations) { foreach (var symbol in symbols) { foreach (var location in symbol.Locations) { // reverseMappedLocations may not contain the location if the location's token // does not contain the text of it's name (e.g. the getter of "int X { get; }" // does not contain the text "get_X" so conflicting renames to "get_X" will not // have added the getter to reverseMappedLocations). if (location.IsInSource && reverseMappedLocations.ContainsKey(location)) { conflicts.Add(reverseMappedLocations[location]); } } } } public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync( ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken) { // Handle renaming of symbols used for foreach var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property && string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0; implicitReferencesMightConflict = implicitReferencesMightConflict || (renameSymbol.Kind == SymbolKind.Method && (string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0)); // TODO: handle Dispose for using statement and Add methods for collection initializers. if (implicitReferencesMightConflict) { if (renamedSymbol.Name != renameSymbol.Name) { foreach (var implicitReferenceLocation in implicitReferenceLocations) { var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync( implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false); switch (token.Kind()) { case SyntaxKind.ForEachKeyword: return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation()); case SyntaxKind.AwaitKeyword: return ImmutableArray.Create(token.GetLocation()); } if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft)) { return ImmutableArray.Create(deconstructionLeft.GetLocation()); } } } } return ImmutableArray<Location>.Empty; } public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts( ISymbol renamedSymbol, SemanticModel semanticModel, Location originalDeclarationLocation, int newDeclarationLocationStartingPosition, CancellationToken cancellationToken) { // TODO: support other implicitly used methods like dispose if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0) { // TODO: partial methods currently only show the location where the rename happens as a conflict. // Consider showing both locations as a conflict. var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault(); if (baseType != null) { var implicitSymbols = semanticModel.LookupSymbols( newDeclarationLocationStartingPosition, baseType, renamedSymbol.Name) .Where(sym => !sym.Equals(renamedSymbol)); foreach (var symbol in implicitSymbols) { if (symbol.GetAllTypeArguments().Length != 0) { continue; } if (symbol.Kind == SymbolKind.Method) { var method = (IMethodSymbol)symbol; if (symbol.Name == "MoveNext") { if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean) { return ImmutableArray.Create(originalDeclarationLocation); } } else if (symbol.Name == "GetEnumerator") { // we are a bit pessimistic here. // To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach if (!method.ReturnsVoid && !method.Parameters.Any()) { return ImmutableArray.Create(originalDeclarationLocation); } } } else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current") { var property = (IPropertySymbol)symbol; if (!property.Parameters.Any() && !property.IsWriteOnly) { return ImmutableArray.Create(originalDeclarationLocation); } } } } } return ImmutableArray<Location>.Empty; } #endregion public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts) { if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9) { var conflict = replacementText.Substring(0, replacementText.Length - 9); if (!possibleNameConflicts.Contains(conflict)) { possibleNameConflicts.Add(conflict); } } if (symbol.Kind == SymbolKind.Property) { foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText }) { if (!possibleNameConflicts.Contains(conflict)) { possibleNameConflicts.Add(conflict); } } } // in C# we also need to add the valueText because it can be different from the text in source // e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for // v\u0061r and var or similar. var valueText = replacementText; var kind = SyntaxFacts.GetKeywordKind(replacementText); if (kind != SyntaxKind.None) { valueText = SyntaxFacts.GetText(kind); } else { var name = SyntaxFactory.ParseName(replacementText); if (name.Kind() == SyntaxKind.IdentifierName) { valueText = ((IdentifierNameSyntax)name).Identifier.ValueText; } } // this also covers the case of an escaped replacementText if (valueText != replacementText) { possibleNameConflicts.Add(valueText); } } /// <summary> /// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on. /// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing /// statement of this lambda. /// </summary> /// <param name="token">The token to get the complexification target for.</param> /// <returns></returns> public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token) => GetExpansionTarget(token); private static SyntaxNode? GetExpansionTarget(SyntaxToken token) { // get the directly enclosing statement var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault(); // System.Func<int, int> myFunc = arg => X; var possibleLambdaExpression = enclosingStatement == null ? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault() : null; if (possibleLambdaExpression != null) { var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression); if (lambdaExpression.Body is ExpressionSyntax) { return lambdaExpression.Body; } } // int M() => X; var possibleArrowExpressionClause = enclosingStatement == null ? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault() : null; if (possibleArrowExpressionClause != null) { return possibleArrowExpressionClause.Expression; } var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault(); if (enclosingNameMemberCrefOrnull != null) { if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax) { enclosingNameMemberCrefOrnull = null; } } var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault(); if (enclosingXmlNameAttr != null) { return null; } var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault(); if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax) { return enclosingInitializer.Value; } var attributeSyntax = token.GetAncestor<AttributeSyntax>(); if (attributeSyntax != null) { return attributeSyntax; } // there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault(); } #region "Helper Methods" public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService) { // Identifiers we never consider valid to rename to. switch (replacementText) { case "var": case "dynamic": case "unmanaged": case "notnull": return false; } var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal) ? replacementText : "@" + replacementText; // Make sure we got an identifier. if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier)) { // We still don't have an identifier, so let's fail return false; } return true; } /// <summary> /// Gets the semantic model for the given node. /// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel. /// Otherwise, returns a speculative model. /// The assumption for the later case is that span start position of the given node in it's syntax tree is same as /// the span start of the original node in the original syntax tree. /// </summary> public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel) { if (node.SyntaxTree == originalSemanticModel.SyntaxTree) { // This is possible if the previous rename phase didn't rewrite any nodes in this tree. return originalSemanticModel; } var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault(); if (nodeToSpeculate == null) { if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember)) { nodeToSpeculate = nameMember.Name; } else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref)) { nodeToSpeculate = qualifiedCref.Container; } else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint)) { nodeToSpeculate = typeConstraint.Type; } else if (node is BaseTypeSyntax baseType) { nodeToSpeculate = baseType.Type; } else { return null; } } var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); var position = nodeToSpeculate.SpanStart; return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext); } #endregion } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task FileScopedNamespace() { var initial = @"using B; using A; namespace N; using D; using C; "; var final = @"using A; using B; namespace N; using C; using D; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports { [UseExportProvider] public class OrganizeUsingsTests { protected static async Task CheckAsync( string initial, string final, bool placeSystemNamespaceFirst = false, bool separateImportGroups = false) { using var workspace = new AdhocWorkspace(); var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp); var document = project.AddDocument("Document", initial.NormalizeLineEndings()); var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst); newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups); document = document.WithSolutionOptions(newOptions); var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default); Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString()); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task EmptyFile() => await CheckAsync(string.Empty, string.Empty); [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SingleUsingStatement() { var initial = @"using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AliasesAtBottom() { var initial = @"using A = B; using C; using D = E; using F;"; var final = @"using C; using F; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task UsingStaticsBetweenUsingsAndAliases() { var initial = @"using static System.Convert; using A = B; using C; using Z; using D = E; using static System.Console; using F;"; var final = @"using C; using F; using Z; using static System.Console; using static System.Convert; using A = B; using D = E; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedStatements() { var initial = @"using B; using A; namespace N { using D; using C; namespace N1 { using F; using E; } namespace N2 { using H; using G; } } namespace N3 { using J; using I; namespace N4 { using L; using K; } namespace N5 { using N; using M; } }"; var final = @"using A; using B; namespace N { using C; using D; namespace N1 { using E; using F; } namespace N2 { using G; using H; } } namespace N3 { using I; using J; namespace N4 { using K; using L; } namespace N5 { using M; using N; } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task FileScopedNamespace() { var initial = @"using B; using A; namespace N; using D; using C; "; var final = @"using A; using B; namespace N; using C; using D; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using System; using System.Linq; using M1; using M2; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task SpecialCaseSystemWithUsingStatic() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using System; using System.Linq; using M1; using M2; using static System.BitConverter; using static Microsoft.Win32.Registry; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem() { var initial = @"using M2; using M1; using System.Linq; using System;"; var final = @"using M1; using M2; using System; using System.Linq; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystemWithUsingStatics() { var initial = @"using M2; using M1; using System.Linq; using System; using static Microsoft.Win32.Registry; using static System.BitConverter;"; var final = @"using M1; using M2; using System; using System.Linq; using static Microsoft.Win32.Registry; using static System.BitConverter;"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IndentationAfterSorting() { var initial = @"namespace A { using V.W; using U; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; var final = @"namespace A { using U; using V.W; using X.Y.Z; class B { } } namespace U { } namespace V.W { } namespace X.Y.Z { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotTouchCommentsAtBeginningOfFile3() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile4() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// Copyright (c) Microsoft Corporation. All rights reserved. /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] [WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")] public async Task DoNotTouchCommentsAtBeginningOfFile5() { var initial = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/** Copyright (c) Microsoft Corporation. All rights reserved. */ /// I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile1() { var initial = @"// Copyright (c) Microsoft Corporation. All rights reserved. using B; // I like namespace A using A; namespace A { } namespace B { }"; var final = @"// Copyright (c) Microsoft Corporation. All rights reserved. // I like namespace A using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile2() { var initial = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ using B; /* I like namespace A */ using A; namespace A { } namespace B { }"; var final = @"/* Copyright (c) Microsoft Corporation. All rights reserved. */ /* I like namespace A */ using A; using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoTouchCommentsAtBeginningOfFile3() { var initial = @"/// Copyright (c) Microsoft Corporation. All rights reserved. using B; /// I like namespace A using A; namespace A { } namespace B { }"; var final = @"/// I like namespace A using A; /// Copyright (c) Microsoft Corporation. All rights reserved. using B; namespace A { } namespace B { }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile1() { var initial = @"namespace N { // attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // attached to System using System; // attached to System.Text using System.Text; }"; await CheckAsync(initial, final); } [WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CommentsNotAtTheStartOfTheFile2() { var initial = @"namespace N { // not attached to System.Text using System.Text; // attached to System using System; }"; var final = @"namespace N { // not attached to System.Text // attached to System using System; using System.Text; }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSortIfEndIfBlocks() { var initial = @"using D; #if MYCONFIG using C; #else using B; #endif using A; namespace A { } namespace B { } namespace C { } namespace D { }"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task ExternAliases() { var initial = @"extern alias Z; extern alias Y; extern alias X; using C; using U = C.L.T; using O = A.J; using A; using W = A.J.R; using N = B.K; using V = B.K.S; using M = C.L; using B; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; var final = @"extern alias X; extern alias Y; extern alias Z; using A; using B; using C; using M = C.L; using N = B.K; using O = A.J; using U = C.L.T; using V = B.K.S; using W = A.J.R; namespace A { namespace J { class R { } } } namespace B { namespace K { struct S { } } } namespace C { namespace L { struct T { } } }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DuplicateUsings() { var initial = @"using A; using A;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InlineComments() { var initial = @"/*00*/using/*01*/D/*02*/;/*03*/ /*04*/using/*05*/C/*06*/;/*07*/ /*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*16*/"; var final = @"/*08*/using/*09*/A/*10*/;/*11*/ /*12*/using/*13*/B/*14*/;/*15*/ /*04*/using/*05*/C/*06*/;/*07*/ /*00*/using/*01*/D/*02*/;/*03*/ /*16*/"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task AllOnOneLine() { var initial = @"using C; using B; using A;"; var final = @"using A; using B; using C; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideRegionBlock() { var initial = @"#region Using directives using C; using A; using B; #endregion class Class1 { }"; var final = @"#region Using directives using A; using B; using C; #endregion class Class1 { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task NestedRegionBlock() { var initial = @"using C; #region Z using A; #endregion using B;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task MultipleRegionBlocks() { var initial = @"#region Using directives using C; #region Z using A; #endregion using B; #endregion"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InterleavedNewlines() { var initial = @"using B; using A; using C; class D { }"; var final = @"using A; using B; using C; class D { }"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task InsideIfEndIfBlock() { var initial = @"#if !X using B; using A; using C; #endif"; var final = @"#if !X using A; using B; using C; #endif"; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockAbove() { var initial = @"#if !X using C; using B; using F; #endif using D; using A; using E;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockMiddle() { var initial = @"using D; using A; using H; #if !X using C; using B; using I; #endif using F; using E; using G;"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task IfEndIfBlockBelow() { var initial = @"using D; using A; using E; #if !X using C; using B; using F; #endif"; var final = initial; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task Korean() { var initial = @"using 하; using 파; using 타; using 카; using 차; using 자; using 아; using 사; using 바; using 마; using 라; using 다; using 나; using 가;"; var final = @"using 가; using 나; using 다; using 라; using 마; using 바; using 사; using 아; using 자; using 차; using 카; using 타; using 파; using 하; "; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem1() { var initial = @"using B; using System.Collections.Generic; using C; using _System; using SystemZ; using D.System; using System; using System.Collections; using A;"; var final = @"using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task DoNotSpecialCaseSystem2() { var initial = @"extern alias S; extern alias R; extern alias T; using B; using System.Collections.Generic; using C; using _System; using SystemZ; using Y = System.UInt32; using Z = System.Int32; using D.System; using System; using N = System; using M = System.Collections; using System.Collections; using A;"; var final = @"extern alias R; extern alias S; extern alias T; using _System; using A; using B; using C; using D.System; using System; using System.Collections; using System.Collections.Generic; using SystemZ; using M = System.Collections; using N = System; using Y = System.UInt32; using Z = System.Int32; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: false); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity1() { var initial = @"using Bb; using B; using bB; using b; using Aa; using a; using A; using aa; using aA; using AA; using bb; using BB; using bBb; using bbB; using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using cC; using Cc; using アア; using アア; using アあ; using アア; using アア; using BBb; using BbB; using bBB; using BBB; using c; using C; using bbb; using Bbb; using cc; using cC; using CC; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; var final = @"using a; using A; using aa; using aA; using Aa; using AA; using b; using B; using bb; using bB; using Bb; using BB; using bbb; using bbB; using bBb; using bBB; using Bbb; using BbB; using BBb; using BBB; using c; using C; using cc; using cC; using cC; using Cc; using CC; using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; // If Kana is sensitive あ != ア, if Kana is insensitive あ == ア. // If Width is sensitiveア != ア, if Width is insensitive ア == ア."; await CheckAsync(initial, final); } [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task CaseSensitivity2() { var initial = @"using あ; using ア; using ア; using ああ; using あア; using あア; using アあ; using アア; using アア; using アあ; using アア; using アア;"; var final = @"using ア; using ア; using あ; using アア; using アア; using アア; using アア; using アあ; using アあ; using あア; using あア; using ああ; "; await CheckAsync(initial, final); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping() { var initial = @"// Banner using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using IntList = System.Collections.Generic.List<int>; using static System.Console;"; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } [WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")] [Fact, Trait(Traits.Feature, Traits.Features.Organizing)] public async Task TestGrouping2() { // Make sure we don't insert extra newlines if they're already there. var initial = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; var final = @"// Banner using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using static System.Console; using IntList = System.Collections.Generic.List<int>; "; await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true); } } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationServiceRunner.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.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Recommendations { internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext> where TSyntaxContext : SyntaxContext { protected readonly TSyntaxContext _context; protected readonly bool _filterOutOfScopeLocals; protected readonly CancellationToken _cancellationToken; private readonly StringComparer _stringComparerForLanguage; public AbstractRecommendationServiceRunner( TSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) { _context = context; _stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer; _filterOutOfScopeLocals = filterOutOfScopeLocals; _cancellationToken = cancellationToken; } public abstract RecommendedSymbols GetRecommendedSymbols(); public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType); // This code is to help give intellisense in the following case: // query.Include(a => a.SomeProperty).ThenInclude(a => a. // where there are more than one overloads of ThenInclude accepting different types of parameters. private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable) { var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position); return symbols.IsDefault ? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable) : symbols; } private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position) { // Use normal lookup path for this/base parameters. if (parameter.IsThis) return default; // Starting from a. in the example, looking for a => a. if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod) return default; // Cannot proceed without DeclaringSyntaxReferences. // We expect that there is a single DeclaringSyntaxReferences in the scenario. // If anything changes on the compiler side, the approach should be revised. if (owningMethod.DeclaringSyntaxReferences.Length != 1) return default; var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>(); // Check that a => a. belongs to an invocation. // Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a. var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken); if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) && syntaxFactsService.IsArgument(lambdaSyntax.Parent) && syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent))) { return default; } var invocationExpression = lambdaSyntax.Parent.Parent.Parent; var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression); var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent); var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent); var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression); var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty; if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType)) { parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType); } else { // Get all members potentially matching the invocation expression. // We filter them out based on ordinality later. var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken); // parameter.Ordinal is the ordinal within (a,b,c) => b. // For candidate symbols of (a,b,c) => b., get types of all possible b. parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal); // The parameterTypeSymbols may include type parameters, and we want their substituted types if available. parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression); } // For each type of b., return all suitable members. Also, ensure we consider the actual type of the // parameter the compiler inferred as it may have made a completely suitable inference for it. return parameterTypeSymbols .Concat(parameter.Type) .SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false)) .ToImmutableArray(); } private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression) { if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter))) { return parameterTypeSymbols; } var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols(); if (invocationSymbols.Length == 0) { return parameterTypeSymbols; } using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes); foreach (var invocationSymbol in invocationSymbols) { var typeParameters = invocationSymbol.GetTypeParameters(); var typeArguments = invocationSymbol.GetTypeArguments(); foreach (var parameterTypeSymbol in parameterTypeSymbols) { if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter)) { // The typeParameter could be from the containing type, so it may not be // present in this method's list of typeParameters. var index = typeParameters.IndexOf(typeParameter); var concreteType = typeArguments.ElementAtOrDefault(index); // If we couldn't find the concrete type, still consider the typeParameter // as is to provide members of any types it is constrained to (including object) concreteTypes.Add(concreteType ?? typeParameter); } else { concreteTypes.Add(parameterTypeSymbol); } } } return concreteTypes.ToImmutable(); } /// <summary> /// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol. /// </summary> /// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/> /// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length) /// </param> /// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param> /// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param> /// <returns></returns> private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda) { var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName); var builder = ArrayBuilder<ITypeSymbol>.GetInstance(); foreach (var candidateSymbol in candidateSymbols) { if (candidateSymbol is IMethodSymbol method) { if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type)) { continue; } // If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate. // Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>. if (expressionSymbol != null && type is INamedTypeSymbol expressionSymbolNamedTypeCandidate && expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol)) { var allTypeArguments = type.GetAllTypeArguments(); if (allTypeArguments.Length != 1) { continue; } type = allTypeArguments[0]; } if (type.IsDelegateType()) { var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { continue; } var parameters = methods[0].GetParameters(); if (parameters.Length <= ordinalInLambda) { continue; } builder.Add(parameters[ordinalInLambda].Type); } } } return builder.ToImmutableAndFree().Distinct(); } private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType) { if (!string.IsNullOrEmpty(argumentName)) { parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type; return parameterType != null; } // We don't know the argument name, so have to find the parameter based on position if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1)) { if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType) { parameterType = arrayType.ElementType; return true; } else { parameterType = null; return false; } } if (ordinalInInvocation < method.Parameters.Length) { parameterType = method.Parameters[ordinalInInvocation].Type; return true; } parameterType = null; return false; } protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>() where TNamespaceDeclarationSyntax : SyntaxNode { var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>(); if (declarationSyntax == null) return ImmutableArray<ISymbol>.Empty; var semanticModel = _context.SemanticModel; var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace( semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken)); var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol) .WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax)); return symbols; } protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax) { // // Apart from filtering out non-namespace symbols, this also filters out the symbol // currently being declared. For example... // // namespace X$$ // // ...X won't show in the completion list (unless it is also declared elsewhere). // // In addition, in VB, it will filter out Bar from the sample below... // // Namespace Goo.$$ // Namespace Bar // End Namespace // End Namespace // // ...unless, again, it's also declared elsewhere. // return recommendationSymbol.IsNamespace() && recommendationSymbol.Locations.Any( candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree && declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan))); } protected ImmutableArray<ISymbol> GetMemberSymbols( ISymbol container, int position, bool excludeInstance, bool useBaseReferenceAccessibility, bool unwrapNullable) { // For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter // information that the compiler may fail to give. if (container is IParameterSymbol parameter) return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable); if (container is not INamespaceOrTypeSymbol namespaceOrType) return ImmutableArray<ISymbol>.Empty; if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol) { namespaceOrType = typeSymbol.RemoveNullableIfPresent(); } return useBaseReferenceAccessibility ? _context.SemanticModel.LookupBaseMembers(position) : LookupSymbolsInContainer(namespaceOrType, position, excludeInstance); } protected ImmutableArray<ISymbol> LookupSymbolsInContainer( INamespaceOrTypeSymbol container, int position, bool excludeInstance) { return excludeInstance ? _context.SemanticModel.LookupStaticMembers(position, container) : SuppressDefaultTupleElements( container, _context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true)); } /// <summary> /// If container is a tuple type, any of its tuple element which has a friendly name will cause /// the suppression of the corresponding default name (ItemN). /// In that case, Rest is also removed. /// </summary> protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements( INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols) { var namedType = container as INamedTypeSymbol; if (namedType?.IsTupleType != true) { // container is not a tuple return symbols; } //return tuple elements followed by other members that are not fields return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements). Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field)); } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.Recommendations { internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext> where TSyntaxContext : SyntaxContext { protected readonly TSyntaxContext _context; protected readonly bool _filterOutOfScopeLocals; protected readonly CancellationToken _cancellationToken; private readonly StringComparer _stringComparerForLanguage; public AbstractRecommendationServiceRunner( TSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken) { _context = context; _stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer; _filterOutOfScopeLocals = filterOutOfScopeLocals; _cancellationToken = cancellationToken; } public abstract RecommendedSymbols GetRecommendedSymbols(); public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType); // This code is to help give intellisense in the following case: // query.Include(a => a.SomeProperty).ThenInclude(a => a. // where there are more than one overloads of ThenInclude accepting different types of parameters. private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable) { var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position); return symbols.IsDefault ? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable) : symbols; } private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position) { // Use normal lookup path for this/base parameters. if (parameter.IsThis) return default; // Starting from a. in the example, looking for a => a. if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod) return default; // Cannot proceed without DeclaringSyntaxReferences. // We expect that there is a single DeclaringSyntaxReferences in the scenario. // If anything changes on the compiler side, the approach should be revised. if (owningMethod.DeclaringSyntaxReferences.Length != 1) return default; var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>(); // Check that a => a. belongs to an invocation. // Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a. var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken); if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) && syntaxFactsService.IsArgument(lambdaSyntax.Parent) && syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent))) { return default; } var invocationExpression = lambdaSyntax.Parent.Parent.Parent; var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression); var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent); var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent); var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression); var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty; if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType)) { parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType); } else { // Get all members potentially matching the invocation expression. // We filter them out based on ordinality later. var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken); // parameter.Ordinal is the ordinal within (a,b,c) => b. // For candidate symbols of (a,b,c) => b., get types of all possible b. parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal); // The parameterTypeSymbols may include type parameters, and we want their substituted types if available. parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression); } // For each type of b., return all suitable members. Also, ensure we consider the actual type of the // parameter the compiler inferred as it may have made a completely suitable inference for it. return parameterTypeSymbols .Concat(parameter.Type) .SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false)) .ToImmutableArray(); } private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression) { if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter))) { return parameterTypeSymbols; } var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols(); if (invocationSymbols.Length == 0) { return parameterTypeSymbols; } using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes); foreach (var invocationSymbol in invocationSymbols) { var typeParameters = invocationSymbol.GetTypeParameters(); var typeArguments = invocationSymbol.GetTypeArguments(); foreach (var parameterTypeSymbol in parameterTypeSymbols) { if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter)) { // The typeParameter could be from the containing type, so it may not be // present in this method's list of typeParameters. var index = typeParameters.IndexOf(typeParameter); var concreteType = typeArguments.ElementAtOrDefault(index); // If we couldn't find the concrete type, still consider the typeParameter // as is to provide members of any types it is constrained to (including object) concreteTypes.Add(concreteType ?? typeParameter); } else { concreteTypes.Add(parameterTypeSymbol); } } } return concreteTypes.ToImmutable(); } /// <summary> /// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol. /// </summary> /// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/> /// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length) /// </param> /// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param> /// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param> /// <returns></returns> private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda) { var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName); var builder = ArrayBuilder<ITypeSymbol>.GetInstance(); foreach (var candidateSymbol in candidateSymbols) { if (candidateSymbol is IMethodSymbol method) { if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type)) { continue; } // If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate. // Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>. if (expressionSymbol != null && type is INamedTypeSymbol expressionSymbolNamedTypeCandidate && expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol)) { var allTypeArguments = type.GetAllTypeArguments(); if (allTypeArguments.Length != 1) { continue; } type = allTypeArguments[0]; } if (type.IsDelegateType()) { var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName); if (methods.Length != 1) { continue; } var parameters = methods[0].GetParameters(); if (parameters.Length <= ordinalInLambda) { continue; } builder.Add(parameters[ordinalInLambda].Type); } } } return builder.ToImmutableAndFree().Distinct(); } private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType) { if (!string.IsNullOrEmpty(argumentName)) { parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type; return parameterType != null; } // We don't know the argument name, so have to find the parameter based on position if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1)) { if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType) { parameterType = arrayType.ElementType; return true; } else { parameterType = null; return false; } } if (ordinalInInvocation < method.Parameters.Length) { parameterType = method.Parameters[ordinalInInvocation].Type; return true; } parameterType = null; return false; } protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>() where TNamespaceDeclarationSyntax : SyntaxNode { var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>(); if (declarationSyntax == null) return ImmutableArray<ISymbol>.Empty; var semanticModel = _context.SemanticModel; var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace( semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken)); var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol) .WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax)); return symbols; } protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax) { // // Apart from filtering out non-namespace symbols, this also filters out the symbol // currently being declared. For example... // // namespace X$$ // // ...X won't show in the completion list (unless it is also declared elsewhere). // // In addition, in VB, it will filter out Bar from the sample below... // // Namespace Goo.$$ // Namespace Bar // End Namespace // End Namespace // // ...unless, again, it's also declared elsewhere. // return recommendationSymbol.IsNamespace() && recommendationSymbol.Locations.Any( candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree && declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan))); } protected ImmutableArray<ISymbol> GetMemberSymbols( ISymbol container, int position, bool excludeInstance, bool useBaseReferenceAccessibility, bool unwrapNullable) { // For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter // information that the compiler may fail to give. if (container is IParameterSymbol parameter) return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable); if (container is not INamespaceOrTypeSymbol namespaceOrType) return ImmutableArray<ISymbol>.Empty; if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol) { namespaceOrType = typeSymbol.RemoveNullableIfPresent(); } return useBaseReferenceAccessibility ? _context.SemanticModel.LookupBaseMembers(position) : LookupSymbolsInContainer(namespaceOrType, position, excludeInstance); } protected ImmutableArray<ISymbol> LookupSymbolsInContainer( INamespaceOrTypeSymbol container, int position, bool excludeInstance) { return excludeInstance ? _context.SemanticModel.LookupStaticMembers(position, container) : SuppressDefaultTupleElements( container, _context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true)); } /// <summary> /// If container is a tuple type, any of its tuple element which has a friendly name will cause /// the suppression of the corresponding default name (ItemN). /// In that case, Rest is also removed. /// </summary> protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements( INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols) { var namedType = container as INamedTypeSymbol; if (namedType?.IsTupleType != true) { // container is not a tuple return symbols; } //return tuple elements followed by other members that are not fields return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements). Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field)); } } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxNodeExtensions { public static void Deconstruct(this SyntaxNode node, out SyntaxKind kind) { kind = node.Kind(); } public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result) where TNode : SyntaxNode { if (node.IsKind(kind)) { result = (TNode)node; return true; } result = null; return false; } public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind) => CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind); public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result) where TNode : SyntaxNode { if (node.IsParentKind(kind)) { result = (TNode)node.Parent!; return true; } result = null; return false; } public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2) => IsKind(node?.Parent, kind1, kind2); public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) => IsKind(node?.Parent, kind1, kind2, kind3); public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) => IsKind(node?.Parent, kind1, kind2, kind3, kind4); public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11; } public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken( this SyntaxNode node, SourceText? sourceText = null, bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false) => node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken( sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine); /// <summary> /// Returns all of the trivia to the left of this token up to the previous token (concatenates /// the previous token's trailing trivia and this token's leading trivia). /// </summary> public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken( this SyntaxToken token, SourceText? sourceText = null, bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false) { var prevToken = token.GetPreviousToken(includeSkipped: true); if (prevToken.Kind() == SyntaxKind.None) { return token.LeadingTrivia; } Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too."); if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine && !sourceText!.AreOnSameLine(prevToken, token)) { return token.LeadingTrivia; } return prevToken.TrailingTrivia.Concat(token.LeadingTrivia); } public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.ArgumentList) || node.IsKind(SyntaxKind.AttributeArgumentList) || node.IsKind(SyntaxKind.BracketedArgumentList) || node.IsKind(SyntaxKind.TypeArgumentList); } public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node) { switch (node) { case NamespaceDeclarationSyntax namespaceNode: return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken); case BaseTypeDeclarationSyntax baseTypeNode: return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken); case AccessorListSyntax accessorListNode: return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken); case BlockSyntax blockNode: return (blockNode.OpenBraceToken, blockNode.CloseBraceToken); case SwitchStatementSyntax switchStatementNode: return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken); case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression: return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken); case InitializerExpressionSyntax initializeExpressionNode: return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken); case SwitchExpressionSyntax switchExpression: return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken); case PropertyPatternClauseSyntax property: return (property.OpenBraceToken, property.CloseBraceToken); case WithExpressionSyntax withExpr: return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken); case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }: return (initializer.OpenBraceToken, initializer.CloseBraceToken); } return default; } public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node is DoStatementSyntax || node is ElseClauseSyntax || node is FixedStatementSyntax || node is CommonForEachStatementSyntax || node is ForStatementSyntax || node is IfStatementSyntax || node is LabeledStatementSyntax || node is LockStatementSyntax || node is UsingStatementSyntax || node is WhileStatementSyntax; } public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node) => node switch { DoStatementSyntax n => n.Statement, ElseClauseSyntax n => n.Statement, FixedStatementSyntax n => n.Statement, CommonForEachStatementSyntax n => n.Statement, ForStatementSyntax n => n.Statement, IfStatementSyntax n => n.Statement, LabeledStatementSyntax n => n.Statement, LockStatementSyntax n => n.Statement, UsingStatementSyntax n => n.Statement, WhileStatementSyntax n => n.Statement, _ => null, }; public static BaseParameterListSyntax? GetParameterList(this SyntaxNode? declaration) => declaration?.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList, SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList, SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList, SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList, SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList, SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList, SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList, SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList, SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList, SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration => ((RecordDeclarationSyntax)declaration).ParameterList, _ => null, }; public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, _ => default, }; public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node) { // Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in // LanguageParser.ParseConsequenceSyntax). // These are the parts of the expression that the ?... expression can end with. Specifically: // // 1. x?.y.M() // invocation // 2. x?.y[...]; // element access // 3. x?.y.z // member access // 4. x?.y // member binding // 5. x?[y] // element binding var current = node; if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) || (current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current)) { current = current.Parent; } // Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first // conditional access. while (current.IsKind( SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.MemberBindingExpression, SyntaxKind.ElementBindingExpression) && current.Parent is not ConditionalAccessExpressionSyntax) { current = current.Parent; } // Two cases we have to care about: // // 1. a?.b.$$c.d and // 2. a?.b.$$c.d?.e... // // Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are // lower in the tree and are not seen as we walk upwards. // // // To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the // right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a // another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction: // // a?.b.$$c.d?.e // it will do: // -----> // <--------- // // Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to // get the root parent in a case like: // // x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do: // -----> // <--------- // <--- // <--- // <--- if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) && conditional.Expression == current) { current = conditional; } if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) && conditional.WhenNotNull == current) { current = conditional; } return current as ConditionalAccessExpressionSyntax; } /// <summary> /// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/> /// </summary>> public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node) { // Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at // the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with // `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE // sequence). var current = node.GetParentConditionalAccessExpression(); while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) && conditional.WhenNotNull == current) { current = conditional; } return current; } public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node) { if (!(node is ConditionalAccessExpressionSyntax)) { return null; } var result = (ConditionalAccessExpressionSyntax)node; while (result.WhenNotNull is ConditionalAccessExpressionSyntax) { result = (ConditionalAccessExpressionSyntax)result.WhenNotNull; } return result; } public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.MethodDeclaration) || node.IsAnyLambdaOrAnonymousMethod() || node.IsKind(SyntaxKind.LocalFunctionStatement); } public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || node.IsKind(SyntaxKind.SimpleLambdaExpression); } public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression); public static bool IsAnyAssignExpression(this SyntaxNode node) => SyntaxFacts.IsAssignmentExpression(node.Kind()); public static bool IsCompoundAssignExpression(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: return true; } return false; } public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) && assignment.Left == node; public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Right == node; } public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsCompoundAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } /// <summary> /// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in /// top down order. /// </summary> public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Usings)); } public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Externs)); } public static bool IsUnsafeContext(this SyntaxNode node) { if (node.GetAncestor<UnsafeStatementSyntax>() != null) { return true; } return node.GetAncestors<MemberDeclarationSyntax>().Any( m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)); } public static bool IsInStaticContext(this SyntaxNode node) { // this/base calls are always static. if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null) { return true; } var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (memberDeclaration == null) { return false; } switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) || node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Inside a field one can only access static members of a type (unless it's top-level). return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit); case SyntaxKind.DestructorDeclaration: return false; } // Global statements are not a static context. if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null) { return false; } // any other location is considered static return true; } public static NamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode) { var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirectiveAncestor == null) { return contextNode.GetAncestorsOrThis<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } else { // We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings. var containingNamespace = usingDirectiveAncestor.GetAncestor<NamespaceDeclarationSyntax>(); if (containingNamespace == null) { // We are inside a top level using directive (i.e. one that's directly in the compilation unit). return null; } else { return containingNamespace.GetAncestors<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } } } public static bool IsBreakableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return true; } return false; } public static bool IsContinuableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return true; } return false; } public static bool IsReturnableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.LocalFunctionStatement: case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; } return false; } public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list); [return: NotNullIfNotNull("node")] public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false) where TNode : SyntaxNode { if (node == null) { return node; } var rewriter = new SingleLineRewriter(useElasticTrivia); return (TNode)rewriter.Visit(node); } /// <summary> /// Returns true if the passed in node contains an interleaved pp directive. /// /// i.e. The following returns false: /// /// void Goo() { /// #if true /// #endif /// } /// /// #if true /// void Goo() { /// } /// #endif /// /// but these return true: /// /// #if true /// void Goo() { /// #endif /// } /// /// void Goo() { /// #if true /// } /// #endif /// /// #if true /// void Goo() { /// #else /// } /// #endif /// /// i.e. the method returns true if it contains a PP directive that belongs to a grouping /// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't /// entirely contained within the span of the node. /// </summary> public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken) => CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken); /// <summary> /// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check /// for interleaved directives can be specified separately to the node passed in. /// </summary> public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken) => CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken); public static bool ContainsInterleavedDirective( this SyntaxToken token, TextSpan textSpan, CancellationToken cancellationToken) { return ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) || ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken); } private static bool ContainsInterleavedDirective( TextSpan textSpan, SyntaxTriviaList list, CancellationToken cancellationToken) { foreach (var trivia in list) { if (textSpan.Contains(trivia.Span)) { if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken)) { return true; } } } return false; } private static bool ContainsInterleavedDirective( TextSpan textSpan, SyntaxTrivia trivia, CancellationToken cancellationToken) { if (trivia.HasStructure) { var structure = trivia.GetStructure()!; if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.IfDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia)) { var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken); if (match != null) { var matchSpan = match.Span; if (!textSpan.Contains(matchSpan.Start)) { // The match for this pp directive is outside // this node. return true; } } } else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia)) { var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken); if (directives != null && directives.Count > 0) { if (!textSpan.Contains(directives[0].SpanStart) || !textSpan.Contains(directives[directives.Count - 1].SpanStart)) { // This else/elif belongs to a pp span that isn't // entirely within this node. return true; } } } } return false; } /// <summary> /// Breaks up the list of provided nodes, based on how they are interspersed with pp /// directives, into groups. Within these groups nodes can be moved around safely, without /// breaking any pp constructs. /// </summary> public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>( this IEnumerable<TSyntaxNode> nodes, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var result = new List<IList<TSyntaxNode>>(); var currentGroup = new List<TSyntaxNode>(); foreach (var node in nodes) { var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken); var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind())); if (hasUnmatchedInteriorDirective) { // we have a #if/#endif/#region/#endregion/#else/#elif in // this node that belongs to a span of pp directives that // is not entirely contained within the node. i.e.: // // void Goo() { // #if ... // } // // This node cannot be moved at all. It is in a group that // only contains itself (and thus can never be moved). // add whatever group we've built up to now. And reset the // next group to empty. result.Add(currentGroup); currentGroup = new List<TSyntaxNode>(); result.Add(new List<TSyntaxNode> { node }); } else if (hasLeadingDirective) { // We have a PP directive before us. i.e.: // // #if ... // void Goo() { // // That means we start a new group that is contained between // the above directive and the following directive. // add whatever group we've built up to now. And reset the // next group to empty. result.Add(currentGroup); currentGroup = new List<TSyntaxNode>(); currentGroup.Add(node); } else { // simple case. just add ourselves to the current group currentGroup.Add(node); } } // add the remainder of the final group. result.Add(currentGroup); // Now, filter out any empty groups. result = result.Where(group => !group.IsEmpty()).ToList(); return result; } public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node); public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node); public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia); public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node); public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node); public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia); public static bool IsVariableDeclaratorValue(this SyntaxNode node) => node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) && equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) && equalsValue.Value == node; public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode<BlockSyntax>(); public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate) { var current = node; while (current != null) { if (predicate(current)) { yield return current; } current = current.Parent; } } /// <summary> /// Returns child node or token that contains given position. /// </summary> /// <remarks> /// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node. /// </remarks> internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex) { var childList = self.ChildNodesAndTokens(); var left = 0; var right = childList.Count - 1; while (left <= right) { var middle = left + ((right - left) / 2); var node = childList[middle]; var span = node.FullSpan; if (position < span.Start) { right = middle - 1; } else if (position >= span.End) { left = middle + 1; } else { childIndex = middle; return node; } } // we could check up front that index is within FullSpan, // but we wan to optimize for the common case where position is valid. Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?"); throw new ArgumentOutOfRangeException(nameof(position)); } public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node) { switch (node) { case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken); case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken); case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken); default: return default; } } public static (SyntaxToken openBracket, SyntaxToken closeBracket) GetBrackets(this SyntaxNode node) { switch (node) { case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); default: return default; } } public static SyntaxTokenList GetModifiers(this SyntaxNode? member) { switch (member) { case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers; case AccessorDeclarationSyntax accessor: return accessor.Modifiers; case AnonymousFunctionExpressionSyntax anonymous: return anonymous.Modifiers; case LocalFunctionStatementSyntax localFunction: return localFunction.Modifiers; case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.Modifiers; } return default; } public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers) { switch (member) { case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers); case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers); case AnonymousFunctionExpressionSyntax anonymous: return anonymous.WithModifiers(modifiers); case LocalFunctionStatementSyntax localFunction: return localFunction.WithModifiers(modifiers); case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.WithModifiers(modifiers); } return null; } public static bool CheckTopLevel(this SyntaxNode node, TextSpan span) { switch (node) { case BlockSyntax block: return block.ContainsInBlockBody(span); case ArrowExpressionClauseSyntax expressionBodiedMember: return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span); case FieldDeclarationSyntax field: { foreach (var variable in field.Declaration.Variables) { if (variable.Initializer != null && variable.Initializer.Span.Contains(span)) { return true; } } break; } case GlobalStatementSyntax _: return true; case ConstructorInitializerSyntax constructorInitializer: return constructorInitializer.ContainsInArgument(span); } return false; } public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan) { if (initializer == null) { return false; } return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan)); } public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan) { if (block == null) { return false; } var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart); return blockSpan.Contains(textSpan); } public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan) { if (expressionBodiedMember == null) { return false; } var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End); return expressionBodiedMemberBody.Contains(textSpan); } public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node) { switch (node) { case CompilationUnitSyntax compilation: return compilation.Members; case BaseNamespaceDeclarationSyntax @namespace: return @namespace.Members; case TypeDeclarationSyntax type: return type.Members; case EnumDeclarationSyntax @enum: return @enum.Members; } return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>(); } public static bool IsInExpressionTree( [NotNullWhen(returnValue: true)] this SyntaxNode? node, SemanticModel semanticModel, [NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) { if (expressionTypeOpt != null) { for (var current = node; current != null; current = current.Parent) { if (current.IsAnyLambda()) { var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken); if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition)) return true; } else if (current is SelectOrGroupClauseSyntax || current is OrderingSyntax) { var info = semanticModel.GetSymbolInfo(current, cancellationToken); if (TakesExpressionTree(info, expressionTypeOpt)) return true; } else if (current is QueryClauseSyntax queryClause) { var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken); if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) || TakesExpressionTree(info.OperationInfo, expressionTypeOpt)) { return true; } } } } return false; static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType) { foreach (var symbol in info.GetAllSymbols()) { if (symbol is IMethodSymbol method && method.Parameters.Length > 0 && expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition)) { return true; } } return false; } } public static bool IsInDeconstructionLeft( [NotNullWhen(returnValue: true)] this SyntaxNode? node, [NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft) { SyntaxNode? previous = null; for (var current = node; current != null; current = current.Parent) { if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) || (current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable)) { deconstructionLeft = previous; return true; } if (current is StatementSyntax) { break; } previous = current; } deconstructionLeft = null; return false; } public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node) => node switch { { Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true, { Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true, _ => false }; public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken) where T : SyntaxNode => node.WithCommentsFrom( SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken), SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken)); public static T WithCommentsFrom<T>( this T node, IEnumerable<SyntaxToken> leadingTokens, IEnumerable<SyntaxToken> trailingTokens) where T : SyntaxNode => node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia()); public static T WithCommentsFrom<T>( this T node, IEnumerable<SyntaxTrivia> leadingTrivia, IEnumerable<SyntaxTrivia> trailingTrivia, params SyntaxNodeOrToken[] trailingNodesOrTokens) where T : SyntaxNode => node .WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false)) .WithTrailingTrivia( node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false)); public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode => node .WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true)) .WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: true)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class SyntaxNodeExtensions { public static void Deconstruct(this SyntaxNode node, out SyntaxKind kind) { kind = node.Kind(); } public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result) where TNode : SyntaxNode { if (node.IsKind(kind)) { result = (TNode)node; return true; } result = null; return false; } public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind) => CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind); public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result) where TNode : SyntaxNode { if (node.IsParentKind(kind)) { result = (TNode)node.Parent!; return true; } result = null; return false; } public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2) => IsKind(node?.Parent, kind1, kind2); public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) => IsKind(node?.Parent, kind1, kind2, kind3); public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) => IsKind(node?.Parent, kind1, kind2, kind3, kind4); public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10; } public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11) { if (node == null) { return false; } var csharpKind = node.Kind(); return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11; } public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken( this SyntaxNode node, SourceText? sourceText = null, bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false) => node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken( sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine); /// <summary> /// Returns all of the trivia to the left of this token up to the previous token (concatenates /// the previous token's trailing trivia and this token's leading trivia). /// </summary> public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken( this SyntaxToken token, SourceText? sourceText = null, bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false) { var prevToken = token.GetPreviousToken(includeSkipped: true); if (prevToken.Kind() == SyntaxKind.None) { return token.LeadingTrivia; } Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too."); if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine && !sourceText!.AreOnSameLine(prevToken, token)) { return token.LeadingTrivia; } return prevToken.TrailingTrivia.Concat(token.LeadingTrivia); } public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.ArgumentList) || node.IsKind(SyntaxKind.AttributeArgumentList) || node.IsKind(SyntaxKind.BracketedArgumentList) || node.IsKind(SyntaxKind.TypeArgumentList); } public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node) { switch (node) { case NamespaceDeclarationSyntax namespaceNode: return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken); case BaseTypeDeclarationSyntax baseTypeNode: return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken); case AccessorListSyntax accessorListNode: return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken); case BlockSyntax blockNode: return (blockNode.OpenBraceToken, blockNode.CloseBraceToken); case SwitchStatementSyntax switchStatementNode: return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken); case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression: return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken); case InitializerExpressionSyntax initializeExpressionNode: return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken); case SwitchExpressionSyntax switchExpression: return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken); case PropertyPatternClauseSyntax property: return (property.OpenBraceToken, property.CloseBraceToken); case WithExpressionSyntax withExpr: return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken); case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }: return (initializer.OpenBraceToken, initializer.CloseBraceToken); } return default; } public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node is DoStatementSyntax || node is ElseClauseSyntax || node is FixedStatementSyntax || node is CommonForEachStatementSyntax || node is ForStatementSyntax || node is IfStatementSyntax || node is LabeledStatementSyntax || node is LockStatementSyntax || node is UsingStatementSyntax || node is WhileStatementSyntax; } public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node) => node switch { DoStatementSyntax n => n.Statement, ElseClauseSyntax n => n.Statement, FixedStatementSyntax n => n.Statement, CommonForEachStatementSyntax n => n.Statement, ForStatementSyntax n => n.Statement, IfStatementSyntax n => n.Statement, LabeledStatementSyntax n => n.Statement, LockStatementSyntax n => n.Statement, UsingStatementSyntax n => n.Statement, WhileStatementSyntax n => n.Statement, _ => null, }; public static BaseParameterListSyntax? GetParameterList(this SyntaxNode? declaration) => declaration?.Kind() switch { SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList, SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList, SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList, SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList, SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList, SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList, SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList, SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList, SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList, SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList, SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration => ((RecordDeclarationSyntax)declaration).ParameterList, _ => null, }; public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists, AccessorDeclarationSyntax accessor => accessor.AttributeLists, ParameterSyntax parameter => parameter.AttributeLists, CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists, _ => default, }; public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node) { // Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in // LanguageParser.ParseConsequenceSyntax). // These are the parts of the expression that the ?... expression can end with. Specifically: // // 1. x?.y.M() // invocation // 2. x?.y[...]; // element access // 3. x?.y.z // member access // 4. x?.y // member binding // 5. x?[y] // element binding var current = node; if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) || (current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current)) { current = current.Parent; } // Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first // conditional access. while (current.IsKind( SyntaxKind.InvocationExpression, SyntaxKind.ElementAccessExpression, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.MemberBindingExpression, SyntaxKind.ElementBindingExpression) && current.Parent is not ConditionalAccessExpressionSyntax) { current = current.Parent; } // Two cases we have to care about: // // 1. a?.b.$$c.d and // 2. a?.b.$$c.d?.e... // // Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are // lower in the tree and are not seen as we walk upwards. // // // To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the // right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a // another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction: // // a?.b.$$c.d?.e // it will do: // -----> // <--------- // // Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to // get the root parent in a case like: // // x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do: // -----> // <--------- // <--- // <--- // <--- if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) && conditional.Expression == current) { current = conditional; } if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) && conditional.WhenNotNull == current) { current = conditional; } return current as ConditionalAccessExpressionSyntax; } /// <summary> /// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/> /// </summary>> public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node) { // Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at // the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with // `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE // sequence). var current = node.GetParentConditionalAccessExpression(); while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) && conditional.WhenNotNull == current) { current = conditional; } return current; } public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node) { if (!(node is ConditionalAccessExpressionSyntax)) { return null; } var result = (ConditionalAccessExpressionSyntax)node; while (result.WhenNotNull is ConditionalAccessExpressionSyntax) { result = (ConditionalAccessExpressionSyntax)result.WhenNotNull; } return result; } public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.MethodDeclaration) || node.IsAnyLambdaOrAnonymousMethod() || node.IsKind(SyntaxKind.LocalFunctionStatement); } public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node) { return node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) || node.IsKind(SyntaxKind.SimpleLambdaExpression); } public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression); public static bool IsAnyAssignExpression(this SyntaxNode node) => SyntaxFacts.IsAssignmentExpression(node.Kind()); public static bool IsCompoundAssignExpression(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.CoalesceAssignmentExpression: case SyntaxKind.AddAssignmentExpression: case SyntaxKind.SubtractAssignmentExpression: case SyntaxKind.MultiplyAssignmentExpression: case SyntaxKind.DivideAssignmentExpression: case SyntaxKind.ModuloAssignmentExpression: case SyntaxKind.AndAssignmentExpression: case SyntaxKind.ExclusiveOrAssignmentExpression: case SyntaxKind.OrAssignmentExpression: case SyntaxKind.LeftShiftAssignmentExpression: case SyntaxKind.RightShiftAssignmentExpression: return true; } return false; } public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node) => node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) && assignment.Left == node; public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsAnyAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Right == node; } public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node) { return node?.Parent != null && node.Parent.IsCompoundAssignExpression() && ((AssignmentExpressionSyntax)node.Parent).Left == node; } /// <summary> /// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in /// top down order. /// </summary> public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings .Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Usings)); } public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node) { return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs .Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>() .Reverse() .SelectMany(n => n.Externs)); } public static bool IsUnsafeContext(this SyntaxNode node) { if (node.GetAncestor<UnsafeStatementSyntax>() != null) { return true; } return node.GetAncestors<MemberDeclarationSyntax>().Any( m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword)); } public static bool IsInStaticContext(this SyntaxNode node) { // this/base calls are always static. if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null) { return true; } var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>(); if (memberDeclaration == null) { return false; } switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) || node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Inside a field one can only access static members of a type (unless it's top-level). return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit); case SyntaxKind.DestructorDeclaration: return false; } // Global statements are not a static context. if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null) { return false; } // any other location is considered static return true; } public static NamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode) { var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirectiveAncestor == null) { return contextNode.GetAncestorsOrThis<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } else { // We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings. var containingNamespace = usingDirectiveAncestor.GetAncestor<NamespaceDeclarationSyntax>(); if (containingNamespace == null) { // We are inside a top level using directive (i.e. one that's directly in the compilation unit). return null; } else { return containingNamespace.GetAncestors<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0); } } } public static bool IsBreakableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return true; } return false; } public static bool IsContinuableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.DoStatement: case SyntaxKind.WhileStatement: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return true; } return false; } public static bool IsReturnableConstruct(this SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.LocalFunctionStatement: case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; } return false; } public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list); [return: NotNullIfNotNull("node")] public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false) where TNode : SyntaxNode { if (node == null) { return node; } var rewriter = new SingleLineRewriter(useElasticTrivia); return (TNode)rewriter.Visit(node); } /// <summary> /// Returns true if the passed in node contains an interleaved pp directive. /// /// i.e. The following returns false: /// /// void Goo() { /// #if true /// #endif /// } /// /// #if true /// void Goo() { /// } /// #endif /// /// but these return true: /// /// #if true /// void Goo() { /// #endif /// } /// /// void Goo() { /// #if true /// } /// #endif /// /// #if true /// void Goo() { /// #else /// } /// #endif /// /// i.e. the method returns true if it contains a PP directive that belongs to a grouping /// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't /// entirely contained within the span of the node. /// </summary> public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken) => CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken); /// <summary> /// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check /// for interleaved directives can be specified separately to the node passed in. /// </summary> public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken) => CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken); public static bool ContainsInterleavedDirective( this SyntaxToken token, TextSpan textSpan, CancellationToken cancellationToken) { return ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) || ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken); } private static bool ContainsInterleavedDirective( TextSpan textSpan, SyntaxTriviaList list, CancellationToken cancellationToken) { foreach (var trivia in list) { if (textSpan.Contains(trivia.Span)) { if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken)) { return true; } } } return false; } private static bool ContainsInterleavedDirective( TextSpan textSpan, SyntaxTrivia trivia, CancellationToken cancellationToken) { if (trivia.HasStructure) { var structure = trivia.GetStructure()!; if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia, SyntaxKind.EndRegionDirectiveTrivia, SyntaxKind.IfDirectiveTrivia, SyntaxKind.EndIfDirectiveTrivia)) { var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken); if (match != null) { var matchSpan = match.Span; if (!textSpan.Contains(matchSpan.Start)) { // The match for this pp directive is outside // this node. return true; } } } else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia)) { var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken); if (directives != null && directives.Count > 0) { if (!textSpan.Contains(directives[0].SpanStart) || !textSpan.Contains(directives[directives.Count - 1].SpanStart)) { // This else/elif belongs to a pp span that isn't // entirely within this node. return true; } } } } return false; } /// <summary> /// Breaks up the list of provided nodes, based on how they are interspersed with pp /// directives, into groups. Within these groups nodes can be moved around safely, without /// breaking any pp constructs. /// </summary> public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>( this IEnumerable<TSyntaxNode> nodes, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var result = new List<IList<TSyntaxNode>>(); var currentGroup = new List<TSyntaxNode>(); foreach (var node in nodes) { var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken); var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind())); if (hasUnmatchedInteriorDirective) { // we have a #if/#endif/#region/#endregion/#else/#elif in // this node that belongs to a span of pp directives that // is not entirely contained within the node. i.e.: // // void Goo() { // #if ... // } // // This node cannot be moved at all. It is in a group that // only contains itself (and thus can never be moved). // add whatever group we've built up to now. And reset the // next group to empty. result.Add(currentGroup); currentGroup = new List<TSyntaxNode>(); result.Add(new List<TSyntaxNode> { node }); } else if (hasLeadingDirective) { // We have a PP directive before us. i.e.: // // #if ... // void Goo() { // // That means we start a new group that is contained between // the above directive and the following directive. // add whatever group we've built up to now. And reset the // next group to empty. result.Add(currentGroup); currentGroup = new List<TSyntaxNode>(); currentGroup.Add(node); } else { // simple case. just add ourselves to the current group currentGroup.Add(node); } } // add the remainder of the final group. result.Add(currentGroup); // Now, filter out any empty groups. result = result.Where(group => !group.IsEmpty()).ToList(); return result; } public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node); public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node); public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia); public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node); public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node); public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode => CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia); public static bool IsVariableDeclaratorValue(this SyntaxNode node) => node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) && equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) && equalsValue.Value == node; public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode<BlockSyntax>(); public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate) { var current = node; while (current != null) { if (predicate(current)) { yield return current; } current = current.Parent; } } /// <summary> /// Returns child node or token that contains given position. /// </summary> /// <remarks> /// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node. /// </remarks> internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex) { var childList = self.ChildNodesAndTokens(); var left = 0; var right = childList.Count - 1; while (left <= right) { var middle = left + ((right - left) / 2); var node = childList[middle]; var span = node.FullSpan; if (position < span.Start) { right = middle - 1; } else if (position >= span.End) { left = middle + 1; } else { childIndex = middle; return node; } } // we could check up front that index is within FullSpan, // but we wan to optimize for the common case where position is valid. Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?"); throw new ArgumentOutOfRangeException(nameof(position)); } public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node) { switch (node) { case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken); case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken); case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken); case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken); case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken); case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken); default: return default; } } public static (SyntaxToken openBracket, SyntaxToken closeBracket) GetBrackets(this SyntaxNode node) { switch (node) { case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken); default: return default; } } public static SyntaxTokenList GetModifiers(this SyntaxNode? member) { switch (member) { case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers; case AccessorDeclarationSyntax accessor: return accessor.Modifiers; case AnonymousFunctionExpressionSyntax anonymous: return anonymous.Modifiers; case LocalFunctionStatementSyntax localFunction: return localFunction.Modifiers; case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.Modifiers; } return default; } public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers) { switch (member) { case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers); case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers); case AnonymousFunctionExpressionSyntax anonymous: return anonymous.WithModifiers(modifiers); case LocalFunctionStatementSyntax localFunction: return localFunction.WithModifiers(modifiers); case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.WithModifiers(modifiers); } return null; } public static bool CheckTopLevel(this SyntaxNode node, TextSpan span) { switch (node) { case BlockSyntax block: return block.ContainsInBlockBody(span); case ArrowExpressionClauseSyntax expressionBodiedMember: return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span); case FieldDeclarationSyntax field: { foreach (var variable in field.Declaration.Variables) { if (variable.Initializer != null && variable.Initializer.Span.Contains(span)) { return true; } } break; } case GlobalStatementSyntax _: return true; case ConstructorInitializerSyntax constructorInitializer: return constructorInitializer.ContainsInArgument(span); } return false; } public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan) { if (initializer == null) { return false; } return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan)); } public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan) { if (block == null) { return false; } var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart); return blockSpan.Contains(textSpan); } public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan) { if (expressionBodiedMember == null) { return false; } var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End); return expressionBodiedMemberBody.Contains(textSpan); } public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node) { switch (node) { case CompilationUnitSyntax compilation: return compilation.Members; case BaseNamespaceDeclarationSyntax @namespace: return @namespace.Members; case TypeDeclarationSyntax type: return type.Members; case EnumDeclarationSyntax @enum: return @enum.Members; } return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>(); } public static bool IsInExpressionTree( [NotNullWhen(returnValue: true)] this SyntaxNode? node, SemanticModel semanticModel, [NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken) { if (expressionTypeOpt != null) { for (var current = node; current != null; current = current.Parent) { if (current.IsAnyLambda()) { var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken); if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition)) return true; } else if (current is SelectOrGroupClauseSyntax || current is OrderingSyntax) { var info = semanticModel.GetSymbolInfo(current, cancellationToken); if (TakesExpressionTree(info, expressionTypeOpt)) return true; } else if (current is QueryClauseSyntax queryClause) { var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken); if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) || TakesExpressionTree(info.OperationInfo, expressionTypeOpt)) { return true; } } } } return false; static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType) { foreach (var symbol in info.GetAllSymbols()) { if (symbol is IMethodSymbol method && method.Parameters.Length > 0 && expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition)) { return true; } } return false; } } public static bool IsInDeconstructionLeft( [NotNullWhen(returnValue: true)] this SyntaxNode? node, [NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft) { SyntaxNode? previous = null; for (var current = node; current != null; current = current.Parent) { if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) || (current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable)) { deconstructionLeft = previous; return true; } if (current is StatementSyntax) { break; } previous = current; } deconstructionLeft = null; return false; } public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node) => node switch { { Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true, { Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true, _ => false }; public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken) where T : SyntaxNode => node.WithCommentsFrom( SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken), SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken)); public static T WithCommentsFrom<T>( this T node, IEnumerable<SyntaxToken> leadingTokens, IEnumerable<SyntaxToken> trailingTokens) where T : SyntaxNode => node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia()); public static T WithCommentsFrom<T>( this T node, IEnumerable<SyntaxTrivia> leadingTrivia, IEnumerable<SyntaxTrivia> trailingTrivia, params SyntaxNodeOrToken[] trailingNodesOrTokens) where T : SyntaxNode => node .WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false)) .WithTrailingTrivia( node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false)); public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode => node .WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true)) .WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: true)); } }
1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/CSharp/Impl/Snippets/SnippetFunctions/SnippetFunctionSimpleTypeName.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionSimpleTypeName : AbstractSnippetFunctionSimpleTypeName { public SnippetFunctionSimpleTypeName(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName) : base(snippetExpansionClient, subjectBuffer, fieldName, fullyQualifiedName) { } protected override bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var syntaxRoot = documentWithFullyQualifiedTypeName.GetSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == updatedTextSpan); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithFullyQualifiedTypeName.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); simplifiedTypeName = simplifiedDocument.GetSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.Snippets.SnippetFunctions; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Snippets.SnippetFunctions { internal sealed class SnippetFunctionSimpleTypeName : AbstractSnippetFunctionSimpleTypeName { public SnippetFunctionSimpleTypeName(SnippetExpansionClient snippetExpansionClient, ITextBuffer subjectBuffer, string fieldName, string fullyQualifiedName) : base(snippetExpansionClient, subjectBuffer, fieldName, fullyQualifiedName) { } protected override bool TryGetSimplifiedTypeName(Document documentWithFullyQualifiedTypeName, TextSpan updatedTextSpan, CancellationToken cancellationToken, out string simplifiedTypeName) { simplifiedTypeName = string.Empty; var typeAnnotation = new SyntaxAnnotation(); var syntaxRoot = documentWithFullyQualifiedTypeName.GetSyntaxRootSynchronously(cancellationToken); var nodeToReplace = syntaxRoot.DescendantNodes().FirstOrDefault(n => n.Span == updatedTextSpan); if (nodeToReplace == null) { return false; } var updatedRoot = syntaxRoot.ReplaceNode(nodeToReplace, nodeToReplace.WithAdditionalAnnotations(typeAnnotation, Simplifier.Annotation)); var documentWithAnnotations = documentWithFullyQualifiedTypeName.WithSyntaxRoot(updatedRoot); var simplifiedDocument = Simplifier.ReduceAsync(documentWithAnnotations, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken); simplifiedTypeName = simplifiedDocument.GetSyntaxRootSynchronously(cancellationToken).GetAnnotatedNodesAndTokens(typeAnnotation).Single().ToString(); return true; } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Lsif/Generator/Writing/LineModeLsifJsonWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { /// <summary> /// An <see cref="ILsifJsonWriter"/> that writes in <see cref="LsifFormat.Line"/>. /// </summary> internal sealed partial class LineModeLsifJsonWriter : ILsifJsonWriter { private readonly object _writeGate = new object(); private readonly TextWriter _outputWriter; private readonly JsonSerializerSettings _settings; public LineModeLsifJsonWriter(TextWriter outputWriter) { _settings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.None, NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), TypeNameHandling = TypeNameHandling.None, Converters = new[] { new LsifConverter() } }; _outputWriter = outputWriter; } public void Write(Element element) { var line = JsonConvert.SerializeObject(element, _settings); lock (_writeGate) { _outputWriter.WriteLine(line); } } public void WriteAll(List<Element> elements) { var lines = new List<string>(); foreach (var element in elements) lines.Add(JsonConvert.SerializeObject(element, _settings)); lock (_writeGate) { foreach (var line in lines) _outputWriter.WriteLine(line); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Graph; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.Writing { /// <summary> /// An <see cref="ILsifJsonWriter"/> that writes in <see cref="LsifFormat.Line"/>. /// </summary> internal sealed partial class LineModeLsifJsonWriter : ILsifJsonWriter { private readonly object _writeGate = new object(); private readonly TextWriter _outputWriter; private readonly JsonSerializerSettings _settings; public LineModeLsifJsonWriter(TextWriter outputWriter) { _settings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.None, NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver(), TypeNameHandling = TypeNameHandling.None, Converters = new[] { new LsifConverter() } }; _outputWriter = outputWriter; } public void Write(Element element) { var line = JsonConvert.SerializeObject(element, _settings); lock (_writeGate) { _outputWriter.WriteLine(line); } } public void WriteAll(List<Element> elements) { var lines = new List<string>(); foreach (var element in elements) lines.Add(JsonConvert.SerializeObject(element, _settings)); lock (_writeGate) { foreach (var line in lines) _outputWriter.WriteLine(line); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/CustomEventKeywordRecommenderTests.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 Public Class CustomEventKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CustomEventInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Custom Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CustomEventInStructureDeclarationTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Custom Event") End Sub <Fact> <WorkItem(544999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544999")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CustomEventNotInInterfaceDeclarationTest() VerifyRecommendationsMissing(<InterfaceDeclaration>|</InterfaceDeclaration>, "Custom Event") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Custom Event") 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 Public Class CustomEventKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CustomEventInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Custom Event") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CustomEventInStructureDeclarationTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Custom Event") End Sub <Fact> <WorkItem(544999, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544999")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub CustomEventNotInInterfaceDeclarationTest() VerifyRecommendationsMissing(<InterfaceDeclaration>|</InterfaceDeclaration>, "Custom Event") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Custom Event") End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/VisualBasic/Portable/CodeRefactorings/AddAwait/VisualBasicAddAwaitCodeRefactoringProvider.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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.AddAwait Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.AddAwait <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddAwait), [Shared]> Friend Class VisualBasicAddAwaitCodeRefactoringProvider Inherits AbstractAddAwaitCodeRefactoringProvider(Of ExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Add_Await End Function Protected Overrides Function GetTitleWithConfigureAwait() As String Return VBFeaturesResources.Add_Await_and_ConfigureAwaitFalse End Function Protected Overrides Function IsInAsyncContext(node As SyntaxNode) As Boolean For Each current In node.Ancestors() Select Case current.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(current, LambdaExpressionSyntax).SubOrFunctionHeader.Modifiers.Any(SyntaxKind.AsyncKeyword) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(current, MethodBlockBaseSyntax).BlockStatement.Modifiers.Any(SyntaxKind.AsyncKeyword) End Select Next Return 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.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeRefactorings.AddAwait Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.AddAwait <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.AddAwait), [Shared]> Friend Class VisualBasicAddAwaitCodeRefactoringProvider Inherits AbstractAddAwaitCodeRefactoringProvider(Of ExpressionSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Add_Await End Function Protected Overrides Function GetTitleWithConfigureAwait() As String Return VBFeaturesResources.Add_Await_and_ConfigureAwaitFalse End Function Protected Overrides Function IsInAsyncContext(node As SyntaxNode) As Boolean For Each current In node.Ancestors() Select Case current.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression Return DirectCast(current, LambdaExpressionSyntax).SubOrFunctionHeader.Modifiers.Any(SyntaxKind.AsyncKeyword) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(current, MethodBlockBaseSyntax).BlockStatement.Modifiers.Any(SyntaxKind.AsyncKeyword) End Select Next Return False End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/Interop/ICodeElements.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; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { /// <summary> /// A redefinition of the EnvDTE.CodeElements interface. The interface, as defined in the PIA does not do /// PreserveSig for the Item function. WinForms, specifically, uses the Item property when generating methods to see /// if a method already exists. The only way it sees if something exists is if the call returns E_INVALIDARG. With /// the normal PIAs though, this would result in a first-chance exception. Therefore, the WinForms team has their /// own definition for CodeElements which also [PreserveSig]s Item. We do this here to make their work still /// worthwhile. /// </summary> [ComImport] [Guid("0CFBC2B5-0D4E-11D3-8997-00C04F688DDE")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] internal interface ICodeElements : IEnumerable { [DispId(-4)] [TypeLibFunc(TypeLibFuncFlags.FRestricted)] new IEnumerator GetEnumerator(); [DispId(1)] EnvDTE.DTE DTE { [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(2)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0)] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int Item(object index, [MarshalAs(UnmanagedType.Interface)] out EnvDTE.CodeElement element); [DispId(3)] int Count { get; } [TypeLibFunc(TypeLibFuncFlags.FHidden | TypeLibFuncFlags.FRestricted)] [DispId(4)] void Reserved1(object element); [DispId(5)] bool CreateUniqueID([MarshalAs(UnmanagedType.BStr)] string prefix, [MarshalAs(UnmanagedType.BStr)] ref string newName); } }
// Licensed to the .NET Foundation under one or more 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; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop { /// <summary> /// A redefinition of the EnvDTE.CodeElements interface. The interface, as defined in the PIA does not do /// PreserveSig for the Item function. WinForms, specifically, uses the Item property when generating methods to see /// if a method already exists. The only way it sees if something exists is if the call returns E_INVALIDARG. With /// the normal PIAs though, this would result in a first-chance exception. Therefore, the WinForms team has their /// own definition for CodeElements which also [PreserveSig]s Item. We do this here to make their work still /// worthwhile. /// </summary> [ComImport] [Guid("0CFBC2B5-0D4E-11D3-8997-00C04F688DDE")] [InterfaceType(ComInterfaceType.InterfaceIsDual)] internal interface ICodeElements : IEnumerable { [DispId(-4)] [TypeLibFunc(TypeLibFuncFlags.FRestricted)] new IEnumerator GetEnumerator(); [DispId(1)] EnvDTE.DTE DTE { [return: MarshalAs(UnmanagedType.Interface)] get; } [DispId(2)] object Parent { [return: MarshalAs(UnmanagedType.IDispatch)] get; } [DispId(0)] [PreserveSig] [return: MarshalAs(UnmanagedType.Error)] int Item(object index, [MarshalAs(UnmanagedType.Interface)] out EnvDTE.CodeElement element); [DispId(3)] int Count { get; } [TypeLibFunc(TypeLibFuncFlags.FHidden | TypeLibFuncFlags.FRestricted)] [DispId(4)] void Reserved1(object element); [DispId(5)] bool CreateUniqueID([MarshalAs(UnmanagedType.BStr)] string prefix, [MarshalAs(UnmanagedType.BStr)] ref string newName); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/AbstractMethodXmlBuilder.AttributeInfo.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.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == 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 namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal abstract partial class AbstractMethodXmlBuilder { private struct AttributeInfo { public static readonly AttributeInfo Empty = new AttributeInfo(); public readonly string Name; public readonly string Value; public AttributeInfo(string name, string value) { this.Name = name; this.Value = value; } public bool IsEmpty { get { return this.Name == null && this.Value == null; } } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/DirectiveTriviaSyntax.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class DirectiveTriviaSyntax { internal override DirectiveStack ApplyDirectives(DirectiveStack stack) { return stack.Add(new Directive(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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax { internal partial class DirectiveTriviaSyntax { internal override DirectiveStack ApplyDirectives(DirectiveStack stack) { return stack.Add(new Directive(this)); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/SymbolsTests/RetargetingCycle/V1/ClassB.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. ' vbc ClassB.vb /target:module /vbruntime- /r:ClassA.dll Public Class ClassB Inherits ClassA End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. ' vbc ClassB.vb /target:module /vbruntime- /r:ClassA.dll Public Class ClassB Inherits ClassA End Class
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SyntaxTokenExtensions.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.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Partial Friend Module SyntaxTokenExtensions <Extension()> Public Function IsKind(token As SyntaxToken, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean Return token.Kind = kind1 OrElse token.Kind = kind2 End Function <Extension()> Public Function IsKind(token As SyntaxToken, ParamArray kinds As SyntaxKind()) As Boolean Return kinds.Contains(token.Kind) End Function <Extension()> Public Function IsKindOrHasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean Return token.Kind = kind OrElse token.HasMatchingText(kind) End Function <Extension()> Public Function HasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean Return String.Equals(token.ToString(), SyntaxFacts.GetText(kind), StringComparison.OrdinalIgnoreCase) End Function <Extension()> Public Function IsCharacterLiteral(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.CharacterLiteralToken End Function <Extension()> Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Return _ token.Kind = SyntaxKind.DateLiteralToken OrElse token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function <Extension()> Public Function IsNewOnRightSideOfDotOrBang(token As SyntaxToken) As Boolean Dim expression = TryCast(token.Parent, ExpressionSyntax) Return If(expression IsNot Nothing, expression.IsNewOnRightSideOfDotOrBang(), False) End Function <Extension()> Public Function IsSkipped(token As SyntaxToken) As Boolean Return TypeOf token.Parent Is SkippedTokensTriviaSyntax End Function <Extension()> Public Function FirstAncestorOrSelf(token As SyntaxToken, predicate As Func(Of SyntaxNode, Boolean)) As SyntaxNode Return token.Parent.FirstAncestorOrSelf(predicate) End Function <Extension()> Public Function HasAncestor(Of T As SyntaxNode)(token As SyntaxToken) As Boolean Return token.GetAncestor(Of T)() IsNot Nothing End Function ''' <summary> ''' Returns true if is a given token is a child token of a certain type of parent node. ''' </summary> ''' <typeparam name="TParent">The type of the parent node.</typeparam> ''' <param name="token">The token that we are testing.</param> ''' <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param> <Extension()> Public Function IsChildToken(Of TParent As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SyntaxToken)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Dim ancestorToken = childGetter(ancestor) Return token = ancestorToken End Function ''' <summary> ''' Returns true if is a given token is a separator token in a given parent list. ''' </summary> ''' <typeparam name="TParent">The type of the parent node containing the separated list.</typeparam> ''' <param name="token">The token that we are testing.</param> ''' <param name="childGetter">A function that, when given the parent node, returns the separated list.</param> <Extension()> Public Function IsChildSeparatorToken(Of TParent As SyntaxNode, TChild As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SeparatedSyntaxList(Of TChild))) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Dim separatedList = childGetter(ancestor) For i = 0 To separatedList.SeparatorCount - 1 If separatedList.GetSeparator(i) = token Then Return True End If Next Return False End Function <Extension> Public Function IsDescendantOf(token As SyntaxToken, node As SyntaxNode) As Boolean Return token.Parent IsNot Nothing AndAlso token.Parent.AncestorsAndSelf().Any(Function(n) n Is node) End Function <Extension()> Friend Function GetInnermostDeclarationContext(node As SyntaxToken) As SyntaxNode Dim ancestors = node.GetAncestors(Of SyntaxNode) ' In error cases where the declaration is not complete, the parser attaches the incomplete token to the ' trailing trivia of preceding block. In such cases, skip through the siblings and search upwards to find a candidate ancestor. If TypeOf ancestors.FirstOrDefault() Is EndBlockStatementSyntax Then ' If the first ancestor is an EndBlock, the second is the matching OpenBlock, if one exists Dim openBlock = ancestors.ElementAtOrDefault(1) Dim closeTypeBlock = DirectCast(ancestors.First(), EndBlockStatementSyntax) If openBlock Is Nothing Then ' case: No matching open block ' End Class ' C| ancestors = ancestors.Skip(1) ElseIf TypeOf openBlock Is TypeBlockSyntax Then ancestors = FilterAncestors(ancestors, DirectCast(openBlock, TypeBlockSyntax).EndBlockStatement, closeTypeBlock) ElseIf TypeOf openBlock Is NamespaceBlockSyntax Then ancestors = FilterAncestors(ancestors, DirectCast(openBlock, NamespaceBlockSyntax).EndNamespaceStatement, closeTypeBlock) ElseIf TypeOf openBlock Is EnumBlockSyntax Then ancestors = FilterAncestors(ancestors, DirectCast(openBlock, EnumBlockSyntax).EndEnumStatement, closeTypeBlock) End If End If Return ancestors.FirstOrDefault( Function(ancestor) ancestor.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.EnumBlock, SyntaxKind.InterfaceBlock, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.CompilationUnit)) End Function Private Function FilterAncestors(ancestors As IEnumerable(Of SyntaxNode), parentEndBlock As EndBlockStatementSyntax, precedingEndBlock As EndBlockStatementSyntax) As IEnumerable(Of SyntaxNode) If parentEndBlock.Equals(precedingEndBlock) Then ' case: the preceding end block has a matching open block and the declaration context for 'C' is 'N1' ' Namespace N1 ' Class C1 ' ' End Class ' C| ' End Namespace Return ancestors.Skip(2) Else ' case: mismatched end block and the declaration context for 'C' is 'N1' ' Namespace N1 ' End Class ' C| ' End Namespace Return ancestors.Skip(1) End If End Function <Extension()> Public Function GetContainingMember(token As SyntaxToken) As DeclarationStatementSyntax Return token.GetAncestors(Of DeclarationStatementSyntax) _ .FirstOrDefault(Function(a) Return a.IsMemberDeclaration() OrElse (a.IsMemberBlock() AndAlso a.GetMemberBlockBegin().IsMemberDeclaration()) End Function) End Function <Extension()> Public Function GetContainingMemberBlockBegin(token As SyntaxToken) As StatementSyntax Return token.GetContainingMember().GetMemberBlockBegin() End Function ''' <summary> ''' Determines whether the given SyntaxToken is the first token on a line ''' </summary> <Extension()> Public Function IsFirstTokenOnLine(token As SyntaxToken) As Boolean Dim previousToken = token.GetPreviousToken(includeSkipped:=True, includeDirectives:=True, includeDocumentationComments:=True) If previousToken.Kind = SyntaxKind.None Then Return True End If Dim text = token.SyntaxTree.GetText() Dim tokenLine = text.Lines.IndexOf(token.SpanStart) Dim previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart) Return tokenLine > previousTokenLine End Function <Extension()> Public Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return VisualBasicSyntaxFacts.Instance.SpansPreprocessorDirective(tokens) End Function <Extension()> Public Function GetPreviousTokenIfTouchingWord(token As SyntaxToken, position As Integer) As SyntaxToken Return If(token.IntersectsWith(position) AndAlso IsWord(token), token.GetPreviousToken(includeSkipped:=True), token) End Function <Extension> Public Function IsWord(token As SyntaxToken) As Boolean Return VisualBasicSyntaxFacts.Instance.IsWord(token) End Function <Extension()> Public Function IntersectsWith(token As SyntaxToken, position As Integer) As Boolean Return token.Span.IntersectsWith(position) End Function <Extension()> Public Function GetNextNonZeroWidthTokenOrEndOfFile(token As SyntaxToken) As SyntaxToken Dim nextToken = token.GetNextToken() Return If(nextToken.Kind = SyntaxKind.None, token.GetAncestor(Of CompilationUnitSyntax)().EndOfFileToken, nextToken) End Function <Extension> Public Function IsValidAttributeTarget(token As SyntaxToken) As Boolean Return token.Kind() = SyntaxKind.AssemblyKeyword OrElse token.Kind() = SyntaxKind.ModuleKeyword 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.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions Partial Friend Module SyntaxTokenExtensions <Extension()> Public Function IsKind(token As SyntaxToken, kind1 As SyntaxKind, kind2 As SyntaxKind) As Boolean Return token.Kind = kind1 OrElse token.Kind = kind2 End Function <Extension()> Public Function IsKind(token As SyntaxToken, ParamArray kinds As SyntaxKind()) As Boolean Return kinds.Contains(token.Kind) End Function <Extension()> Public Function IsKindOrHasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean Return token.Kind = kind OrElse token.HasMatchingText(kind) End Function <Extension()> Public Function HasMatchingText(token As SyntaxToken, kind As SyntaxKind) As Boolean Return String.Equals(token.ToString(), SyntaxFacts.GetText(kind), StringComparison.OrdinalIgnoreCase) End Function <Extension()> Public Function IsCharacterLiteral(token As SyntaxToken) As Boolean Return token.Kind = SyntaxKind.CharacterLiteralToken End Function <Extension()> Public Function IsNumericLiteral(token As SyntaxToken) As Boolean Return _ token.Kind = SyntaxKind.DateLiteralToken OrElse token.Kind = SyntaxKind.DecimalLiteralToken OrElse token.Kind = SyntaxKind.FloatingLiteralToken OrElse token.Kind = SyntaxKind.IntegerLiteralToken End Function <Extension()> Public Function IsNewOnRightSideOfDotOrBang(token As SyntaxToken) As Boolean Dim expression = TryCast(token.Parent, ExpressionSyntax) Return If(expression IsNot Nothing, expression.IsNewOnRightSideOfDotOrBang(), False) End Function <Extension()> Public Function IsSkipped(token As SyntaxToken) As Boolean Return TypeOf token.Parent Is SkippedTokensTriviaSyntax End Function <Extension()> Public Function FirstAncestorOrSelf(token As SyntaxToken, predicate As Func(Of SyntaxNode, Boolean)) As SyntaxNode Return token.Parent.FirstAncestorOrSelf(predicate) End Function <Extension()> Public Function HasAncestor(Of T As SyntaxNode)(token As SyntaxToken) As Boolean Return token.GetAncestor(Of T)() IsNot Nothing End Function ''' <summary> ''' Returns true if is a given token is a child token of a certain type of parent node. ''' </summary> ''' <typeparam name="TParent">The type of the parent node.</typeparam> ''' <param name="token">The token that we are testing.</param> ''' <param name="childGetter">A function that, when given the parent node, returns the child token we are interested in.</param> <Extension()> Public Function IsChildToken(Of TParent As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SyntaxToken)) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Dim ancestorToken = childGetter(ancestor) Return token = ancestorToken End Function ''' <summary> ''' Returns true if is a given token is a separator token in a given parent list. ''' </summary> ''' <typeparam name="TParent">The type of the parent node containing the separated list.</typeparam> ''' <param name="token">The token that we are testing.</param> ''' <param name="childGetter">A function that, when given the parent node, returns the separated list.</param> <Extension()> Public Function IsChildSeparatorToken(Of TParent As SyntaxNode, TChild As SyntaxNode)(token As SyntaxToken, childGetter As Func(Of TParent, SeparatedSyntaxList(Of TChild))) As Boolean Dim ancestor = token.GetAncestor(Of TParent)() If ancestor Is Nothing Then Return False End If Dim separatedList = childGetter(ancestor) For i = 0 To separatedList.SeparatorCount - 1 If separatedList.GetSeparator(i) = token Then Return True End If Next Return False End Function <Extension> Public Function IsDescendantOf(token As SyntaxToken, node As SyntaxNode) As Boolean Return token.Parent IsNot Nothing AndAlso token.Parent.AncestorsAndSelf().Any(Function(n) n Is node) End Function <Extension()> Friend Function GetInnermostDeclarationContext(node As SyntaxToken) As SyntaxNode Dim ancestors = node.GetAncestors(Of SyntaxNode) ' In error cases where the declaration is not complete, the parser attaches the incomplete token to the ' trailing trivia of preceding block. In such cases, skip through the siblings and search upwards to find a candidate ancestor. If TypeOf ancestors.FirstOrDefault() Is EndBlockStatementSyntax Then ' If the first ancestor is an EndBlock, the second is the matching OpenBlock, if one exists Dim openBlock = ancestors.ElementAtOrDefault(1) Dim closeTypeBlock = DirectCast(ancestors.First(), EndBlockStatementSyntax) If openBlock Is Nothing Then ' case: No matching open block ' End Class ' C| ancestors = ancestors.Skip(1) ElseIf TypeOf openBlock Is TypeBlockSyntax Then ancestors = FilterAncestors(ancestors, DirectCast(openBlock, TypeBlockSyntax).EndBlockStatement, closeTypeBlock) ElseIf TypeOf openBlock Is NamespaceBlockSyntax Then ancestors = FilterAncestors(ancestors, DirectCast(openBlock, NamespaceBlockSyntax).EndNamespaceStatement, closeTypeBlock) ElseIf TypeOf openBlock Is EnumBlockSyntax Then ancestors = FilterAncestors(ancestors, DirectCast(openBlock, EnumBlockSyntax).EndEnumStatement, closeTypeBlock) End If End If Return ancestors.FirstOrDefault( Function(ancestor) ancestor.IsKind(SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.EnumBlock, SyntaxKind.InterfaceBlock, SyntaxKind.NamespaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.CompilationUnit)) End Function Private Function FilterAncestors(ancestors As IEnumerable(Of SyntaxNode), parentEndBlock As EndBlockStatementSyntax, precedingEndBlock As EndBlockStatementSyntax) As IEnumerable(Of SyntaxNode) If parentEndBlock.Equals(precedingEndBlock) Then ' case: the preceding end block has a matching open block and the declaration context for 'C' is 'N1' ' Namespace N1 ' Class C1 ' ' End Class ' C| ' End Namespace Return ancestors.Skip(2) Else ' case: mismatched end block and the declaration context for 'C' is 'N1' ' Namespace N1 ' End Class ' C| ' End Namespace Return ancestors.Skip(1) End If End Function <Extension()> Public Function GetContainingMember(token As SyntaxToken) As DeclarationStatementSyntax Return token.GetAncestors(Of DeclarationStatementSyntax) _ .FirstOrDefault(Function(a) Return a.IsMemberDeclaration() OrElse (a.IsMemberBlock() AndAlso a.GetMemberBlockBegin().IsMemberDeclaration()) End Function) End Function <Extension()> Public Function GetContainingMemberBlockBegin(token As SyntaxToken) As StatementSyntax Return token.GetContainingMember().GetMemberBlockBegin() End Function ''' <summary> ''' Determines whether the given SyntaxToken is the first token on a line ''' </summary> <Extension()> Public Function IsFirstTokenOnLine(token As SyntaxToken) As Boolean Dim previousToken = token.GetPreviousToken(includeSkipped:=True, includeDirectives:=True, includeDocumentationComments:=True) If previousToken.Kind = SyntaxKind.None Then Return True End If Dim text = token.SyntaxTree.GetText() Dim tokenLine = text.Lines.IndexOf(token.SpanStart) Dim previousTokenLine = text.Lines.IndexOf(previousToken.SpanStart) Return tokenLine > previousTokenLine End Function <Extension()> Public Function SpansPreprocessorDirective(tokens As IEnumerable(Of SyntaxToken)) As Boolean Return VisualBasicSyntaxFacts.Instance.SpansPreprocessorDirective(tokens) End Function <Extension()> Public Function GetPreviousTokenIfTouchingWord(token As SyntaxToken, position As Integer) As SyntaxToken Return If(token.IntersectsWith(position) AndAlso IsWord(token), token.GetPreviousToken(includeSkipped:=True), token) End Function <Extension> Public Function IsWord(token As SyntaxToken) As Boolean Return VisualBasicSyntaxFacts.Instance.IsWord(token) End Function <Extension()> Public Function IntersectsWith(token As SyntaxToken, position As Integer) As Boolean Return token.Span.IntersectsWith(position) End Function <Extension()> Public Function GetNextNonZeroWidthTokenOrEndOfFile(token As SyntaxToken) As SyntaxToken Dim nextToken = token.GetNextToken() Return If(nextToken.Kind = SyntaxKind.None, token.GetAncestor(Of CompilationUnitSyntax)().EndOfFileToken, nextToken) End Function <Extension> Public Function IsValidAttributeTarget(token As SyntaxToken) As Boolean Return token.Kind() = SyntaxKind.AssemblyKeyword OrElse token.Kind() = SyntaxKind.ModuleKeyword End Function End Module End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/KeywordHighlighting/YieldStatementHighlighterTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class YieldStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(YieldStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { {|Cursor:[|yield break|];|} } [|yield return|] min++; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { [|yield break|]; } {|Cursor:[|yield return|]|} min++; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_3() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { yield break; } yield return {|Cursor:min++|}; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_4() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { [|yield break|]; } [|yield return|] min++;{|Cursor:|} } } }"); } } }
// Licensed to the .NET Foundation under one or more 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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting { public class YieldStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests { internal override Type GetHighlighterType() => typeof(YieldStatementHighlighter); [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_1() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { {|Cursor:[|yield break|];|} } [|yield return|] min++; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_2() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { [|yield break|]; } {|Cursor:[|yield return|]|} min++; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_3() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { yield break; } yield return {|Cursor:min++|}; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)] public async Task TestExample1_4() { await TestAsync( @"class C { IEnumerable<int> Range(int min, int max) { while (true) { if (min >= max) { [|yield break|]; } [|yield return|] min++;{|Cursor:|} } } }"); } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/CSharpTest/ObjectFormatterTests.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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using ObjectFormatterFixtures; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class ObjectFormatterTests : ObjectFormatterTestBase { private static readonly TestCSharpObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void Objects() { string str; object nested = new Outer.Nested<int>(); str = s_formatter.FormatObject(nested, SingleLineOptions); Assert.Equal(@"Outer.Nested<int> { A=1, B=2 }", str); str = s_formatter.FormatObject(nested, HiddenOptions); Assert.Equal(@"Outer.Nested<int>", str); str = s_formatter.FormatObject(A<int>.X, HiddenOptions); Assert.Equal(@"A<int>.B<int>", str); object obj = new A<int>.B<bool>.C.D<string, double>.E(); str = s_formatter.FormatObject(obj, HiddenOptions); Assert.Equal(@"A<int>.B<bool>.C.D<string, double>.E", str); var sort = new Sort(); str = new TestCSharpObjectFormatter(maximumLineLength: 51).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1...", str); Assert.Equal(51 + 3, str.Length); str = new TestCSharpObjectFormatter(maximumLineLength: 5).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort ...", str); Assert.Equal(5 + 3, str.Length); str = new TestCSharpObjectFormatter(maximumLineLength: 4).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 3).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sor...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 2).FormatObject(sort, SingleLineOptions); Assert.Equal(@"So...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 1).FormatObject(sort, SingleLineOptions); Assert.Equal(@"S...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 80).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1, AG=1 }", str); } [Fact] public void TupleType() { var tup = new Tuple<int, int>(1, 2); Assert.Equal("(1, 2)", s_formatter.FormatObject(tup)); } [Fact] public void ValueTupleType() { (int, int) tup = (1, 2); Assert.Equal("(1, 2)", s_formatter.FormatObject(tup)); } [Fact] public void ArrayMethodParameters() { var result = s_formatter.FormatMethodSignature(Signatures.Arrays); Assert.Equal("ObjectFormatterFixtures.Signatures.ArrayParameters(int[], int[,], int[,,])", result); } [Fact] public void ArrayOfInt32_NoMembers() { object o = new int[4] { 3, 4, 5, 6 }; var str = s_formatter.FormatObject(o, HiddenOptions); Assert.Equal("int[4] { 3, 4, 5, 6 }", str); } #region DANGER: Debugging this method under VS2010 might freeze your machine. [Fact] public void RecursiveRootHidden() { var DO_NOT_ADD_TO_WATCH_WINDOW = new RecursiveRootHidden(); DO_NOT_ADD_TO_WATCH_WINDOW.C = DO_NOT_ADD_TO_WATCH_WINDOW; string str = s_formatter.FormatObject(DO_NOT_ADD_TO_WATCH_WINDOW, SingleLineOptions); Assert.Equal(@"RecursiveRootHidden { A=0, B=0 }", str); } #endregion [Fact] public void DebuggerDisplay_ParseSimpleMemberName() { Test_ParseSimpleMemberName("goo", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName("goo ", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName(" goo", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName(" goo ", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName("goo()", name: "goo", callable: true, nq: false); Test_ParseSimpleMemberName("\ngoo (\r\n)", name: "goo", callable: true, nq: false); Test_ParseSimpleMemberName(" goo ( \t) ", name: "goo", callable: true, nq: false); Test_ParseSimpleMemberName("goo,nq", name: "goo", callable: false, nq: true); Test_ParseSimpleMemberName("goo ,nq", name: "goo", callable: false, nq: true); Test_ParseSimpleMemberName("goo(),nq", name: "goo", callable: true, nq: true); Test_ParseSimpleMemberName(" goo \t( ) ,nq", name: "goo", callable: true, nq: true); Test_ParseSimpleMemberName(" goo \t( ) , nq", name: "goo", callable: true, nq: true); Test_ParseSimpleMemberName("goo, nq", name: "goo", callable: false, nq: true); Test_ParseSimpleMemberName("goo(,nq", name: "goo(", callable: false, nq: true); Test_ParseSimpleMemberName("goo),nq", name: "goo)", callable: false, nq: true); Test_ParseSimpleMemberName("goo ( ,nq", name: "goo (", callable: false, nq: true); Test_ParseSimpleMemberName("goo ) ,nq", name: "goo )", callable: false, nq: true); Test_ParseSimpleMemberName(",nq", name: "", callable: false, nq: true); Test_ParseSimpleMemberName(" ,nq", name: "", callable: false, nq: true); } private void Test_ParseSimpleMemberName(string value, string name, bool callable, bool nq) { bool actualNoQuotes, actualIsCallable; string actualName = ObjectFormatterHelpers.ParseSimpleMemberName(value, 0, value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); actualName = ObjectFormatterHelpers.ParseSimpleMemberName("---" + value + "-", 3, 3 + value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); } [Fact] public void DebuggerDisplay() { string str; var a = new ComplexProxy(); str = s_formatter.FormatObject(a, SeparateLinesOptions); AssertMembers(str, @"[AStr]", @"_02_public_property_dd: *1", @"_03_private_property_dd: *2", @"_04_protected_property_dd: *3", @"_05_internal_property_dd: *4", @"_07_private_field_dd: +2", @"_08_protected_field_dd: +3", @"_09_internal_field_dd: +4", @"_10_private_collapsed: 0", @"_12_public: 0", @"_13_private: 0", @"_14_protected: 0", @"_15_internal: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_33: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1", @"_40_private_get_private_set: 1" ); var b = new TypeWithComplexProxy(); str = s_formatter.FormatObject(b, SeparateLinesOptions); AssertMembers(str, @"[BStr]", @"_02_public_property_dd: *1", @"_04_protected_property_dd: *3", @"_08_protected_field_dd: +3", @"_10_private_collapsed: 0", @"_12_public: 0", @"_14_protected: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1" ); } [Fact] public void DebuggerDisplay_Inherited() { var obj = new InheritedDebuggerDisplay(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("InheritedDebuggerDisplay(DebuggerDisplayValue)", str); } [Fact] public void DebuggerProxy_DebuggerDisplayAndProxy() { var obj = new TypeWithDebuggerDisplayAndProxy(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("TypeWithDebuggerDisplayAndProxy(DD) { A=0, B=0 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "TypeWithDebuggerDisplayAndProxy(DD)", "A: 0", "B: 0" ); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10816")] public void DebuggerProxy_Recursive() { string str; object obj = new RecursiveProxy.Node(0); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "RecursiveProxy.Node", "x: 0", "y: RecursiveProxy.Node { x=1, y=RecursiveProxy.Node { x=2, y=RecursiveProxy.Node { x=3, y=RecursiveProxy.Node { x=4, y=RecursiveProxy.Node { x=5, y=null } } } } }" ); obj = new InvalidRecursiveProxy.Node(); str = s_formatter.FormatObject(obj, SeparateLinesOptions); // TODO: better overflow handling Assert.Equal(ScriptingResources.StackOverflowWhileEvaluating, str); } [Fact] public void Array_Recursive() { string str; ListNode n2; ListNode n1 = new ListNode(); object[] obj = new object[5]; obj[0] = 1; obj[1] = obj; obj[2] = n2 = new ListNode() { data = obj, next = n1 }; obj[3] = new object[] { 4, 5, obj, 6, new ListNode() }; obj[4] = 3; n1.next = n2; n1.data = new object[] { 7, n2, 8, obj }; str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "object[5]", "1", "{ ... }", "ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }", "object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }", "3" ); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("object[5] { 1, { ... }, ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }, object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }, 3 }", str); } [Fact] public void LargeGraph() { var list = new LinkedList<object>(); object obj = list; for (int i = 0; i < 10000; i++) { var node = list.AddFirst(i); var newList = new LinkedList<object>(); list.AddAfter(node, newList); list = newList; } string output = "LinkedList<object>(2) { 0, LinkedList<object>(2) { 1, LinkedList<object>(2) { 2, LinkedList<object>(2) {"; for (int i = 100; i > 4; i--) { var printOptions = new PrintOptions { MaximumOutputLength = i, MemberDisplayFormat = MemberDisplayFormat.SingleLine, }; var actual = s_formatter.FormatObject(obj, printOptions); var expected = output.Substring(0, i) + "..."; Assert.Equal(expected, actual); } } [Fact] public void LongMembers() { object obj = new LongMembers(); var str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SingleLineOptions); Assert.Equal("LongMembers { LongNa...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SeparateLinesOptions); Assert.Equal($"LongMembers {{{Environment.NewLine} LongName0123456789...{Environment.NewLine} LongValue: \"012345...{Environment.NewLine}}}{Environment.NewLine}", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Array() { var obj = new Object[] { new C(), 1, "str", 'c', true, null, new bool[] { true, false, true, false } }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "object[7]", "[CStr]", "1", "\"str\"", "'c'", "true", "null", "bool[4] { true, false, true, false }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_MdArray() { string str; int[,,] a = new int[2, 3, 4] { { { 000, 001, 002, 003 }, { 010, 011, 012, 013 }, { 020, 021, 022, 023 }, }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 }, } }; str = s_formatter.FormatObject(a, SingleLineOptions); Assert.Equal("int[2, 3, 4] { { { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } } }", str); str = s_formatter.FormatObject(a, SeparateLinesOptions); AssertMembers(str, "int[2, 3, 4]", "{ { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }", "{ { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } }" ); int[][,][,,,] obj = new int[2][,][,,,]; obj[0] = new int[1, 2][,,,]; obj[0][0, 0] = new int[1, 2, 3, 4]; str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("int[2][,][,,,] { int[1, 2][,,,] { { int[1, 2, 3, 4] { { { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } } } }, null } }, null }", str); Array x = Array.CreateInstance(typeof(Object), lengths: new int[] { 2, 3 }, lowerBounds: new int[] { 2, 9 }); str = s_formatter.FormatObject(x, SingleLineOptions); Assert.Equal("object[2..4, 9..12] { { null, null, null }, { null, null, null } }", str); Array y = Array.CreateInstance(typeof(Object), lengths: new int[] { 1, 1 }, lowerBounds: new int[] { 0, 0 }); str = s_formatter.FormatObject(y, SingleLineOptions); Assert.Equal("object[1, 1] { { null } }", str); Array z = Array.CreateInstance(typeof(Object), lengths: new int[] { 0, 0 }, lowerBounds: new int[] { 0, 0 }); str = s_formatter.FormatObject(z, SingleLineOptions); Assert.Equal("object[0, 0] { }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Core() { string str; object obj; obj = Range_Core(0, 10); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ObjectFormatterTests.CoreRangeIterator(Count = 10)", str); } // This method and the class below emulate the behaviour of Enumerable.Range // in .NET Core. We use a custom type since not all runtime implementations // (e.g. Mono) apply precisely the same attributes, but we want to test behavior // under a specific set of attributes. private static IEnumerable<int> Range_Core(int start, int count) => new CoreRangeIterator(start, count); [DebuggerDisplay("Count = {CountForDebugger}")] private class CoreRangeIterator : IEnumerable<int> { private readonly int _start; private readonly int _end; private int CountForDebugger => _end - _start; public CoreRangeIterator(int start, int count) => (_start, _end) = (start, start + count); public IEnumerator<int> GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => null; } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Framework() { string str; object obj; obj = Range_Framework(0, 10); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("RangeIterator { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", str); } // These methods emulate the .NET Framework Enumerable.Range method private static IEnumerable<int> Range_Framework(int start, int count) => RangeIterator(start, count); private static IEnumerable<int> RangeIterator(int start, int count) { for (var i = 0; i < count; i++) yield return start + i; } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Exception() { string str; object obj; obj = Enumerable.Range(0, 10).Where(i => { if (i == 5) throw new Exception("xxx"); return i < 7; }); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Enumerable.WhereEnumerableIterator<int> { 0, 1, 2, 3, 4, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary() { string str; object obj; obj = new ThrowingDictionary(throwAt: -1); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "ThrowingDictionary(10)", "{ 1, 1 }", "{ 2, 2 }", "{ 3, 3 }", "{ 4, 4 }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary_Exception() { string str; object obj; obj = new ThrowingDictionary(throwAt: 3); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BitArray() { // BitArray doesn't have debugger proxy/display var obj = new System.Collections.BitArray(new int[] { 1 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue<int>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Queue<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack<int>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Stack<int>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Dictionary() { var obj = new Dictionary<string, int> { { "x", 1 }, }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Dictionary<string, int>(1)", "{ \"x\", 1 }" ); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Dictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_KeyValuePair() { var obj = new KeyValuePair<int, string>(1, "x"); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("KeyValuePair<int, string> { 1, \"x\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_List() { var obj = new List<object> { 1, 2, 'c' }; var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("List<object>(3) { 1, 2, 'c' }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_LinkedList() { var obj = new LinkedList<int>(); obj.AddLast(1); obj.AddLast(2); obj.AddLast(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("LinkedList<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { var obj = new SortedList<int, int>(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList<int, int>(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); var obj2 = new SortedList<int[], int[]>(); obj2.Add(new[] { 3 }, new int[] { 4 }); str = s_formatter.FormatObject(obj2, SingleLineOptions); Assert.Equal("SortedList<int[], int[]>(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedDictionary() { var obj = new SortedDictionary<int, int>(); obj.Add(1, 0x1a); obj.Add(3, 0x3c); obj.Add(2, 0x2b); var str = s_formatter. FormatObject(obj, new PrintOptions { NumberRadix = ObjectFormatterHelpers.NumberRadixHexadecimal }); Assert.Equal("SortedDictionary<int, int>(3) { { 0x00000001, 0x0000001a }, { 0x00000002, 0x0000002b }, { 0x00000003, 0x0000003c } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_HashSet() { var obj = new HashSet<int>(); obj.Add(1); obj.Add(2); // HashSet doesn't implement ICollection (it only implements ICollection<T>) so we don't call Count, // instead a DebuggerDisplay.Value is used. var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("HashSet<int>(Count = 2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedSet() { var obj = new SortedSet<int>(); obj.Add(1); obj.Add(2); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedSet<int>(2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentDictionary() { var obj = new ConcurrentDictionary<string, int>(); obj.AddOrUpdate("x", 1, (k, v) => v); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentDictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentQueue() { var obj = new ConcurrentQueue<object>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentQueue<object>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentStack() { var obj = new ConcurrentStack<object>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentStack<object>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BlockingCollection() { var obj = new BlockingCollection<int>(); obj.Add(1); obj.Add(2, new CancellationToken()); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("BlockingCollection<int>(2) { 1, 2 }", str); } // TODO(tomat): this only works with System.dll file version 30319.16644 (Win8 build) //[Fact] //public void DebuggerProxy_FrameworkTypes_ConcurrentBag() //{ // var obj = new ConcurrentBag<int>(); // obj.Add(1); // var str = ObjectFormatter.Instance.FormatObject(obj, quoteStrings: true, memberFormat: MemberDisplayFormat.Inline); // Assert.Equal("ConcurrentBag<int>(1) { 1 }", str); //} [Fact] public void DebuggerProxy_FrameworkTypes_ReadOnlyCollection() { var obj = new System.Collections.ObjectModel.ReadOnlyCollection<int>(new[] { 1, 2, 3 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ReadOnlyCollection<int>(3) { 1, 2, 3 }", str); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void DebuggerProxy_FrameworkTypes_Lazy() { var obj = new Lazy<int[]>(() => new int[] { 1, 2 }, LazyThreadSafetyMode.None); // Lazy<T> has both DebuggerDisplay and DebuggerProxy attributes and both display the same information. var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null) { IsValueCreated=false, IsValueFaulted=false, Mode=None, Value=null }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null)", "IsValueCreated: false", "IsValueFaulted: false", "Mode: None", "Value: null" ); Assert.NotNull(obj.Value); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 }) { IsValueCreated=true, IsValueFaulted=false, Mode=None, Value=int[2] { 1, 2 } }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 })", "IsValueCreated: true", "IsValueFaulted: false", "Mode: None", "Value: int[2] { 1, 2 }" ); } private void TaskMethod() { } [Fact] [WorkItem(10838, "https://github.com/mono/mono/issues/10838")] public void DebuggerProxy_FrameworkTypes_Task() { var obj = new MockDesktopTask(TaskMethod); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal( "MockDesktopTask(Id = 1234, Status = Created, Method = \"Void TaskMethod()\") " + "{ AsyncState=null, CancellationPending=false, CreationOptions=None, Exception=null, Id=1234, Status=Created }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "MockDesktopTask(Id = 1234, Status = Created, Method = \"Void TaskMethod()\")", "AsyncState: null", "CancellationPending: false", "CreationOptions: None", "Exception: null", "Id: 1234", "Status: Created" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock1() { var obj = new MockDesktopSpinLock(false); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("MockDesktopSpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=!<InvalidOperationException>, OwnerThreadID=null }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "MockDesktopSpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: !<InvalidOperationException>", "OwnerThreadID: null" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock2() { var obj = new MockDesktopSpinLock(true); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("MockDesktopSpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=true, OwnerThreadID=0 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "MockDesktopSpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: true", "OwnerThreadID: 0" ); } [Fact] public void DebuggerProxy_DiagnosticBag() { var obj = new DiagnosticBag(); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_AbstractAndExtern, "bar"), NoLocation.Singleton); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_BadExternIdentifier, "goo"), NoLocation.Singleton); using (new EnsureEnglishUICulture()) { var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("DiagnosticBag(Count = 2) { =error CS0180: 'bar' cannot be both extern and abstract, =error CS1679: Invalid extern alias for '/reference'; 'goo' is not a valid identifier }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "DiagnosticBag(Count = 2)", ": error CS0180: 'bar' cannot be both extern and abstract", ": error CS1679: Invalid extern alias for '/reference'; 'goo' is not a valid identifier" ); } } [Fact] public void DebuggerProxy_ArrayBuilder() { var obj = new ArrayBuilder<int>(); obj.AddRange(new[] { 1, 2, 3, 4, 5 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ArrayBuilder<int>(Count = 5) { 1, 2, 3, 4, 5 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "ArrayBuilder<int>(Count = 5)", "1", "2", "3", "4", "5" ); } [WorkItem(8542, "https://github.com/dotnet/roslyn/issues/8452")] [Fact] public void FormatConstructorSignature() { var constructor = typeof(object).GetTypeInfo().DeclaredConstructors.Single(); var signature = ((CommonObjectFormatter)s_formatter).FormatMethodSignature(constructor); Assert.Equal("object..ctor()", signature); // Checking for exceptions, more than particular output. } // The stack trace contains line numbers. We use a #line directive // so that the baseline doesn't need to be updated every time this // file changes. // // When adding a new test to this region, ADD IT ADD THE END, so you // don't have to update all the other baselines. #line 10000 "z:\Fixture.cs" private static class Fixture { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method() { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>() { throw new Exception(); } } private static class Fixture<T> { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method() { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>() { throw new Exception(); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_NonGeneric() { try { Fixture.Method(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10006)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_NonGeneric(){string.Format(ScriptingResources.AtFileLine, filePath, 10036)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericMethod() { try { Fixture.Method<char>(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture.Method<char> var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10012)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethod(){string.Format(ScriptingResources.AtFileLine, filePath, 10057)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericType() { try { Fixture<int>.Method(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture<int>.Method var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10021)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10079)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericMethodInGenericType() { try { Fixture<int>.Method<char>(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture<int>.Method<char> var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10027)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethodInGenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10101)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } private static class Fixture2 { [MethodImpl(MethodImplOptions.NoInlining)] public static void MethodDynamic() { ((dynamic)new object()).x(); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9221"), WorkItem(9221, "https://github.com/dotnet/roslyn/issues/9221")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_Dynamic() { try { Fixture2.MethodDynamic(); Assert.False(true); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"'object' does not contain a definition for 'x' + System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1<T0>(System.Runtime.CompilerServices.CallSite, T0) + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture2.MethodDynamic(){string.Format(ScriptingResources.AtFileLine, filePath, 10123)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_Dynamic(){string.Format(ScriptingResources.AtFileLine, filePath, 10132)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } private static class ParametersFixture { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method(ref char c, out DateTime d) { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>(ref U u) { throw new Exception(); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_RefOutParameters() { try { char c = ' '; DateTime date; ParametersFixture.Method(ref c, out date); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.ParametersFixture.Method(ref char, out System.DateTime){string.Format(ScriptingResources.AtFileLine, filePath, 10155)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_RefOutParameters(){string.Format(ScriptingResources.AtFileLine, filePath, 10172)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericRefParameter() { try { char c = ' '; ParametersFixture.Method<char>(ref c); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show ParametersFixture.Method<char>(ref char) var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.ParametersFixture.Method<U>(ref U){string.Format(ScriptingResources.AtFileLine, filePath, 10161)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericRefParameter(){string.Format(ScriptingResources.AtFileLine, filePath, 10194)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using ObjectFormatterFixtures; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests { public class ObjectFormatterTests : ObjectFormatterTestBase { private static readonly TestCSharpObjectFormatter s_formatter = new TestCSharpObjectFormatter(); [Fact] public void Objects() { string str; object nested = new Outer.Nested<int>(); str = s_formatter.FormatObject(nested, SingleLineOptions); Assert.Equal(@"Outer.Nested<int> { A=1, B=2 }", str); str = s_formatter.FormatObject(nested, HiddenOptions); Assert.Equal(@"Outer.Nested<int>", str); str = s_formatter.FormatObject(A<int>.X, HiddenOptions); Assert.Equal(@"A<int>.B<int>", str); object obj = new A<int>.B<bool>.C.D<string, double>.E(); str = s_formatter.FormatObject(obj, HiddenOptions); Assert.Equal(@"A<int>.B<bool>.C.D<string, double>.E", str); var sort = new Sort(); str = new TestCSharpObjectFormatter(maximumLineLength: 51).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1...", str); Assert.Equal(51 + 3, str.Length); str = new TestCSharpObjectFormatter(maximumLineLength: 5).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort ...", str); Assert.Equal(5 + 3, str.Length); str = new TestCSharpObjectFormatter(maximumLineLength: 4).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 3).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sor...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 2).FormatObject(sort, SingleLineOptions); Assert.Equal(@"So...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 1).FormatObject(sort, SingleLineOptions); Assert.Equal(@"S...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 80).FormatObject(sort, SingleLineOptions); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1, AG=1 }", str); } [Fact] public void TupleType() { var tup = new Tuple<int, int>(1, 2); Assert.Equal("(1, 2)", s_formatter.FormatObject(tup)); } [Fact] public void ValueTupleType() { (int, int) tup = (1, 2); Assert.Equal("(1, 2)", s_formatter.FormatObject(tup)); } [Fact] public void ArrayMethodParameters() { var result = s_formatter.FormatMethodSignature(Signatures.Arrays); Assert.Equal("ObjectFormatterFixtures.Signatures.ArrayParameters(int[], int[,], int[,,])", result); } [Fact] public void ArrayOfInt32_NoMembers() { object o = new int[4] { 3, 4, 5, 6 }; var str = s_formatter.FormatObject(o, HiddenOptions); Assert.Equal("int[4] { 3, 4, 5, 6 }", str); } #region DANGER: Debugging this method under VS2010 might freeze your machine. [Fact] public void RecursiveRootHidden() { var DO_NOT_ADD_TO_WATCH_WINDOW = new RecursiveRootHidden(); DO_NOT_ADD_TO_WATCH_WINDOW.C = DO_NOT_ADD_TO_WATCH_WINDOW; string str = s_formatter.FormatObject(DO_NOT_ADD_TO_WATCH_WINDOW, SingleLineOptions); Assert.Equal(@"RecursiveRootHidden { A=0, B=0 }", str); } #endregion [Fact] public void DebuggerDisplay_ParseSimpleMemberName() { Test_ParseSimpleMemberName("goo", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName("goo ", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName(" goo", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName(" goo ", name: "goo", callable: false, nq: false); Test_ParseSimpleMemberName("goo()", name: "goo", callable: true, nq: false); Test_ParseSimpleMemberName("\ngoo (\r\n)", name: "goo", callable: true, nq: false); Test_ParseSimpleMemberName(" goo ( \t) ", name: "goo", callable: true, nq: false); Test_ParseSimpleMemberName("goo,nq", name: "goo", callable: false, nq: true); Test_ParseSimpleMemberName("goo ,nq", name: "goo", callable: false, nq: true); Test_ParseSimpleMemberName("goo(),nq", name: "goo", callable: true, nq: true); Test_ParseSimpleMemberName(" goo \t( ) ,nq", name: "goo", callable: true, nq: true); Test_ParseSimpleMemberName(" goo \t( ) , nq", name: "goo", callable: true, nq: true); Test_ParseSimpleMemberName("goo, nq", name: "goo", callable: false, nq: true); Test_ParseSimpleMemberName("goo(,nq", name: "goo(", callable: false, nq: true); Test_ParseSimpleMemberName("goo),nq", name: "goo)", callable: false, nq: true); Test_ParseSimpleMemberName("goo ( ,nq", name: "goo (", callable: false, nq: true); Test_ParseSimpleMemberName("goo ) ,nq", name: "goo )", callable: false, nq: true); Test_ParseSimpleMemberName(",nq", name: "", callable: false, nq: true); Test_ParseSimpleMemberName(" ,nq", name: "", callable: false, nq: true); } private void Test_ParseSimpleMemberName(string value, string name, bool callable, bool nq) { bool actualNoQuotes, actualIsCallable; string actualName = ObjectFormatterHelpers.ParseSimpleMemberName(value, 0, value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); actualName = ObjectFormatterHelpers.ParseSimpleMemberName("---" + value + "-", 3, 3 + value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); } [Fact] public void DebuggerDisplay() { string str; var a = new ComplexProxy(); str = s_formatter.FormatObject(a, SeparateLinesOptions); AssertMembers(str, @"[AStr]", @"_02_public_property_dd: *1", @"_03_private_property_dd: *2", @"_04_protected_property_dd: *3", @"_05_internal_property_dd: *4", @"_07_private_field_dd: +2", @"_08_protected_field_dd: +3", @"_09_internal_field_dd: +4", @"_10_private_collapsed: 0", @"_12_public: 0", @"_13_private: 0", @"_14_protected: 0", @"_15_internal: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_33: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1", @"_40_private_get_private_set: 1" ); var b = new TypeWithComplexProxy(); str = s_formatter.FormatObject(b, SeparateLinesOptions); AssertMembers(str, @"[BStr]", @"_02_public_property_dd: *1", @"_04_protected_property_dd: *3", @"_08_protected_field_dd: +3", @"_10_private_collapsed: 0", @"_12_public: 0", @"_14_protected: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1" ); } [Fact] public void DebuggerDisplay_Inherited() { var obj = new InheritedDebuggerDisplay(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("InheritedDebuggerDisplay(DebuggerDisplayValue)", str); } [Fact] public void DebuggerProxy_DebuggerDisplayAndProxy() { var obj = new TypeWithDebuggerDisplayAndProxy(); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("TypeWithDebuggerDisplayAndProxy(DD) { A=0, B=0 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "TypeWithDebuggerDisplayAndProxy(DD)", "A: 0", "B: 0" ); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10816")] public void DebuggerProxy_Recursive() { string str; object obj = new RecursiveProxy.Node(0); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "RecursiveProxy.Node", "x: 0", "y: RecursiveProxy.Node { x=1, y=RecursiveProxy.Node { x=2, y=RecursiveProxy.Node { x=3, y=RecursiveProxy.Node { x=4, y=RecursiveProxy.Node { x=5, y=null } } } } }" ); obj = new InvalidRecursiveProxy.Node(); str = s_formatter.FormatObject(obj, SeparateLinesOptions); // TODO: better overflow handling Assert.Equal(ScriptingResources.StackOverflowWhileEvaluating, str); } [Fact] public void Array_Recursive() { string str; ListNode n2; ListNode n1 = new ListNode(); object[] obj = new object[5]; obj[0] = 1; obj[1] = obj; obj[2] = n2 = new ListNode() { data = obj, next = n1 }; obj[3] = new object[] { 4, 5, obj, 6, new ListNode() }; obj[4] = 3; n1.next = n2; n1.data = new object[] { 7, n2, 8, obj }; str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "object[5]", "1", "{ ... }", "ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }", "object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }", "3" ); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("object[5] { 1, { ... }, ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }, object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }, 3 }", str); } [Fact] public void LargeGraph() { var list = new LinkedList<object>(); object obj = list; for (int i = 0; i < 10000; i++) { var node = list.AddFirst(i); var newList = new LinkedList<object>(); list.AddAfter(node, newList); list = newList; } string output = "LinkedList<object>(2) { 0, LinkedList<object>(2) { 1, LinkedList<object>(2) { 2, LinkedList<object>(2) {"; for (int i = 100; i > 4; i--) { var printOptions = new PrintOptions { MaximumOutputLength = i, MemberDisplayFormat = MemberDisplayFormat.SingleLine, }; var actual = s_formatter.FormatObject(obj, printOptions); var expected = output.Substring(0, i) + "..."; Assert.Equal(expected, actual); } } [Fact] public void LongMembers() { object obj = new LongMembers(); var str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SingleLineOptions); Assert.Equal("LongMembers { LongNa...", str); str = new TestCSharpObjectFormatter(maximumLineLength: 20).FormatObject(obj, SeparateLinesOptions); Assert.Equal($"LongMembers {{{Environment.NewLine} LongName0123456789...{Environment.NewLine} LongValue: \"012345...{Environment.NewLine}}}{Environment.NewLine}", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Array() { var obj = new Object[] { new C(), 1, "str", 'c', true, null, new bool[] { true, false, true, false } }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "object[7]", "[CStr]", "1", "\"str\"", "'c'", "true", "null", "bool[4] { true, false, true, false }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_MdArray() { string str; int[,,] a = new int[2, 3, 4] { { { 000, 001, 002, 003 }, { 010, 011, 012, 013 }, { 020, 021, 022, 023 }, }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 }, } }; str = s_formatter.FormatObject(a, SingleLineOptions); Assert.Equal("int[2, 3, 4] { { { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } } }", str); str = s_formatter.FormatObject(a, SeparateLinesOptions); AssertMembers(str, "int[2, 3, 4]", "{ { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }", "{ { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } }" ); int[][,][,,,] obj = new int[2][,][,,,]; obj[0] = new int[1, 2][,,,]; obj[0][0, 0] = new int[1, 2, 3, 4]; str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("int[2][,][,,,] { int[1, 2][,,,] { { int[1, 2, 3, 4] { { { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } } } }, null } }, null }", str); Array x = Array.CreateInstance(typeof(Object), lengths: new int[] { 2, 3 }, lowerBounds: new int[] { 2, 9 }); str = s_formatter.FormatObject(x, SingleLineOptions); Assert.Equal("object[2..4, 9..12] { { null, null, null }, { null, null, null } }", str); Array y = Array.CreateInstance(typeof(Object), lengths: new int[] { 1, 1 }, lowerBounds: new int[] { 0, 0 }); str = s_formatter.FormatObject(y, SingleLineOptions); Assert.Equal("object[1, 1] { { null } }", str); Array z = Array.CreateInstance(typeof(Object), lengths: new int[] { 0, 0 }, lowerBounds: new int[] { 0, 0 }); str = s_formatter.FormatObject(z, SingleLineOptions); Assert.Equal("object[0, 0] { }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Core() { string str; object obj; obj = Range_Core(0, 10); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ObjectFormatterTests.CoreRangeIterator(Count = 10)", str); } // This method and the class below emulate the behaviour of Enumerable.Range // in .NET Core. We use a custom type since not all runtime implementations // (e.g. Mono) apply precisely the same attributes, but we want to test behavior // under a specific set of attributes. private static IEnumerable<int> Range_Core(int start, int count) => new CoreRangeIterator(start, count); [DebuggerDisplay("Count = {CountForDebugger}")] private class CoreRangeIterator : IEnumerable<int> { private readonly int _start; private readonly int _end; private int CountForDebugger => _end - _start; public CoreRangeIterator(int start, int count) => (_start, _end) = (start, start + count); public IEnumerator<int> GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => null; } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Framework() { string str; object obj; obj = Range_Framework(0, 10); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("RangeIterator { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", str); } // These methods emulate the .NET Framework Enumerable.Range method private static IEnumerable<int> Range_Framework(int start, int count) => RangeIterator(start, count); private static IEnumerable<int> RangeIterator(int start, int count) { for (var i = 0; i < count; i++) yield return start + i; } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Exception() { string str; object obj; obj = Enumerable.Range(0, 10).Where(i => { if (i == 5) throw new Exception("xxx"); return i < 7; }); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Enumerable.WhereEnumerableIterator<int> { 0, 1, 2, 3, 4, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary() { string str; object obj; obj = new ThrowingDictionary(throwAt: -1); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "ThrowingDictionary(10)", "{ 1, 1 }", "{ 2, 2 }", "{ 3, 3 }", "{ 4, 4 }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary_Exception() { string str; object obj; obj = new ThrowingDictionary(throwAt: 3); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BitArray() { // BitArray doesn't have debugger proxy/display var obj = new System.Collections.BitArray(new int[] { 1 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue<int>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Queue<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack<int>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Stack<int>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Dictionary() { var obj = new Dictionary<string, int> { { "x", 1 }, }; var str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Dictionary<string, int>(1)", "{ \"x\", 1 }" ); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Dictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_KeyValuePair() { var obj = new KeyValuePair<int, string>(1, "x"); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("KeyValuePair<int, string> { 1, \"x\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_List() { var obj = new List<object> { 1, 2, 'c' }; var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("List<object>(3) { 1, 2, 'c' }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_LinkedList() { var obj = new LinkedList<int>(); obj.AddLast(1); obj.AddLast(2); obj.AddLast(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("LinkedList<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { var obj = new SortedList<int, int>(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedList<int, int>(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); var obj2 = new SortedList<int[], int[]>(); obj2.Add(new[] { 3 }, new int[] { 4 }); str = s_formatter.FormatObject(obj2, SingleLineOptions); Assert.Equal("SortedList<int[], int[]>(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedDictionary() { var obj = new SortedDictionary<int, int>(); obj.Add(1, 0x1a); obj.Add(3, 0x3c); obj.Add(2, 0x2b); var str = s_formatter. FormatObject(obj, new PrintOptions { NumberRadix = ObjectFormatterHelpers.NumberRadixHexadecimal }); Assert.Equal("SortedDictionary<int, int>(3) { { 0x00000001, 0x0000001a }, { 0x00000002, 0x0000002b }, { 0x00000003, 0x0000003c } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_HashSet() { var obj = new HashSet<int>(); obj.Add(1); obj.Add(2); // HashSet doesn't implement ICollection (it only implements ICollection<T>) so we don't call Count, // instead a DebuggerDisplay.Value is used. var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("HashSet<int>(Count = 2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedSet() { var obj = new SortedSet<int>(); obj.Add(1); obj.Add(2); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("SortedSet<int>(2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentDictionary() { var obj = new ConcurrentDictionary<string, int>(); obj.AddOrUpdate("x", 1, (k, v) => v); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentDictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentQueue() { var obj = new ConcurrentQueue<object>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentQueue<object>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentStack() { var obj = new ConcurrentStack<object>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ConcurrentStack<object>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BlockingCollection() { var obj = new BlockingCollection<int>(); obj.Add(1); obj.Add(2, new CancellationToken()); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("BlockingCollection<int>(2) { 1, 2 }", str); } // TODO(tomat): this only works with System.dll file version 30319.16644 (Win8 build) //[Fact] //public void DebuggerProxy_FrameworkTypes_ConcurrentBag() //{ // var obj = new ConcurrentBag<int>(); // obj.Add(1); // var str = ObjectFormatter.Instance.FormatObject(obj, quoteStrings: true, memberFormat: MemberDisplayFormat.Inline); // Assert.Equal("ConcurrentBag<int>(1) { 1 }", str); //} [Fact] public void DebuggerProxy_FrameworkTypes_ReadOnlyCollection() { var obj = new System.Collections.ObjectModel.ReadOnlyCollection<int>(new[] { 1, 2, 3 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ReadOnlyCollection<int>(3) { 1, 2, 3 }", str); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] public void DebuggerProxy_FrameworkTypes_Lazy() { var obj = new Lazy<int[]>(() => new int[] { 1, 2 }, LazyThreadSafetyMode.None); // Lazy<T> has both DebuggerDisplay and DebuggerProxy attributes and both display the same information. var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null) { IsValueCreated=false, IsValueFaulted=false, Mode=None, Value=null }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null)", "IsValueCreated: false", "IsValueFaulted: false", "Mode: None", "Value: null" ); Assert.NotNull(obj.Value); str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 }) { IsValueCreated=true, IsValueFaulted=false, Mode=None, Value=int[2] { 1, 2 } }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 })", "IsValueCreated: true", "IsValueFaulted: false", "Mode: None", "Value: int[2] { 1, 2 }" ); } private void TaskMethod() { } [Fact] [WorkItem(10838, "https://github.com/mono/mono/issues/10838")] public void DebuggerProxy_FrameworkTypes_Task() { var obj = new MockDesktopTask(TaskMethod); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal( "MockDesktopTask(Id = 1234, Status = Created, Method = \"Void TaskMethod()\") " + "{ AsyncState=null, CancellationPending=false, CreationOptions=None, Exception=null, Id=1234, Status=Created }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "MockDesktopTask(Id = 1234, Status = Created, Method = \"Void TaskMethod()\")", "AsyncState: null", "CancellationPending: false", "CreationOptions: None", "Exception: null", "Id: 1234", "Status: Created" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock1() { var obj = new MockDesktopSpinLock(false); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("MockDesktopSpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=!<InvalidOperationException>, OwnerThreadID=null }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "MockDesktopSpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: !<InvalidOperationException>", "OwnerThreadID: null" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock2() { var obj = new MockDesktopSpinLock(true); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("MockDesktopSpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=true, OwnerThreadID=0 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "MockDesktopSpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: true", "OwnerThreadID: 0" ); } [Fact] public void DebuggerProxy_DiagnosticBag() { var obj = new DiagnosticBag(); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_AbstractAndExtern, "bar"), NoLocation.Singleton); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_BadExternIdentifier, "goo"), NoLocation.Singleton); using (new EnsureEnglishUICulture()) { var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("DiagnosticBag(Count = 2) { =error CS0180: 'bar' cannot be both extern and abstract, =error CS1679: Invalid extern alias for '/reference'; 'goo' is not a valid identifier }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "DiagnosticBag(Count = 2)", ": error CS0180: 'bar' cannot be both extern and abstract", ": error CS1679: Invalid extern alias for '/reference'; 'goo' is not a valid identifier" ); } } [Fact] public void DebuggerProxy_ArrayBuilder() { var obj = new ArrayBuilder<int>(); obj.AddRange(new[] { 1, 2, 3, 4, 5 }); var str = s_formatter.FormatObject(obj, SingleLineOptions); Assert.Equal("ArrayBuilder<int>(Count = 5) { 1, 2, 3, 4, 5 }", str); str = s_formatter.FormatObject(obj, SeparateLinesOptions); AssertMembers(str, "ArrayBuilder<int>(Count = 5)", "1", "2", "3", "4", "5" ); } [WorkItem(8542, "https://github.com/dotnet/roslyn/issues/8452")] [Fact] public void FormatConstructorSignature() { var constructor = typeof(object).GetTypeInfo().DeclaredConstructors.Single(); var signature = ((CommonObjectFormatter)s_formatter).FormatMethodSignature(constructor); Assert.Equal("object..ctor()", signature); // Checking for exceptions, more than particular output. } // The stack trace contains line numbers. We use a #line directive // so that the baseline doesn't need to be updated every time this // file changes. // // When adding a new test to this region, ADD IT ADD THE END, so you // don't have to update all the other baselines. #line 10000 "z:\Fixture.cs" private static class Fixture { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method() { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>() { throw new Exception(); } } private static class Fixture<T> { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method() { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>() { throw new Exception(); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_NonGeneric() { try { Fixture.Method(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10006)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_NonGeneric(){string.Format(ScriptingResources.AtFileLine, filePath, 10036)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericMethod() { try { Fixture.Method<char>(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture.Method<char> var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10012)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethod(){string.Format(ScriptingResources.AtFileLine, filePath, 10057)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericType() { try { Fixture<int>.Method(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture<int>.Method var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method(){string.Format(ScriptingResources.AtFileLine, filePath, 10021)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10079)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericMethodInGenericType() { try { Fixture<int>.Method<char>(); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show Fixture<int>.Method<char> var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture<T>.Method<U>(){string.Format(ScriptingResources.AtFileLine, filePath, 10027)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericMethodInGenericType(){string.Format(ScriptingResources.AtFileLine, filePath, 10101)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } private static class Fixture2 { [MethodImpl(MethodImplOptions.NoInlining)] public static void MethodDynamic() { ((dynamic)new object()).x(); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/9221"), WorkItem(9221, "https://github.com/dotnet/roslyn/issues/9221")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_Dynamic() { try { Fixture2.MethodDynamic(); Assert.False(true); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"'object' does not contain a definition for 'x' + System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1<T0>(System.Runtime.CompilerServices.CallSite, T0) + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.Fixture2.MethodDynamic(){string.Format(ScriptingResources.AtFileLine, filePath, 10123)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_Dynamic(){string.Format(ScriptingResources.AtFileLine, filePath, 10132)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } private static class ParametersFixture { [MethodImpl(MethodImplOptions.NoInlining)] public static void Method(ref char c, out DateTime d) { throw new Exception(); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Method<U>(ref U u) { throw new Exception(); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_RefOutParameters() { try { char c = ' '; DateTime date; ParametersFixture.Method(ref c, out date); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.ParametersFixture.Method(ref char, out System.DateTime){string.Format(ScriptingResources.AtFileLine, filePath, 10155)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_RefOutParameters(){string.Format(ScriptingResources.AtFileLine, filePath, 10172)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/19027")] [WorkItem(15860, "https://github.com/dotnet/roslyn/issues/15860")] [WorkItem(19027, "https://github.com/dotnet/roslyn/issues/19027")] public void StackTrace_GenericRefParameter() { try { char c = ' '; ParametersFixture.Method<char>(ref c); } catch (Exception e) { const string filePath = @"z:\Fixture.cs"; // TODO (DevDiv #173210): Should show ParametersFixture.Method<char>(ref char) var expected = $@"{new Exception().Message} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.ParametersFixture.Method<U>(ref U){string.Format(ScriptingResources.AtFileLine, filePath, 10161)} + Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.UnitTests.ObjectFormatterTests.StackTrace_GenericRefParameter(){string.Format(ScriptingResources.AtFileLine, filePath, 10194)} "; var actual = s_formatter.FormatException(e); Assert.Equal(expected, actual); } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/AscendingKeywordRecommender.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 AscendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AscendingKeywordRecommender() : base(SyntaxKind.AscendingKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.TargetToken.IsOrderByDirectionContext(); } }
// Licensed to the .NET Foundation under one or more 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 AscendingKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AscendingKeywordRecommender() : base(SyntaxKind.AscendingKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.TargetToken.IsOrderByDirectionContext(); } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/AddConstructorParametersFromMembers/AddConstructorParametersFromMembersCodeRefactoringProvider.ConstructorCandidate.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; namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private readonly struct ConstructorCandidate { public readonly IMethodSymbol Constructor; public readonly ImmutableArray<ISymbol> MissingMembers; public readonly ImmutableArray<IParameterSymbol> MissingParameters; public ConstructorCandidate(IMethodSymbol constructor, ImmutableArray<ISymbol> missingMembers, ImmutableArray<IParameterSymbol> missingParameters) { Constructor = constructor; MissingMembers = missingMembers; MissingParameters = missingParameters; } } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.AddConstructorParametersFromMembers { internal partial class AddConstructorParametersFromMembersCodeRefactoringProvider { private readonly struct ConstructorCandidate { public readonly IMethodSymbol Constructor; public readonly ImmutableArray<ISymbol> MissingMembers; public readonly ImmutableArray<IParameterSymbol> MissingParameters; public ConstructorCandidate(IMethodSymbol constructor, ImmutableArray<ISymbol> missingMembers, ImmutableArray<IParameterSymbol> missingParameters) { Constructor = constructor; MissingMembers = missingMembers; MissingParameters = missingParameters; } } } }
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/InterfaceImplementationTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class InterfaceImplementationTests Inherits BasicTestBase <Theory> <CombinatorialData> <WorkItem(46494, "https://github.com/dotnet/roslyn/issues/46494")> Public Sub ExplicitImplementationInBaseType_01(useCompilationReference As Boolean) Dim source0 = "Public Structure S(Of T) End Structure Public Interface I Function F() As S(Of (X As Integer, Y As Integer)) End Interface" Dim source1 = "Public Class A(Of T) Implements I Public Function F() As S(Of T) Return Nothing End Function Private Function I_F() As S(Of (X As Integer, Y As Integer)) Implements I.F Return Nothing End Function End Class" Dim source2 = "Class B(Of T) Inherits A(Of T) Implements I End Class" Dim source3 = "Class Program Shared Sub Main() Dim i As I = New B(Of String)() Dim o = i.F() System.Console.WriteLine(o) End Sub End Class" ExplicitImplementationInBaseType(useCompilationReference, source0, source1, source2, source3, "B", "I.F", "S`1[System.ValueTuple`2[System.Int32,System.Int32]]", "Function A(Of T).I_F() As S(Of (X As System.Int32, Y As System.Int32))") End Sub <Theory> <CombinatorialData> <WorkItem(46494, "https://github.com/dotnet/roslyn/issues/46494")> Public Sub ExplicitImplementationInBaseType_02(useCompilationReference As Boolean) Dim source0 = "Public Structure S(Of T) End Structure Public Interface I Sub F(s As S(Of (X As Integer, Y As Integer))) End Interface" Dim source1 = "Public Class A(Of T) Implements I Public Sub F(s As S(Of T)) End Sub Private Sub I_F(s As S(Of (X As Integer, Y As Integer))) Implements I.F End Sub End Class" Dim source2 = "Class B(Of T) Inherits A(Of T) Implements I End Class" Dim source3 = "Class Program Shared Sub Main() Dim i As I = New B(Of String)() i.F(Nothing) System.Console.WriteLine(1) End Sub End Class" ExplicitImplementationInBaseType(useCompilationReference, source0, source1, source2, source3, "B", "I.F", "1", "Sub A(Of T).I_F(s As S(Of (X As System.Int32, Y As System.Int32)))") End Sub Private Sub ExplicitImplementationInBaseType( useCompilationReference As Boolean, source0 As String, source1 As String, source2 As String, source3 As String, derivedTypeName As String, interfaceMemberName As String, expectedOutput As String, expectedImplementingMember As String) Dim comp = CreateCompilation(source0) Dim ref0 = AsReference(comp, useCompilationReference) comp = CreateCompilation(source1, references:={ref0}) Dim ref1 = AsReference(comp, useCompilationReference) comp = CreateCompilation({source2, source3}, references:={ref0, ref1}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:=expectedOutput) Dim derivedType = comp.GetMember(Of SourceNamedTypeSymbol)(derivedTypeName) Dim interfaceMember = comp.GetMember(Of MethodSymbol)(interfaceMemberName) Dim implementingMember = derivedType.FindImplementationForInterfaceMember(interfaceMember) Assert.Equal(expectedImplementingMember, implementingMember.ToTestDisplayString()) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_1() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Overloads Sub M() End Interface ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) compilation1.AssertNoDiagnostics() Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_2() Dim vbSource0 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Overloads Sub M() End Interface ]]> </file> </compilation> Dim compilation0 = CreateCompilation(vbSource0, options:=TestOptions.ReleaseDll) Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll, references:={compilation0.EmitToImageReference()}) Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_3() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Shadows Sub M() End Interface ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) compilation1.AssertNoDiagnostics() Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_4() Dim vbSource0 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Shadows Sub M() End Interface ]]> </file> </compilation> Dim compilation0 = CreateCompilation(vbSource0, options:=TestOptions.ReleaseDll) Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll, references:={compilation0.EmitToImageReference()}) Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) 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.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class InterfaceImplementationTests Inherits BasicTestBase <Theory> <CombinatorialData> <WorkItem(46494, "https://github.com/dotnet/roslyn/issues/46494")> Public Sub ExplicitImplementationInBaseType_01(useCompilationReference As Boolean) Dim source0 = "Public Structure S(Of T) End Structure Public Interface I Function F() As S(Of (X As Integer, Y As Integer)) End Interface" Dim source1 = "Public Class A(Of T) Implements I Public Function F() As S(Of T) Return Nothing End Function Private Function I_F() As S(Of (X As Integer, Y As Integer)) Implements I.F Return Nothing End Function End Class" Dim source2 = "Class B(Of T) Inherits A(Of T) Implements I End Class" Dim source3 = "Class Program Shared Sub Main() Dim i As I = New B(Of String)() Dim o = i.F() System.Console.WriteLine(o) End Sub End Class" ExplicitImplementationInBaseType(useCompilationReference, source0, source1, source2, source3, "B", "I.F", "S`1[System.ValueTuple`2[System.Int32,System.Int32]]", "Function A(Of T).I_F() As S(Of (X As System.Int32, Y As System.Int32))") End Sub <Theory> <CombinatorialData> <WorkItem(46494, "https://github.com/dotnet/roslyn/issues/46494")> Public Sub ExplicitImplementationInBaseType_02(useCompilationReference As Boolean) Dim source0 = "Public Structure S(Of T) End Structure Public Interface I Sub F(s As S(Of (X As Integer, Y As Integer))) End Interface" Dim source1 = "Public Class A(Of T) Implements I Public Sub F(s As S(Of T)) End Sub Private Sub I_F(s As S(Of (X As Integer, Y As Integer))) Implements I.F End Sub End Class" Dim source2 = "Class B(Of T) Inherits A(Of T) Implements I End Class" Dim source3 = "Class Program Shared Sub Main() Dim i As I = New B(Of String)() i.F(Nothing) System.Console.WriteLine(1) End Sub End Class" ExplicitImplementationInBaseType(useCompilationReference, source0, source1, source2, source3, "B", "I.F", "1", "Sub A(Of T).I_F(s As S(Of (X As System.Int32, Y As System.Int32)))") End Sub Private Sub ExplicitImplementationInBaseType( useCompilationReference As Boolean, source0 As String, source1 As String, source2 As String, source3 As String, derivedTypeName As String, interfaceMemberName As String, expectedOutput As String, expectedImplementingMember As String) Dim comp = CreateCompilation(source0) Dim ref0 = AsReference(comp, useCompilationReference) comp = CreateCompilation(source1, references:={ref0}) Dim ref1 = AsReference(comp, useCompilationReference) comp = CreateCompilation({source2, source3}, references:={ref0, ref1}, options:=TestOptions.ReleaseExe) CompileAndVerify(comp, expectedOutput:=expectedOutput) Dim derivedType = comp.GetMember(Of SourceNamedTypeSymbol)(derivedTypeName) Dim interfaceMember = comp.GetMember(Of MethodSymbol)(interfaceMemberName) Dim implementingMember = derivedType.FindImplementationForInterfaceMember(interfaceMember) Assert.Equal(expectedImplementingMember, implementingMember.ToTestDisplayString()) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_1() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Overloads Sub M() End Interface ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) compilation1.AssertNoDiagnostics() Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_2() Dim vbSource0 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Overloads Sub M() End Interface ]]> </file> </compilation> Dim compilation0 = CreateCompilation(vbSource0, options:=TestOptions.ReleaseDll) Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll, references:={compilation0.EmitToImageReference()}) Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_3() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Shadows Sub M() End Interface ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) compilation1.AssertNoDiagnostics() Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub <Fact()> <WorkItem(50713, "https://github.com/dotnet/roslyn/issues/50713")> Public Sub Issue50713_4() Dim vbSource0 = <compilation> <file name="c.vb"><![CDATA[ Interface I1 Sub M() End Interface Interface I2 Inherits I1 Shadows Sub M() End Interface ]]> </file> </compilation> Dim compilation0 = CreateCompilation(vbSource0, options:=TestOptions.ReleaseDll) Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll, references:={compilation0.EmitToImageReference()}) Dim i1M = compilation1.GetMember("I1.M") Dim i2 = compilation1.GetMember(Of NamedTypeSymbol)("I2") Assert.Null(i2.FindImplementationForInterfaceMember(i1M)) End Sub End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Wrapping/BinaryExpressionWrappingTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public Class BinaryExpressionWrappingTests Inherits AbstractWrappingTests Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicWrappingCodeRefactoringProvider() End Function Private ReadOnly Property EndOfLine As OptionsCollection = [Option]( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.EndOfLine) Private ReadOnly Property BeginningOfLine As OptionsCollection = [Option]( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.BeginningOfLine) <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithSyntaxError() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i andalso (j andalso ) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithSelection() As Task Await TestMissingAsync( "class C sub Bar() if ([|i|] andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingBeforeExpr() As Task Await TestMissingAsync( "class C sub Bar() [||]if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithSingleExpr() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithMultiLineExpression() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i andalso (j + k)) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithMultiLineExpr2() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i andalso "" "") end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf_IncludingOp() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", BeginningOfLine, "class C sub Bar() if (i _ andalso j) end if end sub end class", "class C sub Bar() if (i _ andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf2() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i[||] andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf3() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i [||]andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf4() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i andalso[||] j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf5() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i andalso [||]j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestTwoExprWrappingCases_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestTwoExprWrappingCases_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", BeginningOfLine, "class C sub Bar() if (i _ andalso j) end if end sub end class", "class C sub Bar() if (i _ andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestThreeExprWrappingCases_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j orelse k) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j orelse k) end if end sub end class", "class C sub Bar() if (i andalso j orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestThreeExprWrappingCases_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j orelse k) end if end sub end class", BeginningOfLine, "class C sub Bar() if (i _ andalso j _ orelse k) end if end sub end class", "class C sub Bar() if (i _ andalso j _ orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_AllOptions_NoInitialMatches_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ( [||]i andalso j _ orelse k) end if end sub end class", EndOfLine, "class C sub Bar() if ( i andalso j orelse k) end if end sub end class", "class C sub Bar() if ( i andalso j orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_AllOptions_NoInitialMatches_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ( [||]i andalso j _ orelse k) end if end sub end class", BeginningOfLine, "class C sub Bar() if ( i _ andalso j _ orelse k) end if end sub end class", "class C sub Bar() if ( i andalso j orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_DoNotOfferExistingOption1() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]a andalso b) end if end sub end class", "class C sub Bar() if (a _ andalso b) end if end sub end class", "class C sub Bar() if (a _ andalso b) end if end sub end class", "class C sub Bar() if (a andalso b) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_DoNotOfferExistingOption2_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]a _ andalso b) end if end sub end class", EndOfLine, "class C sub Bar() if (a andalso b) end if end sub end class", "class C sub Bar() if (a andalso b) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_DoNotOfferExistingOption2_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]a _ andalso b) end if end sub end class", BeginningOfLine, "class C sub Bar() if (a andalso b) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInLocalInitializer() As Task Await TestAllWrappingCasesAsync( "class C sub Goo() dim v = [||]a andalso b andalso c end sub end class", EndOfLine, "class C sub Goo() dim v = a andalso b andalso c end sub end class", "class C sub Goo() dim v = a andalso b andalso c end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInField_Beginning() As Task Await TestAllWrappingCasesAsync( "class C dim v = [||]a andalso b andalso c end class", BeginningOfLine, "class C dim v = a _ andalso b _ andalso c end class", "class C dim v = a _ andalso b _ andalso c end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInField_End() As Task Await TestAllWrappingCasesAsync( "class C dim v = [||]a andalso b andalso c end class", EndOfLine, "class C dim v = a andalso b andalso c end class", "class C dim v = a andalso b andalso c end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestAddition_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() dim goo = [||]""now"" & ""is"" & ""the"" & ""time"" end sub end class", EndOfLine, "class C sub Bar() dim goo = ""now"" & ""is"" & ""the"" & ""time"" end sub end class", "class C sub Bar() dim goo = ""now"" & ""is"" & ""the"" & ""time"" end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestAddition_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() dim goo = [||]""now"" & ""is"" & ""the"" & ""time"" end sub end class", "class C sub Bar() dim goo = ""now"" _ & ""is"" _ & ""the"" _ & ""time"" end sub end class", "class C sub Bar() dim goo = ""now"" _ & ""is"" _ & ""the"" _ & ""time"" end sub end class") End Function <WorkItem(34127, "https://github.com/dotnet/roslyn/issues/34127")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestWrapLowerPrecedenceInLargeBinary() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() dim goo = [||]a + b + c + d = x * y * z end sub end class", "class C sub Bar() dim goo = a + b + c + d _ = x * y * z end sub end class", "class C sub Bar() dim goo = a + b + c + d _ = x * y * z end sub end class") End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.CodeStyle Imports Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions Imports Microsoft.CodeAnalysis.VisualBasic.Wrapping Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Wrapping Public Class BinaryExpressionWrappingTests Inherits AbstractWrappingTests Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicWrappingCodeRefactoringProvider() End Function Private ReadOnly Property EndOfLine As OptionsCollection = [Option]( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.EndOfLine) Private ReadOnly Property BeginningOfLine As OptionsCollection = [Option]( CodeStyleOptions2.OperatorPlacementWhenWrapping, OperatorPlacementWhenWrappingPreference.BeginningOfLine) <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithSyntaxError() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i andalso (j andalso ) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithSelection() As Task Await TestMissingAsync( "class C sub Bar() if ([|i|] andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingBeforeExpr() As Task Await TestMissingAsync( "class C sub Bar() [||]if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithSingleExpr() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithMultiLineExpression() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i andalso (j + k)) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestMissingWithMultiLineExpr2() As Task Await TestMissingAsync( "class C sub Bar() if ([||]i andalso "" "") end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf_IncludingOp() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", BeginningOfLine, "class C sub Bar() if (i _ andalso j) end if end sub end class", "class C sub Bar() if (i _ andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf2() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i[||] andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf3() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i [||]andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf4() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i andalso[||] j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInIf5() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if (i andalso [||]j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestTwoExprWrappingCases_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j) end if end sub end class", "class C sub Bar() if (i andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestTwoExprWrappingCases_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j) end if end sub end class", BeginningOfLine, "class C sub Bar() if (i _ andalso j) end if end sub end class", "class C sub Bar() if (i _ andalso j) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestThreeExprWrappingCases_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j orelse k) end if end sub end class", EndOfLine, "class C sub Bar() if (i andalso j orelse k) end if end sub end class", "class C sub Bar() if (i andalso j orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestThreeExprWrappingCases_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]i andalso j orelse k) end if end sub end class", BeginningOfLine, "class C sub Bar() if (i _ andalso j _ orelse k) end if end sub end class", "class C sub Bar() if (i _ andalso j _ orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_AllOptions_NoInitialMatches_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ( [||]i andalso j _ orelse k) end if end sub end class", EndOfLine, "class C sub Bar() if ( i andalso j orelse k) end if end sub end class", "class C sub Bar() if ( i andalso j orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_AllOptions_NoInitialMatches_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ( [||]i andalso j _ orelse k) end if end sub end class", BeginningOfLine, "class C sub Bar() if ( i _ andalso j _ orelse k) end if end sub end class", "class C sub Bar() if ( i andalso j orelse k) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_DoNotOfferExistingOption1() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]a andalso b) end if end sub end class", "class C sub Bar() if (a _ andalso b) end if end sub end class", "class C sub Bar() if (a _ andalso b) end if end sub end class", "class C sub Bar() if (a andalso b) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_DoNotOfferExistingOption2_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]a _ andalso b) end if end sub end class", EndOfLine, "class C sub Bar() if (a andalso b) end if end sub end class", "class C sub Bar() if (a andalso b) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function Test_DoNotOfferExistingOption2_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() if ([||]a _ andalso b) end if end sub end class", BeginningOfLine, "class C sub Bar() if (a andalso b) end if end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInLocalInitializer() As Task Await TestAllWrappingCasesAsync( "class C sub Goo() dim v = [||]a andalso b andalso c end sub end class", EndOfLine, "class C sub Goo() dim v = a andalso b andalso c end sub end class", "class C sub Goo() dim v = a andalso b andalso c end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInField_Beginning() As Task Await TestAllWrappingCasesAsync( "class C dim v = [||]a andalso b andalso c end class", BeginningOfLine, "class C dim v = a _ andalso b _ andalso c end class", "class C dim v = a _ andalso b _ andalso c end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestInField_End() As Task Await TestAllWrappingCasesAsync( "class C dim v = [||]a andalso b andalso c end class", EndOfLine, "class C dim v = a andalso b andalso c end class", "class C dim v = a andalso b andalso c end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestAddition_End() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() dim goo = [||]""now"" & ""is"" & ""the"" & ""time"" end sub end class", EndOfLine, "class C sub Bar() dim goo = ""now"" & ""is"" & ""the"" & ""time"" end sub end class", "class C sub Bar() dim goo = ""now"" & ""is"" & ""the"" & ""time"" end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestAddition_Beginning() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() dim goo = [||]""now"" & ""is"" & ""the"" & ""time"" end sub end class", "class C sub Bar() dim goo = ""now"" _ & ""is"" _ & ""the"" _ & ""time"" end sub end class", "class C sub Bar() dim goo = ""now"" _ & ""is"" _ & ""the"" _ & ""time"" end sub end class") End Function <WorkItem(34127, "https://github.com/dotnet/roslyn/issues/34127")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsWrapping)> Public Async Function TestWrapLowerPrecedenceInLargeBinary() As Task Await TestAllWrappingCasesAsync( "class C sub Bar() dim goo = [||]a + b + c + d = x * y * z end sub end class", "class C sub Bar() dim goo = a + b + c + d _ = x * y * z end sub end class", "class C sub Bar() dim goo = a + b + c + d _ = x * y * z end sub end class") End Function End Class End Namespace
-1
dotnet/roslyn
54,988
Fix 'rename' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-20T19:57:06Z
2021-07-20T23:10:00Z
32b7a6bd898f4ae581f5c796309b2a082361af27
e5abd89899bef647357359e7680c528a4417ce86
Fix 'rename' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/IntegrationTest/TestUtilities/OutOfProcess/EncapsulateField_OutOfProc.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.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class EncapsulateField_OutOfProc : OutOfProcComponent { public string DialogName = "Preview Changes - Encapsulate Field"; public EncapsulateField_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.E, ShiftState.Ctrl)); } }
// Licensed to the .NET Foundation under one or more 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.IntegrationTest.Utilities.Input; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.OutOfProcess { public class EncapsulateField_OutOfProc : OutOfProcComponent { public string DialogName = "Preview Changes - Encapsulate Field"; public EncapsulateField_OutOfProc(VisualStudioInstance visualStudioInstance) : base(visualStudioInstance) { } public void Invoke() => VisualStudioInstance.Editor.SendKeys(new KeyPress(VirtualKey.R, ShiftState.Ctrl), new KeyPress(VirtualKey.E, ShiftState.Ctrl)); } }
-1